/** 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, emojis: EMOJIS, pendingFiles: [], typing: null, // { agent_key, display_name, text } async init() { 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); }, 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)); } 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(); }); 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) { this.draft = (this.draft || '') + '@' + key + ' '; }, 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 = ''; } 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 === '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); 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 (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); this.send(); } }, 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 }; })(); document.addEventListener('alpine:init', function () { if (window.Alpine && Alpine.data) { Alpine.data('warRoomHub', function () { return WarRoomHub.controller({ popupMode: false }); }); Alpine.data('warRoomPopup', function () { return WarRoomHub.controller({ popupMode: true }); }); } });