Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(chat): stream the model's reasoning to web clients
Salman Qureshi18e065b09869
diff --git a/src/channels/web-reasoning.test.ts b/src/channels/web-reasoning.test.tsnew file mode 100644index 00000000..8eab0659--- /dev/null+++ b/src/channels/web-reasoning.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it, vi } from 'vitest';+import { WebChannel } from './web.js';++describe('web channel reasoning stream', () => {+ it('batches deltas and closes the block when the answer starts', async () => {+ vi.useFakeTimers();+ const ch = new WebChannel();+ const sent: Array<{ type: string; data?: Record<string, unknown> }> = [];+ (ch as unknown as { broadcast: (e: { type: string; data?: Record<string, unknown> }) => boolean }).broadcast = (e) => { sent.push(e); return true; };+ ch.sendReasoning('Let me ', 's1');+ ch.sendReasoning('check the file.', 's1');+ expect(sent).toHaveLength(0);+ vi.advanceTimersByTime(130);+ expect(sent).toEqual([{ type: 'reasoning', data: { text: 'Let me check the file.', targetId: 's1' } }]);+ ch.sendReasoning(' Then edit it.', 's1');+ ch.sendReasoning(null, 's1');+ expect(sent.slice(1)).toEqual([+ { type: 'reasoning', data: { text: ' Then edit it.', targetId: 's1' } },+ { type: 'reasoning', data: { done: true, targetId: 's1' } },+ ]);+ vi.useRealTimers();+ });+});diff --git a/src/channels/web.ts b/src/channels/web.tsindex 261f2562..b91c19bf 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -17,7 +17,7 @@ interface PendingInteraction {}export interface ChatEvent {- type: 'thinking' | '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: 'thinking' | 'reasoning' | '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>;}@@ -297,6 +297,36 @@ export class WebChannel extends BaseChannel {});}+ /**+ * The model's reasoning as it streams, for clients that show the thought+ * process live. Deltas are batched (≤ 8 events/s per target); null closes+ * the reasoning block when the answer starts.+ */+ private reasoningBuf = new Map<string, { text: string; timer: ReturnType<typeof setTimeout> | null }>();++ sendReasoning(delta: string | null, targetId?: string): void {+ const key = targetId || 'default';+ const entry = this.reasoningBuf.get(key) ?? { text: '', timer: null };+ const flush = () => {+ const e = this.reasoningBuf.get(key);+ if (!e) return;+ if (e.timer) clearTimeout(e.timer);+ e.timer = null;+ if (e.text) this.broadcast({ type: 'reasoning', data: { text: e.text, targetId } });+ e.text = '';+ };+ if (delta === null) {+ this.reasoningBuf.set(key, entry);+ flush();+ this.broadcast({ type: 'reasoning', data: { done: true, targetId } });+ this.reasoningBuf.delete(key);+ return;+ }+ entry.text += delta;+ this.reasoningBuf.set(key, entry);+ if (!entry.timer) entry.timer = setTimeout(flush, 125);+ }+sendStepDone(toolName: string, result: unknown, targetId?: string): void {const summary = typeof result === 'string'? result.slice(0, 200)diff --git a/src/core/agent.ts b/src/core/agent.tsindex 7338d78a..20d30b6c 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -134,7 +134,7 @@ import type { ApplyResult } from '../memory/beliefs.js';*/export function stepAwareTextStream(fullStream: AsyncIterable<any>,- onReasoning?: (preview: string | null) => void,+ onReasoning?: (preview: string | null, delta?: string) => void,): AsyncIterable<string> {return (async function* () {let firstStep = true;@@ -155,7 +155,7 @@ export function stepAwareTextStream(// Live thinking feedback: the model reasoning before speaking is// surfaced as a preview instead of dead air.reasoningBuf = (reasoningBuf + part.text).slice(-400);- onReasoning?.(reasoningBuf.slice(-160));+ onReasoning?.(reasoningBuf.slice(-160), part.text);continue;}if (part.type === 'text-delta' && part.text) {@@ -3380,9 +3380,13 @@ export class Agent {});const cliChThinking = channel instanceof CLIChannel ? channel : null;+ // Clients that show the thought process live (Mercury Desktop) get the reasoning text.+ const webChThinking = channel instanceof WebChannel ? channel : null;+ const reasoningTarget = msg.channelId;const trackedStream = this.withProgressStream((async function* () {- for await (const chunk of (stepAwareTextStream(streamResult.fullStream, (preview) => {+ for await (const chunk of (stepAwareTextStream(streamResult.fullStream, (preview, delta) => {cliChThinking?.showThinkingPreview(preview);+ if (webChThinking) webChThinking.sendReasoning(preview === null ? null : delta ?? '', reasoningTarget);}))) {if (chunk) hasStreamedOutput = true;cliChThinking?.showThinkingPreview(null);