Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(runtime): activity feed for notifications; background prompts stay answerable
Salman Qureshieb86dd9c0502
diff --git a/src/channels/web-activity.test.ts b/src/channels/web-activity.test.tsnew file mode 100644index 00000000..b71b6124--- /dev/null+++ b/src/channels/web-activity.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';+import { WebChannel } from './web.js';++function sink() {+ const events: Array<{ event: string; data: Record<string, unknown> }> = [];+ const controller = {+ enqueue(value: Uint8Array) {+ const text = new TextDecoder().decode(value);+ const m = /^event: (\S+)\ndata: (.*)\n\n$/s.exec(text);+ if (m) events.push({ event: m[1], data: JSON.parse(m[2]) });+ },+ close() {},+ } as unknown as ReadableStreamDefaultController;+ return { events, controller };+}++describe('activity feed for notifications', () => {+ it('reports a turn starting once and finishing, with its title and duration', async () => {+ const channel = new WebChannel('Mercury');+ const feed = sink();+ channel.addActivityClient(feed.controller);+ channel.setSessionTitleLookup((id) => (id === 's1' ? 'Research report' : undefined));++ await channel.typing('s1');+ await channel.typing('s1');+ await channel.send('Here is the report.', 's1', 42_000);++ const kinds = feed.events.filter((e) => e.event === 'activity').map((e) => e.data.kind);+ expect(kinds).toEqual(['started', 'done']);+ const done = feed.events.at(-1)!.data;+ expect(done).toMatchObject({ sessionId: 's1', title: 'Research report', ms: 42_000, preview: 'Here is the report.' });+ });++ it('marks a stopped turn and a failed one apart from a finished one', async () => {+ const channel = new WebChannel('Mercury');+ const feed = sink();+ channel.addActivityClient(feed.controller);+ await channel.typing('s2');+ await channel.send('⏹ Task stopped.', 's2');+ await channel.typing('s3');+ channel.sendError('Provider unreachable', 's3');+ expect(feed.events.map((e) => e.data.kind)).toEqual(['started', 'stopped', 'started', 'failed']);+ });++ it('keeps a prompt in a session nobody has open, replays it, and reports the answer', async () => {+ const channel = new WebChannel('Mercury');+ const feed = sink();+ channel.addActivityClient(feed.controller);++ const answer = channel.askPermission('Run npm run deploy?', 's4');+ const needs = feed.events.find((e) => e.data.kind === 'needs_you')!;+ expect(needs.data).toMatchObject({ sessionId: 's4', prompt: 'Run npm run deploy?' });++ // Opening the session shows the waiting prompt.+ const pending = channel.pendingFor('s4');+ expect(pending).toHaveLength(1);+ expect(pending[0].data).toMatchObject({ prompt: 'Run npm run deploy?' });++ expect(channel.resolveApproval(String(needs.data.id), 'yes')).toBe(true);+ await expect(answer).resolves.toBe('yes');+ expect(feed.events.at(-1)!.data).toMatchObject({ kind: 'resolved', id: needs.data.id });+ expect(channel.pendingFor('s4')).toHaveLength(0);+ });++ it('still declines at once when no screen at all is listening', async () => {+ const channel = new WebChannel('Mercury');+ await expect(channel.askPermission('Delete files?', 's5')).resolves.toBe('no');+ });+});diff --git a/src/channels/web.ts b/src/channels/web.tsindex b10c1202..0445e013 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -12,13 +12,16 @@ type PendingInteractionKind = 'permission' | 'continue' | 'mode' | 'choice';interface PendingInteraction {kind: PendingInteractionKind;targetId?: string;+ /** The session it was asked in, and the event that asked it (replayed when a screen opens that session). */+ sessionId?: string;+ event?: ChatEvent;allowedValues: Set<string>;resolve: (value: string) => void;timer: ReturnType<typeof setTimeout>;}export interface ChatEvent {- type: 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';data?: Record<string, unknown>;}@@ -52,6 +55,11 @@ class SSEClient {export class WebChannel extends BaseChannel {readonly type = 'web' as const;private sseClients: Map<string, SSEClient> = new Map();+ /** Screens that want a summary of every session (started, needs you, done): notifications. */+ private activityClients: Map<string, SSEClient> = new Map();+ private turnStarts = new Map<string, number>();+ /** Session titles for activity events (set by the web server). */+ private titleOf: ((sessionId: string) => string | undefined) | null = null;private pendingInteractions = new Map<string, PendingInteraction>();private agentName: string;private stepCounter: Map<string, number> = new Map();@@ -95,6 +103,71 @@ export class WebChannel extends BaseChannel {this.sseClients.delete(id);}+ addActivityClient(controller: ReadableStreamDefaultController): string {+ const id = `act_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ this.activityClients.set(id, new SSEClient(controller, id));+ return id;+ }++ removeActivityClient(id: string): void {+ this.activityClients.delete(id);+ }++ setSessionTitleLookup(fn: (sessionId: string) => string | undefined): void {+ this.titleOf = fn;+ }++ /** Prompts still waiting in a session, as the events that asked them. */+ pendingFor(sessionId: string): ChatEvent[] {+ return [...this.pendingInteractions.values()].filter((i) => i.sessionId === sessionId && i.event).map((i) => i.event!);+ }++ /**+ * One line per session event that a person would want to hear about:+ * a turn started, Mercury needs an answer, a turn finished or failed.+ * Cloud-relayed sessions belong to their remote screen, so they're left out.+ */+ private emitActivity(event: ChatEvent, targetId: string | undefined): void {+ if (!targetId) return;+ if (this.cloudEventHandlers.has(targetId)) return;+ const d = event.data ?? {};+ const now = Date.now();+ let data: Record<string, unknown> | null = null;+ switch (event.type) {+ case 'thinking':+ if (!this.turnStarts.has(targetId)) { this.turnStarts.set(targetId, now); data = { kind: 'started' }; }+ break;+ case 'permission_request':+ case 'permission_continue':+ case 'choice_prompt':+ data = { kind: 'needs_you', id: d.id, prompt: String(d.prompt ?? d.question ?? '').slice(0, 300) };+ break;+ case 'permission_resolved':+ case 'choice_resolved':+ data = { kind: 'resolved', id: d.id };+ break;+ case 'text_done': {+ const started = this.turnStarts.get(targetId);+ this.turnStarts.delete(targetId);+ const text = String(d.fullText ?? '');+ const ms = typeof d.elapsedMs === 'number' ? d.elapsedMs : started ? now - started : 0;+ data = { kind: /^⏹/.test(text.trim()) ? 'stopped' : 'done', ms, preview: text.replace(/\s+/g, ' ').trim().slice(0, 200) };+ break;+ }+ case 'error': {+ const started = this.turnStarts.get(targetId);+ this.turnStarts.delete(targetId);+ data = { kind: 'failed', ms: started ? now - started : 0, message: String(d.message ?? '').slice(0, 200) };+ break;+ }+ }+ if (!data || this.activityClients.size === 0) return;+ let title: string | undefined;+ try { title = this.titleOf?.(targetId); } catch { title = undefined; }+ const out: ChatEvent = { type: 'activity', data: { ...data, sessionId: targetId, title, at: now } };+ for (const [, client] of this.activityClients) client.send(out);+ }+/*** Real-time bot activity feed: what each Mercury bot is doing RIGHT NOW* (step, tool calls, turn lifecycle). Broadcast to every connected web@@ -138,6 +211,7 @@ export class WebChannel extends BaseChannel {if (targetId && client.sessionId !== targetId) continue;client.send(event);}+ this.emitActivity(event, targetId);return delivered;}@@ -165,6 +239,8 @@ export class WebChannel extends BaseChannel {this.pendingInteractions.delete(id);clearTimeout(interaction.timer);interaction.resolve(value);+ // Every screen (and the notification feed) learns it was answered.+ this.broadcast({ type: interaction.kind === 'choice' ? 'choice_resolved' : 'permission_resolved', data: { id, status: 'answered', targetId: interaction.sessionId } });return true;}@@ -174,8 +250,12 @@ export class WebChannel extends BaseChannel {values: string[],targetId: string | undefined,fallback: string,+ event?: ChatEvent,): Promise<string> {const boundTargetId = targetId && this.cloudEventHandlers.has(targetId) ? targetId : undefined;+ // The same two minutes whether or not the session is on screen: the agent waits while+ // a prompt is open, so a longer wait would hold up every other conversation.+ const waitMs = 120_000;return new Promise((resolve) => {const timer = setTimeout(() => {const interaction = this.pendingInteractions.get(id);@@ -186,10 +266,12 @@ export class WebChannel extends BaseChannel {data: { id, status: 'expired', targetId: interaction.targetId },});resolve(fallback);- }, 120_000);+ }, waitMs);this.pendingInteractions.set(id, {kind,targetId: boundTargetId,+ sessionId: targetId,+ event,allowedValues: new Set(values),resolve,timer,@@ -206,6 +288,11 @@ export class WebChannel extends BaseChannel {private hasInteractiveTarget(targetId?: string): boolean {if (!targetId) return this.sseClients.size > 0;if (this.cloudEventHandlers.has(targetId)) return true;+ // A screen listening for notifications can answer once the owner opens the session.+ return this.isWatched(targetId) || this.activityClients.size > 0;+ }++ private isWatched(targetId: string): boolean {return [...this.sseClients.values()].some((client) => client.sessionId === targetId);}@@ -242,23 +329,25 @@ export class WebChannel extends BaseChannel {if (this.isPermissionBypassed(_targetId)) return 'yes';if (!this.hasInteractiveTarget(_targetId)) return 'no';const id = `perm_${randomUUID()}`;- this.broadcast({+ const event: ChatEvent = {type: 'permission_request',data: { id, prompt, options: ['yes', 'always', 'no'], targetId: _targetId },- });-- return this.waitForInteraction(id, 'permission', ['yes', 'always', 'no'], _targetId, 'no');+ };+ const pending = this.waitForInteraction(id, 'permission', ['yes', 'always', 'no'], _targetId, 'no', event);+ this.broadcast(event);+ return pending;}async askToContinue(question: string, _targetId?: string): Promise<boolean> {if (!this.hasInteractiveTarget(_targetId)) return false;const id = `loop_${randomUUID()}`;- this.broadcast({+ const event: ChatEvent = {type: 'permission_continue',data: { id, question, options: ['yes', 'no'], targetId: _targetId },- });-- return this.waitForInteraction(id, 'continue', ['yes', 'no'], _targetId, 'no').then((value) => value === 'yes');+ };+ const pending = this.waitForInteraction(id, 'continue', ['yes', 'no'], _targetId, 'no', event);+ this.broadcast(event);+ return pending.then((value) => value === 'yes');}askPermissionMode(): Promise<'allow-all' | 'ask-me'> {@@ -275,12 +364,13 @@ export class WebChannel extends BaseChannel {async presentChoicePrompt(question: string, options: Array<{ value: string; label: string }>, targetId?: string): Promise<string> {if (!this.hasInteractiveTarget(targetId)) return '';const id = `choice_${randomUUID()}`;- this.broadcast({+ const event: ChatEvent = {type: 'choice_prompt',data: { id, question, options, targetId },- });-- return this.waitForInteraction(id, 'choice', options.map((option) => option.value), targetId, '');+ };+ const pending = this.waitForInteraction(id, 'choice', options.map((option) => option.value), targetId, '', event);+ this.broadcast(event);+ return pending;}sendToolFeedback(toolName: string, args: Record<string, unknown>, targetId?: string): void {diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 9f5603b9..05202ad0 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -41,6 +41,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['providers.manage', // GET /api/providers/settings, POST /api/providers/:id/check (live, unsaved), PUT /api/providers/roles; saves apply live; health.setupRequired'voice.check','artifacts', // GET /api/artifacts (paged), /:id, /:id/file (Range), POST /:id/export, DELETE /:id; SSE 'artifacts'; message.artifacts+ 'chat.activity', // GET /api/chat/activity (SSE: started, needs_you, resolved, done, stopped, failed per session), GET /api/chat/pending?sessionId'chat.plan', // SSE 'plan' { steps, updatedAt } + GET /api/chat/plan?sessionId= (the plan checklist)'channels', // GET /api/channels, POST :type/check, PUT :type, POST :type/access, POST/GET signal/link'transcribe', // GET/POST /api/transcribe — dictation: raw audio in, text outdiff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 36f9a33b..fcd6a13b 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -131,6 +131,41 @@ chat.get('/api/chat/plan', (c) => {return c.json({ plan: id ? webChannel.plans.get(id) : null });});+/**+ * Activity across every session (started, needs you, done, failed), for+ * notifications. Prompts asked while this is open wait for the owner.+ */+chat.get('/api/chat/activity', (c) => {+ if (!webChannel) return c.json({ error: 'Web channel not initialized' }, 503);+ const ch = webChannel;+ if (sessions) {+ const repo = sessions;+ ch.setSessionTitleLookup((id) => { try { return repo.get(id)?.title ?? undefined; } catch { return undefined; } });+ }+ const stream = new ReadableStream({+ start(controller) {+ const clientId = ch.addActivityClient(controller);+ const encoder = new TextEncoder();+ const send = (data: string) => { try { controller.enqueue(encoder.encode(data)); } catch { /* closed */ } };+ send(`event: connected\ndata: ${JSON.stringify({ id: clientId })}\n\n`);+ const keepalive = setInterval(() => send(': keepalive\n\n'), 15000);+ c.req.raw.signal.addEventListener('abort', () => {+ clearInterval(keepalive);+ ch.removeActivityClient(clientId);+ });+ },+ });+ return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' } });+});++/** Prompts still waiting for an answer in a session (opening it shows them). */+chat.get('/api/chat/pending', (c) => {+ if (!webChannel) return c.json({ prompts: [] });+ const sessionId = c.req.query('sessionId') ?? '';+ if (!sessionId) return c.json({ prompts: [] });+ return c.json({ prompts: webChannel.pendingFor(sessionId).map((e) => ({ type: e.type, ...e.data })) });+});+chat.get('/api/chat/events', (c) => {if (!webChannel) {return c.json({ error: 'Web channel not initialized' }, 503);