| 1 | // Per-thread tracking page + ingest API. |
| 2 | // The agent posts updates to /api/threads/:id/events from inside its session, |
| 3 | // and external viewers can read /api/threads/:id to see what's happening. |
| 4 | const express = require('express'); |
| 5 | const fs = require('fs'); |
| 6 | const path = require('path'); |
| 7 | |
| 8 | const router = express.Router(); |
| 9 | const DATA_DIR = path.resolve(__dirname, '..', 'data'); |
| 10 | const FILE = path.join(DATA_DIR, 'threads.json'); |
| 11 | |
| 12 | const subscribers = new Map(); // threadId|"*" -> Set<res> |
| 13 | |
| 14 | function readAll() { |
| 15 | try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } |
| 16 | catch { return []; } |
| 17 | } |
| 18 | function writeAll(list) { |
| 19 | fs.mkdirSync(DATA_DIR, { recursive: true }); |
| 20 | fs.writeFileSync(FILE, JSON.stringify(list.slice(0, 500), null, 2)); |
| 21 | } |
| 22 | function broadcast(threadId, payload) { |
| 23 | const data = `data: ${JSON.stringify(payload)}\n\n`; |
| 24 | for (const key of [threadId, '*']) { |
| 25 | for (const res of (subscribers.get(key) || [])) { try { res.write(data); } catch {} } |
| 26 | } |
| 27 | } |
| 28 | function upsertThread(t) { |
| 29 | const all = readAll(); |
| 30 | const i = all.findIndex(x => x.id === t.id); |
| 31 | const merged = i >= 0 ? { ...all[i], ...t, updatedAt: new Date().toISOString() } |
| 32 | : { events: [], status: 'open', createdAt: new Date().toISOString(), |
| 33 | updatedAt: new Date().toISOString(), ...t }; |
| 34 | if (i >= 0) all[i] = merged; else all.unshift(merged); |
| 35 | writeAll(all); |
| 36 | return merged; |
| 37 | } |
| 38 | |
| 39 | router.get('/', (req, res) => { |
| 40 | const all = readAll().map(t => ({ |
| 41 | id: t.id, agentId: t.agentId, subject: t.subject, from: t.from, |
| 42 | status: t.status, version: t.version, |
| 43 | eventCount: (t.events || []).length, |
| 44 | createdAt: t.createdAt, updatedAt: t.updatedAt, |
| 45 | })); |
| 46 | res.json(all); |
| 47 | }); |
| 48 | |
| 49 | router.get('/:id', (req, res) => { |
| 50 | const t = readAll().find(x => x.id === req.params.id); |
| 51 | if (!t) return res.status(404).json({ error: 'thread not found' }); |
| 52 | res.json(t); |
| 53 | }); |
| 54 | |
| 55 | router.post('/', (req, res) => res.json(upsertThread(req.body))); |
| 56 | |
| 57 | router.post('/:id/events', (req, res) => { |
| 58 | const all = readAll(); |
| 59 | const i = all.findIndex(x => x.id === req.params.id); |
| 60 | if (i < 0) return res.status(404).json({ error: 'thread not found' }); |
| 61 | const ev = { ...req.body, at: new Date().toISOString() }; |
| 62 | all[i].events = [...(all[i].events || []), ev].slice(-500); |
| 63 | all[i].updatedAt = ev.at; |
| 64 | writeAll(all); |
| 65 | broadcast(req.params.id, { type: 'event', threadId: req.params.id, event: ev }); |
| 66 | broadcast('*', { type: 'event', threadId: req.params.id, event: ev }); |
| 67 | res.json({ ok: true }); |
| 68 | }); |
| 69 | |
| 70 | router.patch('/:id', (req, res) => { |
| 71 | const all = readAll(); |
| 72 | const i = all.findIndex(x => x.id === req.params.id); |
| 73 | if (i < 0) return res.status(404).json({ error: 'thread not found' }); |
| 74 | all[i] = { ...all[i], ...req.body, updatedAt: new Date().toISOString() }; |
| 75 | writeAll(all); |
| 76 | broadcast(req.params.id, { type: 'thread:update', thread: all[i] }); |
| 77 | res.json(all[i]); |
| 78 | }); |
| 79 | |
| 80 | router.get('/stream/:id', sse); |
| 81 | router.get('/stream', sse); |
| 82 | |
| 83 | function sse(req, res) { |
| 84 | const key = req.params.id || '*'; |
| 85 | res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }); |
| 86 | res.write(': connected\n\n'); |
| 87 | if (!subscribers.has(key)) subscribers.set(key, new Set()); |
| 88 | subscribers.get(key).add(res); |
| 89 | const ping = setInterval(() => { try { res.write(': ping\n\n'); } catch {} }, 30000); |
| 90 | req.on('close', () => { clearInterval(ping); subscribers.get(key)?.delete(res); }); |
| 91 | } |
| 92 | |
| 93 | module.exports = router; |