910ba465d7
Voice Room lets humans talk with agents via Whisper/TTS; chat typing no longer blocked by a full-screen overlay, attachments/avatars are larger, and Settings exposes five vivid mid-dark cyan/blue themes for the whole cockpit.
880 lines
31 KiB
JavaScript
880 lines
31 KiB
JavaScript
/** Foodlinkk War Room — tab + popup (stream, emoji, files) */
|
|
window.WarRoomHub = (function () {
|
|
var EMOJIS = ['😀','😂','🙂','😉','😍','🤝','👍','👎','🙏','🔥','✅','❌','⚠️','💡','📎','📦','🚀','💬','🧠','☕','💪','🎯','📊','🧾','🇳🇱','🌍'];
|
|
|
|
function openPopup(roomQuery) {
|
|
var url = '/agents/warroom/popup' + (roomQuery || '');
|
|
var w = window.open(url, 'flk-warroom', 'width=980,height=780,menubar=no,toolbar=no,location=no,status=no');
|
|
if (w) try { w.focus(); } catch (e) {}
|
|
return w;
|
|
}
|
|
|
|
function warRoomController(opts) {
|
|
opts = opts || {};
|
|
return {
|
|
popupMode: !!opts.popupMode,
|
|
souls: [],
|
|
rooms: [],
|
|
room: null,
|
|
messages: [],
|
|
draft: '',
|
|
busy: false,
|
|
me: { username: '', avatar_url: '', role: '' },
|
|
lastId: 0,
|
|
_poll: null,
|
|
_polling: false,
|
|
status: '',
|
|
emojiOpen: false,
|
|
mentionOpen: false,
|
|
mentionQuery: '',
|
|
mentionIndex: 0,
|
|
emojis: EMOJIS,
|
|
pendingFiles: [],
|
|
typing: null, // { agent_key, display_name, text }
|
|
callOpen: false,
|
|
callBusy: false,
|
|
callUrl: '',
|
|
callSlug: '',
|
|
voiceRecording: false,
|
|
voiceBusy: false,
|
|
speakReplies: true,
|
|
voiceRoomOpen: false,
|
|
voiceRoomAgents: ['herman'],
|
|
voiceSpeakingKey: '',
|
|
voiceLastHeard: '',
|
|
_voiceRec: null,
|
|
_voiceStream: null,
|
|
_voiceChunks: null,
|
|
|
|
async init() {
|
|
this.voiceRoomOpen = false;
|
|
this.busy = false;
|
|
await Promise.all([this.loadMe(), this.loadSouls(), this.loadRooms()]);
|
|
var params = new URLSearchParams(window.location.search || '');
|
|
var want = params.get('room');
|
|
if (want) await this.openRoom(parseInt(want, 10));
|
|
else {
|
|
var wr = (this.rooms || []).find(function (r) { return r.kind === 'warroom'; });
|
|
if (wr) await this.openRoom(wr.id);
|
|
else if (this.rooms.length) await this.openRoom(this.rooms[0].id);
|
|
}
|
|
this.startPoll();
|
|
},
|
|
|
|
destroy() {
|
|
if (this._poll) clearInterval(this._poll);
|
|
if (this._continueTimer) clearTimeout(this._continueTimer);
|
|
},
|
|
|
|
async loadMe() {
|
|
try {
|
|
var r = await fetch('/api/auth/me').then(function (x) { return x.json(); });
|
|
var u = r.user || r || {};
|
|
this.me = {
|
|
username: u.username || '',
|
|
avatar_url: u.avatar_url || '',
|
|
role: u.role || '',
|
|
};
|
|
} catch (e) {
|
|
this.me = { username: '', avatar_url: '', role: '' };
|
|
}
|
|
},
|
|
|
|
async loadSouls() {
|
|
try {
|
|
var r = await fetch('/api/agents/souls').then(function (x) { return x.json(); });
|
|
this.souls = (r.items || r.souls || r || []).filter(function (s) { return s.is_active !== false; });
|
|
} catch (e) {
|
|
this.souls = [];
|
|
}
|
|
this.$nextTick(function () { this.paintAvatars(); }.bind(this));
|
|
},
|
|
|
|
async loadRooms() {
|
|
try {
|
|
var r = await fetch('/api/agents/warroom/rooms').then(function (x) { return x.json(); });
|
|
this.rooms = r.items || [];
|
|
} catch (e) {
|
|
this.rooms = [];
|
|
}
|
|
},
|
|
|
|
warroomRoom() {
|
|
return (this.rooms || []).find(function (r) { return r.kind === 'warroom'; }) || null;
|
|
},
|
|
|
|
async openWarroom() {
|
|
var wr = this.warroomRoom();
|
|
if (wr) return this.openRoom(wr.id);
|
|
await this.loadRooms();
|
|
wr = this.warroomRoom();
|
|
if (wr) return this.openRoom(wr.id);
|
|
},
|
|
|
|
async openDm(agentKey) {
|
|
if (this.busy) return;
|
|
this.busy = true;
|
|
try {
|
|
var r = await Cockpit.api('/api/agents/warroom/rooms/dm/' + encodeURIComponent(agentKey), {
|
|
method: 'POST',
|
|
body: '{}',
|
|
});
|
|
await this.loadRooms();
|
|
if (r.room) await this.openRoom(r.room.id);
|
|
} catch (e) {
|
|
if (window.Cockpit) Cockpit.toast(e.message || 'DM openen mislukt', 'error');
|
|
}
|
|
this.busy = false;
|
|
},
|
|
|
|
async openRoom(id) {
|
|
if (!id) return;
|
|
this.busy = true;
|
|
this.status = '';
|
|
this.typing = null;
|
|
try {
|
|
var r = await fetch('/api/agents/warroom/rooms/' + id + '/messages?limit=120').then(function (x) {
|
|
return x.json();
|
|
});
|
|
this.room = r.room;
|
|
this.messages = this.normalizeList(r.items || []);
|
|
this.lastId = this.maxId(this.messages);
|
|
this.$nextTick(function () {
|
|
this.paintAvatars();
|
|
this.scrollLog();
|
|
}.bind(this));
|
|
var last = (this.messages || [])[(this.messages || []).length - 1];
|
|
if (last && last.sender_type === 'agent' && this.room && this.room.kind === 'warroom') {
|
|
this.scheduleContinue(4000);
|
|
}
|
|
} catch (e) {
|
|
this.status = e.message || 'Laden mislukt';
|
|
}
|
|
this.busy = false;
|
|
},
|
|
|
|
normalizeList(items) {
|
|
return (items || []).map(function (m) {
|
|
if (m && typeof m.metadata === 'string') {
|
|
try { m.metadata = JSON.parse(m.metadata); } catch (e) { m.metadata = {}; }
|
|
}
|
|
return m;
|
|
});
|
|
},
|
|
|
|
maxId(items) {
|
|
var n = 0;
|
|
(items || []).forEach(function (m) {
|
|
var id = Number(m && m.id);
|
|
if (!isNaN(id) && id > n) n = id;
|
|
});
|
|
return n;
|
|
},
|
|
|
|
paintAvatars() {
|
|
if (!window.AgentAvatars) return;
|
|
var root = this.$root || document;
|
|
root.querySelectorAll('.wr-roster [data-agent-avatar], .wr-log [data-agent-avatar]').forEach(function (el) {
|
|
AgentAvatars.paint(el, el.getAttribute('data-agent-avatar'), el.getAttribute('data-agent-color'));
|
|
});
|
|
},
|
|
|
|
upsertMessage(msg) {
|
|
if (!msg || msg.id == null) return false;
|
|
var list = this.messages || [];
|
|
var idx = list.findIndex(function (m) { return String(m.id) === String(msg.id); });
|
|
if (idx >= 0) {
|
|
list[idx] = msg;
|
|
this.messages = list.slice();
|
|
} else {
|
|
this.messages = list.concat([msg]);
|
|
}
|
|
var idn = Number(msg.id);
|
|
if (!isNaN(idn) && idn > (this.lastId || 0)) this.lastId = idn;
|
|
return true;
|
|
},
|
|
|
|
mergeMessages(items) {
|
|
var changed = false;
|
|
var self = this;
|
|
this.normalizeList(items || []).forEach(function (m) {
|
|
if (self.upsertMessage(m)) changed = true;
|
|
});
|
|
return changed;
|
|
},
|
|
|
|
scrollLog() {
|
|
var el = this.$refs && this.$refs.wrLog;
|
|
if (el) el.scrollTop = el.scrollHeight;
|
|
},
|
|
|
|
startPoll() {
|
|
var self = this;
|
|
if (this._poll) clearInterval(this._poll);
|
|
this._poll = setInterval(function () { self.pollNew(); }, 4000);
|
|
},
|
|
|
|
async pollNew() {
|
|
// Cruciaal: niet pollen tijdens send/stream → voorkomt dubbele user-bubbles
|
|
if (!this.room || this._polling || this.busy) return;
|
|
this._polling = true;
|
|
try {
|
|
var url =
|
|
'/api/agents/warroom/rooms/' +
|
|
this.room.id +
|
|
'/messages?limit=50&after_id=' +
|
|
(this.lastId || 0);
|
|
var r = await fetch(url).then(function (x) { return x.json(); });
|
|
this.removeDeletedIds(r.deleted_ids || []);
|
|
if (this.mergeMessages(r.items || [])) {
|
|
this.$nextTick(function () {
|
|
this.paintAvatars();
|
|
this.scrollLog();
|
|
}.bind(this));
|
|
}
|
|
} catch (e) { /* quiet */ }
|
|
this._polling = false;
|
|
},
|
|
|
|
attachmentsOf(m) {
|
|
var meta = (m && m.metadata) || {};
|
|
return meta.attachments || [];
|
|
},
|
|
|
|
isImage(att) {
|
|
var mime = (att && att.mime) || '';
|
|
var name = ((att && att.name) || '').toLowerCase();
|
|
return mime.indexOf('image/') === 0 || /\.(png|jpe?g|gif|webp)$/.test(name);
|
|
},
|
|
|
|
insertEmoji(em) {
|
|
this.draft = (this.draft || '') + em;
|
|
this.emojiOpen = false;
|
|
},
|
|
|
|
insertMention(key) {
|
|
var d = this.draft || '';
|
|
var at = d.lastIndexOf('@');
|
|
if (at >= 0 && !/\s/.test(d.slice(at + 1))) {
|
|
// replace partial @query
|
|
this.draft = d.slice(0, at) + '@' + key + ' ';
|
|
} else {
|
|
this.draft = d + (d && !/\s$/.test(d) ? ' ' : '') + '@' + key + ' ';
|
|
}
|
|
this.mentionOpen = false;
|
|
this.mentionQuery = '';
|
|
this.mentionIndex = 0;
|
|
this.$nextTick(function () {
|
|
var el = this.$refs && this.$refs.wrInput;
|
|
if (el) { el.focus(); el.setSelectionRange(this.draft.length, this.draft.length); }
|
|
}.bind(this));
|
|
},
|
|
|
|
mentionSuggestions() {
|
|
if (!this.mentionOpen) return [];
|
|
var q = (this.mentionQuery || '').toLowerCase();
|
|
return (this.souls || []).filter(function (s) {
|
|
if (!s || !s.agent_key) return false;
|
|
if (!q) return true;
|
|
var key = String(s.agent_key).toLowerCase();
|
|
var name = String(s.display_name || '').toLowerCase();
|
|
return key.indexOf(q) === 0 || key.indexOf(q) >= 0 || name.indexOf(q) >= 0;
|
|
}).slice(0, 8);
|
|
},
|
|
|
|
onDraftInput() {
|
|
var d = this.draft || '';
|
|
var m = /(^|\s)@([a-zA-Z0-9_-]*)$/.exec(d);
|
|
if (m) {
|
|
this.mentionOpen = true;
|
|
this.mentionQuery = m[2] || '';
|
|
this.mentionIndex = 0;
|
|
} else {
|
|
this.mentionOpen = false;
|
|
this.mentionQuery = '';
|
|
}
|
|
},
|
|
|
|
pickMention(s) {
|
|
if (!s) return;
|
|
this.insertMention(s.agent_key);
|
|
},
|
|
|
|
/** Roster: in #war-room → @tag; anders open DM */
|
|
selectAgent(agentKey) {
|
|
if (this.room && this.room.kind === 'warroom') {
|
|
this.insertMention(agentKey);
|
|
return;
|
|
}
|
|
this.openDm(agentKey);
|
|
},
|
|
|
|
|
|
async onPickFiles(ev) {
|
|
var files = Array.prototype.slice.call((ev.target && ev.target.files) || []);
|
|
if (ev.target) ev.target.value = '';
|
|
for (var i = 0; i < files.length; i++) {
|
|
await this.uploadFile(files[i]);
|
|
}
|
|
},
|
|
|
|
async uploadFile(file) {
|
|
if (!file) return;
|
|
this.status = 'Uploaden…';
|
|
try {
|
|
var fd = new FormData();
|
|
fd.append('file', file);
|
|
var resp = await fetch('/api/agents/warroom/upload', { method: 'POST', body: fd, credentials: 'same-origin' });
|
|
var data = await resp.json().catch(function () { return {}; });
|
|
if (!resp.ok) throw new Error(data.detail || data.message || 'Upload mislukt');
|
|
this.pendingFiles = (this.pendingFiles || []).concat([{
|
|
url: data.url,
|
|
name: data.name || file.name,
|
|
mime: data.mime || file.type,
|
|
size: data.size || file.size || 0,
|
|
}]);
|
|
this.status = '';
|
|
} catch (e) {
|
|
this.status = e.message || 'Upload mislukt';
|
|
if (window.Cockpit) Cockpit.toast(this.status, 'error');
|
|
}
|
|
},
|
|
|
|
removePending(idx) {
|
|
this.pendingFiles = (this.pendingFiles || []).filter(function (_, i) { return i !== idx; });
|
|
},
|
|
|
|
canSend() {
|
|
return !this.busy && this.room && (((this.draft || '').trim()) || (this.pendingFiles || []).length);
|
|
},
|
|
|
|
async send() {
|
|
var text = (this.draft || '').trim();
|
|
var files = (this.pendingFiles || []).slice();
|
|
if (!this.room || this.busy) return;
|
|
if (!text && !files.length) return;
|
|
|
|
this.busy = true;
|
|
this.emojiOpen = false;
|
|
this.draft = '';
|
|
this.pendingFiles = [];
|
|
this.typing = null;
|
|
this.status = 'Verzenden…';
|
|
|
|
try {
|
|
var resp = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/messages/stream', {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
|
|
body: JSON.stringify({ content: text, attachments: files }),
|
|
});
|
|
if (!resp.ok) {
|
|
var err = await resp.json().catch(function () { return {}; });
|
|
throw new Error(err.detail || ('HTTP ' + resp.status));
|
|
}
|
|
await this.consumeStream(resp);
|
|
this.status = '';
|
|
this.scheduleContinue(2000);
|
|
} catch (e) {
|
|
this.draft = text;
|
|
this.pendingFiles = files;
|
|
this.status = e.message || 'Verzenden mislukt';
|
|
if (window.Cockpit) Cockpit.toast(this.status, 'error');
|
|
}
|
|
this.typing = null;
|
|
this.busy = false;
|
|
this.$nextTick(function () {
|
|
this.paintAvatars();
|
|
this.scrollLog();
|
|
}.bind(this));
|
|
},
|
|
|
|
async consumeStream(resp) {
|
|
var reader = resp.body.getReader();
|
|
var decoder = new TextDecoder();
|
|
var buf = '';
|
|
while (true) {
|
|
var chunk = await reader.read();
|
|
if (chunk.done) break;
|
|
buf += decoder.decode(chunk.value, { stream: true });
|
|
var parts = buf.split('\n\n');
|
|
buf = parts.pop() || '';
|
|
for (var i = 0; i < parts.length; i++) {
|
|
this.handleSseBlock(parts[i]);
|
|
}
|
|
}
|
|
if (buf.trim()) this.handleSseBlock(buf);
|
|
},
|
|
|
|
handleSseBlock(block) {
|
|
var lines = (block || '').split('\n');
|
|
var dataLines = [];
|
|
for (var i = 0; i < lines.length; i++) {
|
|
if (lines[i].indexOf('data:') === 0) dataLines.push(lines[i].slice(5).trim());
|
|
}
|
|
if (!dataLines.length) return;
|
|
var raw = dataLines.join('\n');
|
|
var ev;
|
|
try {
|
|
ev = JSON.parse(raw);
|
|
} catch (e) {
|
|
return;
|
|
}
|
|
var type = ev.event || '';
|
|
if (type === 'user' && ev.message) {
|
|
this.upsertMessage(ev.message);
|
|
this.status = 'Agent typt…';
|
|
this.$nextTick(function () { this.scrollLog(); }.bind(this));
|
|
} else if (type === 'continue_start') {
|
|
this.status = 'Agents praten verder over: ' + ((ev.topic || '').slice(0, 80));
|
|
} else if (type === 'typing_start') {
|
|
this.typing = {
|
|
agent_key: ev.agent_key,
|
|
display_name: ev.display_name || ev.agent_key,
|
|
text: '',
|
|
};
|
|
this.status = (this.typing.display_name || 'Agent') + ' typt…';
|
|
this.$nextTick(function () { this.scrollLog(); }.bind(this));
|
|
} else if (type === 'typing') {
|
|
if (!this.typing || this.typing.agent_key !== ev.agent_key) {
|
|
this.typing = {
|
|
agent_key: ev.agent_key,
|
|
display_name: (this.soulFor(ev.agent_key) || {}).display_name || ev.agent_key,
|
|
text: '',
|
|
};
|
|
}
|
|
this.typing.text = (this.typing.text || '') + (ev.delta || '');
|
|
// force alpine refresh
|
|
this.typing = Object.assign({}, this.typing);
|
|
this.$nextTick(function () { this.scrollLog(); }.bind(this));
|
|
} else if (type === 'agent' && ev.message) {
|
|
this.typing = null;
|
|
this.upsertMessage(ev.message);
|
|
if (ev.message.content) this.speakText(ev.message.content, ev.message.agent_key);
|
|
this.$nextTick(function () {
|
|
this.paintAvatars();
|
|
this.scrollLog();
|
|
}.bind(this));
|
|
} else if (type === 'system' && ev.message) {
|
|
this.typing = null;
|
|
this.upsertMessage(ev.message);
|
|
} else if (type === 'error') {
|
|
this.typing = null;
|
|
this.status = ev.detail || 'Streamfout';
|
|
if (window.Cockpit) Cockpit.toast(this.status, 'error');
|
|
} else if (type === 'done') {
|
|
this.typing = null;
|
|
}
|
|
},
|
|
|
|
onKey(e) {
|
|
var sug = this.mentionSuggestions();
|
|
if (this.mentionOpen && sug.length) {
|
|
if (e.key === 'ArrowDown') {
|
|
e.preventDefault();
|
|
this.mentionIndex = (this.mentionIndex + 1) % sug.length;
|
|
return;
|
|
}
|
|
if (e.key === 'ArrowUp') {
|
|
e.preventDefault();
|
|
this.mentionIndex = (this.mentionIndex - 1 + sug.length) % sug.length;
|
|
return;
|
|
}
|
|
if (e.key === 'Enter' || e.key === 'Tab') {
|
|
e.preventDefault();
|
|
this.pickMention(sug[this.mentionIndex] || sug[0]);
|
|
return;
|
|
}
|
|
if (e.key === 'Escape') {
|
|
this.mentionOpen = false;
|
|
return;
|
|
}
|
|
}
|
|
if (e.key === 'Enter' && !e.shiftKey) {
|
|
e.preventDefault();
|
|
this.send();
|
|
}
|
|
},
|
|
|
|
|
|
|
|
scheduleContinue(delayMs) {
|
|
if (!this.autoDebate || !this.room || this.room.kind !== 'warroom') return;
|
|
if (this._continueTimer) clearTimeout(this._continueTimer);
|
|
var self = this;
|
|
this._continueTimer = setTimeout(function () { self.runContinue(2); }, delayMs || 2500);
|
|
},
|
|
|
|
async runContinue(turns) {
|
|
if (!this.autoDebate || !this.room || this.room.kind !== 'warroom') return;
|
|
if (this.busy || this._continueBusy) return;
|
|
// only continue if last message is from an agent (they are mid-debate)
|
|
var last = (this.messages || [])[(this.messages || []).length - 1];
|
|
if (!last || last.sender_type !== 'agent') return;
|
|
|
|
this._continueBusy = true;
|
|
this.status = 'Agents overleggen verder…';
|
|
try {
|
|
var resp = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/continue?turns=' + (turns || 2), {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: { Accept: 'text/event-stream', 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
});
|
|
if (!resp.ok) throw new Error('Continue mislukt');
|
|
this.busy = true;
|
|
await this.consumeStream(resp);
|
|
this.busy = false;
|
|
this.status = '';
|
|
// keep the debate alive a bit while the tab is open
|
|
this.scheduleContinue(12000);
|
|
} catch (e) {
|
|
this.busy = false;
|
|
this.status = '';
|
|
}
|
|
this._continueBusy = false;
|
|
},
|
|
|
|
async deleteMessage(m) {
|
|
if (!this.room || !m || !m.id) return;
|
|
if (!window.confirm('Bericht verwijderen?')) return;
|
|
try {
|
|
var r = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/messages/' + m.id, {
|
|
method: 'DELETE',
|
|
credentials: 'same-origin',
|
|
}).then(function (x) { return x.json().then(function (d) { return { ok: x.ok, d: d }; }); });
|
|
if (!r.ok) throw new Error((r.d && (r.d.detail || r.d.message)) || 'Verwijderen mislukt');
|
|
this.messages = (this.messages || []).filter(function (x) { return x.id !== m.id; });
|
|
if (window.Cockpit) Cockpit.toast('Bericht verwijderd', 'ok');
|
|
} catch (e) {
|
|
if (window.Cockpit) Cockpit.toast(e.message || 'Verwijderen mislukt', 'error');
|
|
}
|
|
},
|
|
|
|
removeDeletedIds(ids) {
|
|
if (!ids || !ids.length) return;
|
|
var set = {};
|
|
ids.forEach(function (id) { set[id] = true; });
|
|
this.messages = (this.messages || []).filter(function (m) { return !set[m.id]; });
|
|
},
|
|
|
|
|
|
|
|
openVoiceRoom() {
|
|
if (!this.room) {
|
|
if (window.Cockpit) Cockpit.toast('Geen room geladen', 'error');
|
|
return;
|
|
}
|
|
if (!(this.voiceRoomAgents || []).length) {
|
|
this.voiceRoomAgents = ['herman'];
|
|
}
|
|
this.speakReplies = true;
|
|
this.voiceRoomOpen = true;
|
|
this.callOpen = false;
|
|
this.status = 'Voice Room open — houd 🎤 in om te praten';
|
|
this._announceVoiceRoom('join');
|
|
if (this.micNeedsHttps()) {
|
|
// still open UI; mic will prompt on first PTT
|
|
this.status = 'Voice Room open — voor mic: gebruik HTTPS (:8643)';
|
|
}
|
|
},
|
|
|
|
closeVoiceRoom() {
|
|
if (this.voiceRecording) {
|
|
try { this.stopVoiceTalk(); } catch (e) {}
|
|
}
|
|
if (window.speechSynthesis) try { window.speechSynthesis.cancel(); } catch (e2) {}
|
|
this.voiceRoomOpen = false;
|
|
this.voiceSpeakingKey = '';
|
|
this._announceVoiceRoom('leave');
|
|
if (this.status && String(this.status).indexOf('Voice') === 0) this.status = '';
|
|
},
|
|
|
|
async _announceVoiceRoom(action) {
|
|
if (!this.room) return;
|
|
try {
|
|
await fetch('/api/agents/warroom/rooms/' + this.room.id + '/voice-room', {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ action: action || 'join', agents: this.voiceRoomAgents || [] }),
|
|
});
|
|
await this.pollNew();
|
|
} catch (e) { /* quiet */ }
|
|
},
|
|
|
|
toggleVoiceAgent(key) {
|
|
var list = (this.voiceRoomAgents || []).slice();
|
|
var i = list.indexOf(key);
|
|
if (i >= 0) {
|
|
if (list.length <= 1) return; // keep at least one
|
|
list.splice(i, 1);
|
|
} else {
|
|
list.push(key);
|
|
}
|
|
this.voiceRoomAgents = list;
|
|
},
|
|
|
|
isVoiceAgent(key) {
|
|
return (this.voiceRoomAgents || []).indexOf(key) >= 0;
|
|
},
|
|
|
|
voiceAgentSouls() {
|
|
var souls = (this.souls || []).slice();
|
|
if (!souls.length) {
|
|
return (this.voiceRoomAgents || ['herman']).map(function (k) {
|
|
return { agent_key: k, display_name: k };
|
|
});
|
|
}
|
|
var prefer = ['herman','retail','bizdev','halal','finance','marketing','legal'];
|
|
souls.sort(function (a, b) {
|
|
var ia = prefer.indexOf(a.agent_key); var ib = prefer.indexOf(b.agent_key);
|
|
if (ia < 0) ia = 99; if (ib < 0) ib = 99;
|
|
return ia - ib || String(a.display_name||'').localeCompare(String(b.display_name||''));
|
|
});
|
|
return souls.slice(0, 12);
|
|
},
|
|
|
|
secureWarroomUrl() {
|
|
try {
|
|
var u = new URL(window.location.href);
|
|
if (u.protocol === 'https:') {
|
|
if (u.pathname.indexOf('/agents') === 0 && u.search.indexOf('tab=') < 0) {
|
|
u.searchParams.set('tab', 'warroom');
|
|
}
|
|
return u.toString();
|
|
}
|
|
u.protocol = 'https:';
|
|
if (u.port === '8610' || u.port === '8600') u.port = '8643';
|
|
else if (!u.port || u.port === '80') u.port = '8643';
|
|
if (u.pathname.indexOf('/warroom/popup') >= 0) {
|
|
/* keep popup path */
|
|
} else {
|
|
u.pathname = '/agents';
|
|
u.searchParams.set('tab', 'warroom');
|
|
}
|
|
return u.toString();
|
|
} catch (e) {
|
|
return 'https://10.4.7.18:8643/agents?tab=warroom';
|
|
}
|
|
},
|
|
|
|
micNeedsHttps() {
|
|
return !(window.isSecureContext && navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
|
|
},
|
|
|
|
async ensureMic() {
|
|
if (!this.micNeedsHttps()) return true;
|
|
this.status = 'Microfoon vereist HTTPS — open veilige War Room';
|
|
if (window.Cockpit) {
|
|
Cockpit.toast('Mic werkt niet op HTTP. Open HTTPS War Room.', 'error');
|
|
}
|
|
var url = this.secureWarroomUrl();
|
|
var go = window.confirm('Spraak met agents werkt via HTTPS.\n\nNu openen?\n' + url);
|
|
if (go) window.open(url, '_blank');
|
|
return false;
|
|
},
|
|
|
|
async startVoiceTalk(ev) {
|
|
if (ev) { try { ev.preventDefault(); } catch (e0) {} }
|
|
if (this.voiceRecording || this.voiceBusy || this.busy) return;
|
|
if (!this.voiceRoomOpen) this.openVoiceRoom();
|
|
if (!(await this.ensureMic())) return;
|
|
try {
|
|
this._voiceChunks = [];
|
|
this._voiceStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
var rec = new MediaRecorder(this._voiceStream);
|
|
this._voiceRec = rec;
|
|
var self = this;
|
|
rec.ondataavailable = function (e) {
|
|
if (e.data && e.data.size) self._voiceChunks.push(e.data);
|
|
};
|
|
rec.start(200);
|
|
this.voiceRecording = true;
|
|
this.status = '🎤 Luisteren… laat los om te sturen';
|
|
} catch (e) {
|
|
this.status = 'Microfoon geweigerd of niet beschikbaar';
|
|
if (window.Cockpit) Cockpit.toast(this.status, 'error');
|
|
this._stopVoiceStream();
|
|
}
|
|
},
|
|
|
|
async stopVoiceTalk(ev) {
|
|
if (ev) { try { ev.preventDefault(); } catch (e0) {} }
|
|
if (!this.voiceRecording || !this._voiceRec) return;
|
|
var self = this;
|
|
this.voiceRecording = false;
|
|
this.voiceBusy = true;
|
|
this.status = 'Spraak omzetten…';
|
|
await new Promise(function (resolve) {
|
|
self._voiceRec.onstop = function () { resolve(); };
|
|
try { self._voiceRec.stop(); } catch (e1) { resolve(); }
|
|
});
|
|
this._stopVoiceStream();
|
|
try {
|
|
var blob = new Blob(this._voiceChunks || [], { type: 'audio/webm' });
|
|
this._voiceChunks = [];
|
|
if (!blob.size) throw new Error('Geen audio opgenomen');
|
|
var fd = new FormData();
|
|
fd.append('file', blob, 'warroom-voice.webm');
|
|
var r = await fetch('/api/voice/transcribe', { method: 'POST', body: fd, credentials: 'same-origin' });
|
|
var j = await r.json().catch(function () { return {}; });
|
|
if (!r.ok) throw new Error(j.detail || j.error || 'Transcriptie mislukt');
|
|
var text = (j.text || '').trim();
|
|
if (!text) throw new Error('Geen spraak herkend — probeer opnieuw');
|
|
// Stuur naar War Room (agents antwoorden zoals bij typen)
|
|
this.voiceLastHeard = text;
|
|
var tags = (this.voiceRoomAgents || ['herman']).map(function (k) { return '@' + k; });
|
|
// Mention selected voice-room agents so they all can answer
|
|
var missing = tags.filter(function (t) { return text.toLowerCase().indexOf(t) < 0; });
|
|
if (missing.length) text = missing.join(' ') + ' ' + text;
|
|
this.draft = text;
|
|
this.status = 'Versturen naar Voice Room…';
|
|
if (this.voiceRoomOpen) this.voiceSpeakingKey = '';
|
|
await this.send();
|
|
this.status = this.voiceRoomOpen ? 'Voice Room — wachten op agents…' : '';
|
|
} catch (e) {
|
|
this.status = e.message || 'Voice mislukt';
|
|
if (window.Cockpit) Cockpit.toast(this.status, 'error');
|
|
}
|
|
this.voiceBusy = false;
|
|
},
|
|
|
|
_stopVoiceStream() {
|
|
try { if (this._voiceRec && this._voiceRec.state !== 'inactive') this._voiceRec.stop(); } catch (e) {}
|
|
this._voiceRec = null;
|
|
if (this._voiceStream) {
|
|
try { this._voiceStream.getTracks().forEach(function (t) { t.stop(); }); } catch (e2) {}
|
|
}
|
|
this._voiceStream = null;
|
|
},
|
|
|
|
speakText(text, agentKey) {
|
|
if (!this.speakReplies || !text || !window.speechSynthesis) return;
|
|
try {
|
|
window.speechSynthesis.cancel();
|
|
var self = this;
|
|
this.voiceSpeakingKey = agentKey || 'agent';
|
|
var u = new SpeechSynthesisUtterance(String(text).slice(0, 900));
|
|
u.lang = 'nl-NL';
|
|
u.rate = 1.02;
|
|
var voices = window.speechSynthesis.getVoices() || [];
|
|
var nl = voices.find(function (v) { return /nl/i.test(v.lang) && /google|microsoft|maarten|xander|neder/i.test(v.name); })
|
|
|| voices.find(function (v) { return /nl/i.test(v.lang); });
|
|
if (nl) u.voice = nl;
|
|
u.onend = function () {
|
|
if (self.voiceSpeakingKey === (agentKey || 'agent')) self.voiceSpeakingKey = '';
|
|
if (self.voiceRoomOpen) self.status = 'Voice Room — jouw beurt (houd 🎤 in)';
|
|
};
|
|
window.speechSynthesis.speak(u);
|
|
if (this.voiceRoomOpen) {
|
|
this.status = (agentKey || 'Agent') + ' spreekt…';
|
|
}
|
|
} catch (e) { /* ignore */ }
|
|
},
|
|
|
|
|
|
callHref() {
|
|
var id = (this.room && this.room.id) ? this.room.id : 1;
|
|
var slug = 'FoodlinkkWR' + id;
|
|
if (this.room && this.room.kind === 'dm' && this.room.agent_key) {
|
|
slug = 'FoodlinkkDM' + this.room.agent_key + id;
|
|
}
|
|
return 'https://meet.ffmuc.net/' + slug;
|
|
},
|
|
|
|
onCallClick() {
|
|
// Runs in the same user-gesture as the <a> navigation — always show panel.
|
|
var url = this.callHref();
|
|
this.callUrl = url;
|
|
this.callSlug = url.split('/').pop();
|
|
this.callOpen = true;
|
|
this.status = 'Call open — nieuw tabblad of klik Deelnemen';
|
|
this.announceCall(url);
|
|
},
|
|
|
|
async announceCall(url) {
|
|
if (!this.room || this.callBusy) return;
|
|
this.callBusy = true;
|
|
try {
|
|
var r = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/call', {
|
|
method: 'POST',
|
|
credentials: 'same-origin',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
}).then(function (x) { return x.json().then(function (d) { return { ok: x.ok, d: d }; }); });
|
|
if (r.ok && r.d && r.d.url) {
|
|
this.callUrl = r.d.url;
|
|
this.callSlug = r.d.slug || this.callSlug;
|
|
}
|
|
await this.pollNew();
|
|
} catch (e) {
|
|
/* panel + tab already useful without announce */
|
|
}
|
|
this.callBusy = false;
|
|
},
|
|
|
|
async startCall() {
|
|
// Fallback if something still calls startCall()
|
|
this.onCallClick();
|
|
var url = this.callUrl || this.callHref();
|
|
window.open(url, '_blank');
|
|
},
|
|
|
|
closeCall() {
|
|
this.callOpen = false;
|
|
if (this.status && String(this.status).indexOf('Call') === 0) this.status = '';
|
|
},
|
|
|
|
openCallExternal() {
|
|
var url = this.callUrl || this.callHref();
|
|
window.open(url, '_blank');
|
|
},
|
|
|
|
async copyCallLink() {
|
|
var link = (this.callUrl || this.callHref()).split('#')[0];
|
|
try {
|
|
await navigator.clipboard.writeText(link);
|
|
if (window.Cockpit) Cockpit.toast('Link gekopieerd', 'ok');
|
|
} catch (e) {
|
|
window.prompt('Kopieer deze call-link:', link);
|
|
}
|
|
},
|
|
|
|
popOut() {
|
|
var q = this.room ? '?room=' + this.room.id : '';
|
|
openPopup(q);
|
|
},
|
|
|
|
soulFor(key) {
|
|
return (this.souls || []).find(function (s) { return s.agent_key === key; }) || null;
|
|
},
|
|
|
|
labelForMessage(m) {
|
|
if (m.sender_type === 'user') return m.username || this.me.username || 'Jij';
|
|
if (m.sender_type === 'agent') {
|
|
var s = this.soulFor(m.agent_key);
|
|
return (s && s.display_name) || m.agent_key || 'Agent';
|
|
}
|
|
return 'Systeem';
|
|
},
|
|
};
|
|
}
|
|
|
|
return { openPopup: openPopup, controller: warRoomController };
|
|
})();
|
|
|
|
function __flkRegisterWarRoomAlpine() {
|
|
if (!window.Alpine || typeof Alpine.data !== 'function') return;
|
|
if (Alpine.__flkWarRoomRegistered) return;
|
|
Alpine.data('warRoomHub', function () {
|
|
return WarRoomHub.controller({ popupMode: false });
|
|
});
|
|
Alpine.data('warRoomPopup', function () {
|
|
return WarRoomHub.controller({ popupMode: true });
|
|
});
|
|
Alpine.__flkWarRoomRegistered = true;
|
|
}
|
|
document.addEventListener('alpine:init', __flkRegisterWarRoomAlpine);
|
|
__flkRegisterWarRoomAlpine();
|