Files
foodlinkk-command-center/cockpit/static/js/agents-warroom.js
T

1340 lines
48 KiB
JavaScript
Raw Normal View History

/** 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: [],
chatSearch: '',
searchOpen: false,
toolsOpen: false,
screenCleared: false,
autoDebate: true,
ceoInboxOpen: false,
ceoInbox: [],
ceoUnread: 0,
replyTo: null,
replyHighlightId: null,
stickToBottom: true,
showJumpLatest: false,
_typingScrollAt: 0,
rosterCollapsed: true,
a2aPausedUntil: 0,
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: false,
voiceRoomOpen: false,
voiceRoomAgents: ['herman', 'bizdev', 'finance', 'retail', 'marketing'],
voiceSpeakingKey: '',
voiceLastHeard: '',
_voiceRec: null,
_voiceStream: null,
_voiceChunks: null,
async init() {
this.voiceRoomOpen = false;
this.busy = false;
this._sendLock = 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);
}
try {
var saved = localStorage.getItem('flk-warroom-a2a');
this.autoDebate = (saved === null || saved === '1' || saved === 'true');
} catch (e) { this.autoDebate = true; }
this.startPoll();
this.loadCeoInbox();
if (this.autoDebate && this.room && this.room.kind === 'warroom') this.scheduleContinue(60000);
},
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;
id = parseInt(id, 10);
this.busy = true;
this.status = '';
this.typing = null;
try {
if (!(this.rooms || []).length) await this.loadRooms();
var meta = (this.rooms || []).find(function (r) { return Number(r.id) === id; }) || null;
var r = await fetch('/api/agents/warroom/rooms/' + id + '/messages?limit=120').then(function (x) {
return x.json();
});
// messages API returns {items}, NOT {room} — keep room from rooms list
this.room = meta || r.room || { id: id, kind: 'warroom', title: 'War Room' };
this.messages = this.normalizeList(r.items || []);
this.lastId = this.maxId(this.messages);
this.stickToBottom = true;
this.showJumpLatest = false;
this.$nextTick(function () {
this.paintAvatars();
this.scrollLog(true);
this.focusComposer();
}.bind(this));
var last = (this.messages || [])[(this.messages || []).length - 1];
if (last && last.sender_type === 'agent' && this.room && this.room.kind === 'warroom') {
if (this.autoDebate) this.scheduleContinue(60000);
}
} catch (e) {
this.status = e.message || 'Laden mislukt';
// Still keep a usable room id so send works
if (!this.room) this.room = { id: id, kind: 'warroom', title: 'War Room' };
}
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;
},
isNearBottom(el, px) {
if (!el) return true;
var gap = el.scrollHeight - el.scrollTop - el.clientHeight;
return gap <= (px == null ? 80 : px);
},
onLogScroll() {
var el = this.$refs && this.$refs.wrLog;
if (!el) return;
var near = this.isNearBottom(el, 100);
this.stickToBottom = near;
this.showJumpLatest = !near;
},
scrollLog(force) {
var el = this.$refs && this.$refs.wrLog;
if (!el) return;
if (!force && !this.stickToBottom) {
this.showJumpLatest = true;
return;
}
el.scrollTop = el.scrollHeight;
this.stickToBottom = true;
this.showJumpLatest = false;
},
jumpToLatest() {
this.stickToBottom = true;
this.showJumpLatest = false;
this.scrollLog(true);
},
startPoll() {
var selfCeo = this;
if (!this._ceoPoll) {
this._ceoPoll = setInterval(function () { selfCeo.loadCeoInbox(); }, 20000);
}
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() {
if ((this.draft || '').trim()) this.pauseA2A(90000);
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; });
},
focusComposer() {
try {
var el = this.$refs && this.$refs.wrInput;
if (el) {
el.removeAttribute('disabled');
el.readOnly = false;
el.focus();
}
} catch (e) {}
},
canSend() {
var hasText = !!(this.draft || '').trim();
var hasFiles = !!(this.pendingFiles || []).length;
return !!(hasText || hasFiles);
},
async ensureRoom() {
if (this.room && this.room.id) return true;
try {
await this.loadRooms();
var wr = this.warroomRoom();
if (wr) {
await this.openRoom(wr.id);
} else {
// fallback: known warroom id 1
await this.openRoom(1);
}
} catch (e) {}
return !!(this.room && this.room.id);
},
onEnter(e) {
if (e && e.shiftKey) return; // Shift+Enter = nieuwe regel
if (this.mentionOpen) {
var sug = this.mentionSuggestions();
if (sug && sug.length) {
if (e) e.preventDefault();
this.pickMention(sug[this.mentionIndex] || sug[0]);
return;
}
}
if (e) e.preventDefault();
this.send();
},
async send() {
var text = (this.draft || '').trim();
var files = (this.pendingFiles || []).slice();
if (!text && !files.length) return;
// Never get stuck behind a stale busy flag
if (this._sendLock) return;
this._sendLock = true;
this.busy = true;
this.mentionOpen = false;
this.emojiOpen = false;
var okRoom = await this.ensureRoom();
if (!okRoom) {
this.busy = false;
this._sendLock = false;
this.status = 'Room niet geladen — klik ↻';
if (window.Cockpit) Cockpit.toast(this.status, 'error');
return;
}
// Instant UI — no waiting for network/LLM
var tempId = 'local-' + Date.now();
var replySnapshot = this.replyTo ? {
id: this.replyTo.id,
agent_key: this.replyTo.agent_key,
username: this.replyTo.username,
sender_type: this.replyTo.sender_type,
excerpt: this.replyTo.excerpt,
label: this.replyTo.label,
} : null;
var replyToId = replySnapshot ? replySnapshot.id : null;
var optimisticMeta = {};
if (files.length) optimisticMeta.attachments = files;
if (replySnapshot) optimisticMeta.reply_to = replySnapshot;
var optimistic = {
id: tempId,
room_id: this.room.id,
sender_type: 'user',
content: text || (files.length ? '(bijlage)' : ''),
username: (this.me && this.me.username) || 'Jij',
sender_avatar_url: (this.me && this.me.avatar_url) || null,
metadata: optimisticMeta,
created_at: new Date().toISOString(),
};
this.draft = '';
this.pendingFiles = [];
this.replyTo = null;
this.replyHighlightId = replyToId;
this.pauseA2A(90000);
this.typing = null;
this.upsertMessage(optimistic);
this.status = '';
this.stickToBottom = true;
this.$nextTick(function () {
this.scrollLog(true);
this.focusComposer();
}.bind(this));
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, reply_to_id: replyToId }),
});
if (!resp.ok) {
var err = await resp.json().catch(function () { return {}; });
throw new Error(err.detail || ('HTTP ' + resp.status));
}
await this.consumeStream(resp);
// Drop temp bubble if server user msg arrived with real id
this.messages = (this.messages || []).filter(function (m) {
return m.id !== tempId;
});
// Herlaad recente geschiedenis (merge) zodat reply-parent niet "kwijt" raakt in de UI
await this.refreshMessages({ silent: true });
if (replyToId) {
var self = this;
this.$nextTick(function () {
self.scrollToMessage(replyToId);
setTimeout(function () { self.replyHighlightId = null; }, 4000);
});
}
if (this.autoDebate) this.scheduleContinue(60000);
} catch (e) {
// Keep optimistic message; restore draft only on hard fail
this.status = e.message || 'Verzenden mislukt';
if (window.Cockpit) Cockpit.toast(this.status, 'error');
}
this.typing = null;
this.busy = false;
this._sendLock = false;
this.$nextTick(function () {
this.paintAvatars();
this.scrollLog(true);
this.focusComposer();
}.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.messages = (this.messages || []).filter(function (m) { return String(m.id).indexOf('local-') !== 0; });
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…';
// alleen meescrollen als je al onderaan zit
if (this.stickToBottom) this.$nextTick(function () { this.scrollLog(); }.bind(this));
else this.showJumpLatest = true;
} 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);
// geen jump tijdens teruglezen; max 1x / 600ms als je onderaan zit
if (this.stickToBottom) {
var now = Date.now();
if (now - (this._typingScrollAt || 0) > 600) {
this._typingScrollAt = now;
this.$nextTick(function () { this.scrollLog(); }.bind(this));
}
} else {
this.showJumpLatest = true;
}
} else if (type === 'agent' && ev.message) {
this.typing = null;
this.upsertMessage(ev.message);
if (this.voiceRoomOpen && this.speakReplies && 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) {
if (!this.mentionOpen) return;
var sug = this.mentionSuggestions();
if (!sug.length) return;
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 === 'Tab') {
e.preventDefault();
this.pickMention(sug[this.mentionIndex] || sug[0]);
return;
}
if (e.key === 'Escape') {
this.mentionOpen = false;
}
},
scheduleContinue(delayMs) {
if (this._continueTimer) clearTimeout(this._continueTimer);
if (!this.autoDebate) return;
var self = this;
// default: rustig tempo (~50s), niet elke paar seconden
var wait = (typeof delayMs === 'number' && delayMs >= 0) ? delayMs : 50000;
this._continueTimer = setTimeout(function () { self.runContinue(1); }, wait);
},
toggleA2A() {
this.autoDebate = !this.autoDebate;
try { localStorage.setItem('flk-warroom-a2a', this.autoDebate ? '1' : '0'); } catch (e) {}
if (this._continueTimer) clearTimeout(this._continueTimer);
if (this.autoDebate) {
this.status = 'A2A aan — agents mogen onderling verder praten';
this.scheduleContinue(8000);
if (window.Cockpit) Cockpit.toast('A2A aan', 'ok');
} else {
this.status = 'A2A uit — alleen reacties op jouw berichten';
this.a2aPausedUntil = 0;
if (window.Cockpit) Cockpit.toast('A2A uit', 'ok');
}
},
pauseA2A(ms) {
this.a2aPausedUntil = Date.now() + (ms || 45000);
if (this._continueTimer) clearTimeout(this._continueTimer);
},
setReply(m) {
if (!m || !m.id || String(m.id).indexOf('local-') === 0) return;
this.replyTo = {
id: m.id,
agent_key: m.agent_key || null,
username: m.username || null,
sender_type: m.sender_type,
excerpt: ((m.content || '').trim().slice(0, 160)) + (((m.content || '').length > 160) ? '…' : ''),
label: this.labelForMessage(m),
};
this.replyHighlightId = m.id;
this.pauseA2A(90000);
this.$nextTick(function () {
this.scrollToMessage(m.id);
this.focusComposer();
}.bind(this));
},
scrollToMessage(id) {
if (id == null) return;
var root = (this.$refs && this.$refs.wrLog) || document;
var el = root.querySelector && root.querySelector('[data-msg-id="' + id + '"]');
if (el && el.scrollIntoView) {
try { el.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (e) {
el.scrollIntoView(true);
}
}
},
async refreshMessages(opts) {
opts = opts || {};
if (!this.room || !this.room.id) return;
try {
var r = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/messages?limit=200', {
credentials: 'same-origin',
}).then(function (x) { return x.json(); });
var items = this.normalizeList(r.items || []);
if (items.length) {
this.messages = items;
this.lastId = this.maxId(items);
}
if (!opts.silent) {
this.$nextTick(function () {
this.paintAvatars();
this.scrollLog();
}.bind(this));
} else {
this.$nextTick(function () { this.paintAvatars(); }.bind(this));
}
} catch (e) { /* quiet */ }
},
clearReply() {
this.replyTo = null;
this.replyHighlightId = null;
},
replyPreview(m) {
var meta = (m && m.metadata) || {};
return meta.reply_to || null;
},
async runContinue(turns) {
if (!this.autoDebate || !this.room || this.room.kind !== 'warroom') return;
if (this.busy || this._continueBusy || this._sendLock) {
this.scheduleContinue(20000);
return;
}
if (Date.now() < (this.a2aPausedUntil || 0)) {
this.scheduleContinue(Math.max(10000, this.a2aPausedUntil - Date.now()));
return;
}
// niet doorkletsen terwijl jij typt
if ((this.draft || '').trim().length > 0 || this.replyTo) {
this.scheduleContinue(25000);
return;
}
this._continueBusy = true;
this.status = 'A2A — agents reageren…';
try {
var resp = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/continue?turns=' + (turns || 1), {
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 = 'A2A live';
// keep conversation alive
this.scheduleContinue(55000);
} catch (e) {
this.busy = false;
this.status = 'A2A hervatten…';
this.scheduleContinue(45000);
}
this._continueBusy = false;
},
async loadCeoInbox() {
try {
var r = await fetch('/api/agents/warroom/ceo-inbox?limit=40', { credentials: 'same-origin' })
.then(function (x) { return x.json(); });
this.ceoInbox = r.items || [];
this.ceoUnread = r.unread || 0;
} catch (e) {
this.ceoInbox = this.ceoInbox || [];
}
},
openCeoInbox() {
this.ceoInboxOpen = true;
this.loadCeoInbox();
},
closeCeoInbox() {
this.ceoInboxOpen = false;
},
async markCeoRead(id) {
try {
await fetch('/api/agents/warroom/ceo-inbox/read', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(id ? { ids: [id] } : { all: true }),
});
await this.loadCeoInbox();
} catch (e) {}
},
async markAllCeoRead() {
await this.markCeoRead(null);
if (window.Cockpit) Cockpit.toast('CEO-inbox gelezen', 'ok');
},
isCeoDirect(m) {
if (!m) return false;
if (m.ceo_inbox_id || (m.metadata && m.metadata.ceo_direct)) return true;
var c = (m.content || '').toLowerCase();
return c.indexOf('@aissa') >= 0 || c.indexOf('@ceo') >= 0 || c.indexOf('@ervoorz') >= 0;
},
formatMsgTime(m) {
var raw = (m && (m.created_at || m.createdAt || m.ts)) || '';
if (!raw) return '';
var d = new Date(raw);
if (isNaN(d.getTime())) return '';
return d.toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' });
},
formatMsgDate(m) {
var raw = (m && (m.created_at || m.createdAt || m.ts)) || '';
if (!raw) return '';
var d = new Date(raw);
if (isNaN(d.getTime())) return '';
var today = new Date();
var yest = new Date(); yest.setDate(today.getDate() - 1);
var same = function (a, b) {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
};
if (same(d, today)) return 'Vandaag';
if (same(d, yest)) return 'Gisteren';
return d.toLocaleDateString('nl-NL', { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' });
},
dayKey(m) {
var raw = (m && (m.created_at || m.createdAt || m.ts)) || '';
if (!raw) return '';
var d = new Date(raw);
if (isNaN(d.getTime())) return '';
return d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
},
showDaySep(idx) {
var list = this.visibleMessages();
if (!list.length || idx < 0 || idx >= list.length) return false;
if (idx === 0) return !!this.dayKey(list[idx]);
return this.dayKey(list[idx]) !== this.dayKey(list[idx - 1]);
},
visibleMessages() {
if (this.screenCleared) return [];
var q = (this.chatSearch || '').trim().toLowerCase();
var list = this.messages || [];
if (!q) return list;
return list.filter(function (m) {
var hay = [
m.content || '',
m.agent_key || '',
m.username || '',
m.display_name || '',
m.sender_type || '',
].join(' ').toLowerCase();
return hay.indexOf(q) >= 0;
});
},
toggleSearch() {
this.searchOpen = !this.searchOpen;
this.toolsOpen = false;
if (this.searchOpen) {
var self = this;
this.$nextTick(function () {
var el = self.$refs && self.$refs.wrSearch;
if (el) el.focus();
});
} else {
this.chatSearch = '';
}
},
clearScreen() {
this.screenCleared = true;
this.status = 'Scherm geleegd (berichten blijven bewaard)';
if (window.Cockpit) Cockpit.toast('Chat-scherm geleegd', 'ok');
},
restoreScreen() {
this.screenCleared = false;
this.status = '';
this.$nextTick(function () { this.scrollLog(); }.bind(this));
},
async clearChatHistory() {
if (!this.room) return;
if (!window.confirm('Alle berichten in dit kanaal permanent van het scherm wissen (soft-delete)?')) return;
try {
var r = await fetch('/api/agents/warroom/rooms/' + this.room.id + '/messages', {
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)) || 'Wissen mislukt');
this.messages = [];
this.screenCleared = false;
this.lastId = 0;
this.status = 'Geschiedenis gewist (' + ((r.d && r.d.cleared) || 0) + ')';
if (window.Cockpit) Cockpit.toast('Chatgeschichte gewist', 'ok');
} catch (e) {
if (window.Cockpit) Cockpit.toast(e.message || 'Wissen mislukt', 'error');
}
},
downloadChat(fmt) {
fmt = fmt || 'txt';
var list = this.messages || [];
if (!list.length) {
if (window.Cockpit) Cockpit.toast('Geen berichten om te downloaden', 'info');
return;
}
var title = (this.room && (this.room.title || this.room.kind)) || 'war-room';
var stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-');
var filename = 'foodlinkk-' + String(title).replace(/[^\w\-]+/g, '_') + '-' + stamp;
var body = '';
var mime = 'text/plain;charset=utf-8';
if (fmt === 'json') {
body = JSON.stringify({ room: this.room, exported_at: new Date().toISOString(), messages: list }, null, 2);
filename += '.json';
mime = 'application/json;charset=utf-8';
} else if (fmt === 'md') {
body = '# ' + title + '\n\n_Geëxporteerd: ' + new Date().toLocaleString('nl-NL') + '_\n\n';
list.forEach(function (m) {
var who = this.labelForMessage(m) + (m.agent_key ? (' (@' + m.agent_key + ')') : '');
var when = this.formatMsgDate(m) + ' ' + this.formatMsgTime(m);
body += '### ' + who + ' · ' + when.trim() + '\n\n' + (m.content || '') + '\n\n---\n\n';
}.bind(this));
filename += '.md';
mime = 'text/markdown;charset=utf-8';
} else {
body = title + '\nGeëxporteerd: ' + new Date().toLocaleString('nl-NL') + '\n' + ('='.repeat(48)) + '\n\n';
list.forEach(function (m) {
var who = this.labelForMessage(m) + (m.agent_key ? (' (@' + m.agent_key + ')') : '');
var when = (this.formatMsgDate(m) + ' ' + this.formatMsgTime(m)).trim();
body += '[' + when + '] ' + who + ':\n' + (m.content || '') + '\n\n';
}.bind(this));
filename += '.txt';
}
var blob = new Blob([body], { type: mime });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 500);
this.toolsOpen = false;
if (window.Cockpit) Cockpit.toast('Download gestart (' + fmt + ')', 'ok');
},
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[String(id)] = true; });
this.messages = (this.messages || []).filter(function (m) {
return !set[String(m.id)];
});
},
openVoiceRoom() {
if (!this.room) {
if (window.Cockpit) Cockpit.toast('Geen room geladen', 'error');
return;
}
if (!(this.voiceRoomAgents || []).length) {
this.voiceRoomAgents = ['herman', 'bizdev', 'finance', 'retail', 'marketing'];
}
// voorlezen blijft uit tot gebruiker 🔊 aanzet
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();