Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): the answer streams in, with its steps and a Stop button
trohitgc9da4892f460
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxindex cd11f5ab..6b4929d0 100644--- a/client/src/features/chat/ChatPane.tsx+++ b/client/src/features/chat/ChatPane.tsx@@ -5,16 +5,18 @@* host (`ChatHost`) says who answers, whether a message can go now and what* sits around the conversation; the chat owns the rest.*- * The turns follow the session's runs (docs-internal/chat_protocol.md):- * "Working…" shows while the run a message started is going, whatever- * else arrives meanwhile, and the next message waits until it ends. A- * message that does not go comes back into the box.+ * The turns follow the session's runs (docs-internal/chat_protocol.md): the+ * employee's steps and answer stream in while the run a message started is+ * going, whatever else arrives meanwhile, and the next message waits until+ * it ends. Meanwhile Send is Stop, and Esc anywhere in the pane stops the+ * answer too. A message that does not go comes back into the box.*/-import { useCallback, useImperativeHandle, useRef, type Ref } from 'react';+import { useCallback, useImperativeHandle, useRef, type KeyboardEvent, type Ref } from 'react';import { cn } from '@/lib/utils';import { useConversation } from './data/conversation';import { useSendChatMessage, type ChatSendError } from './data/send';+import { useStopChatRun } from './data/stop';import { Composer } from './composer/Composer';import type { ChatHost, ChatPaneHandle } from './host';import { useComposerStore } from './state/composerStore';@@ -34,7 +36,9 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand[notify, onSendRefused],);const send = useSendChatMessage(sessionId, scope, onRefused);+ const stop = useStopChatRun(sessionId, () => notify('Couldn’t stop the reply. Try again.', 'error'));const busy = send.isPending || lane !== null;+ const stopping = lane?.state === 'stopping' || stop.isPending;const submit = () => {const store = useComposerStore.getState();@@ -43,8 +47,18 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandsend.mutate({ ...draft, text: draft.text.trim() });};+ const stopAnswer = () => {+ if (lane && !stopping) stop.mutate(lane);+ };++ const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {+ if (event.key !== 'Escape' || event.defaultPrevented || !lane || stopping) return;+ event.preventDefault();+ stopAnswer();+ };+return (- <section aria-label={`Chat with ${persona.name}`} className="flex min-h-0 w-full flex-1 flex-col">+ <section aria-label={`Chat with ${persona.name}`} onKeyDown={onKeyDown} className="flex min-h-0 w-full flex-1 flex-col"><ChatThreadpersona={persona}turns={turns}@@ -56,6 +70,7 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandemptyState={host.emptyState}liveNote={host.liveNote}compact={compact}+ canStop={composer !== 'closed'}onScrolledChange={host.onScrolledChange}/><div className={cn('relative flex-none', compact ? 'border-t border-border-default px-3 py-2' : 'px-6 pb-3')}>@@ -68,6 +83,8 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandready={Boolean(thread.data)}busy={busy}onSend={submit}+ onStop={lane ? stopAnswer : undefined}+ stopping={stopping}compact={compact}boxRef={boxRef}/>diff --git a/client/src/features/chat/__tests__/blocks.test.ts b/client/src/features/chat/__tests__/blocks.test.tsnew file mode 100644index 00000000..0abbc9f8--- /dev/null+++ b/client/src/features/chat/__tests__/blocks.test.ts@@ -0,0 +1,27 @@+/**+ * A streaming answer cut into blocks: at blank lines, never inside fenced+ * code, so each finished block renders once.+ */++import { describe, expect, it } from 'vitest';+import { markdownBlocks } from '../markdown/blocks';++describe('markdownBlocks', () => {+ it('cuts at blank lines', () => {+ expect(markdownBlocks('One.\nStill one.\n\n- a\n- b\n\n\nThree')).toEqual(['One.\nStill one.', '- a\n- b', 'Three']);+ });++ it('keeps a fenced block whole, blank lines and all, and the still-open one too', () => {+ const fenced = 'Run this:\n\n```bash\necho one\n\necho two\n```\n\nDone.';+ expect(markdownBlocks(fenced)).toEqual(['Run this:', '```bash\necho one\n\necho two\n```', 'Done.']);+ expect(markdownBlocks('```py\nprint(1)\n\nprint(2)')).toEqual(['```py\nprint(1)\n\nprint(2)']);+ // A shorter or different fence does not close it.+ expect(markdownBlocks('````\n```\n\nx\n````\n\nafter')).toEqual(['````\n```\n\nx\n````', 'after']);+ expect(markdownBlocks('~~~\na\n\n```\n~~~')).toEqual(['~~~\na\n\n```\n~~~']);+ });++ it('gives nothing for nothing', () => {+ expect(markdownBlocks('')).toEqual([]);+ expect(markdownBlocks('\n\n \n')).toEqual([]);+ });+});diff --git a/client/src/features/chat/__tests__/chatPane.test.tsx b/client/src/features/chat/__tests__/chatPane.test.tsxindex 881580e9..0591b9b4 100644--- a/client/src/features/chat/__tests__/chatPane.test.tsx+++ b/client/src/features/chat/__tests__/chatPane.test.tsx@@ -1,9 +1,10 @@/*** The shared chat against a fake server: it follows the session's runs* (subscribing while mounted), shows a message at once and the employee- * working until the run ends, holds the next message until then, says why a- * run failed, waits for Resume, and puts a message that did not go back in- * the box, where it survives leaving the conversation.+ * working until the run ends, streams the answer and its steps, holds the+ * next message until then (Send is Stop, and Esc stops too), says why a run+ * failed, waits for Resume, and puts a message that did not go back in the+ * box, where it survives leaving the conversation.*/import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -142,33 +143,144 @@ describe('ChatPane', () => {expect.objectContaining({ message: 'Any bookings today?', session_id: 'w1', client_message_id: expect.any(String) }),),);- expect(await screen.findByText('Working…')).toBeInTheDocument();- // The next message waits for this answer.+ expect(await screen.findByText('Thinking')).toBeInTheDocument();+ // The next message waits for this answer: Send is Stop meanwhile.type('And tomorrow?');- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Stop reply' })).toBeEnabled();runEvents(frame(1, 'started', { kind: 'message', user_message_id: 'm1' }));- expect(screen.getByText('Working…')).toBeInTheDocument();+ expect(screen.getByText('Thinking')).toBeInTheDocument();server.messages = [...server.messages, row('a_r1', 'assistant', 'Two, at **10** and at 3.', { run_id: 'r1' })];runEvents(frame(2, 'finished', { outcome: { type: 'success' }, result: { reply_message_id: 'a_r1' } }));await threadUpdated();expect(await screen.findByText('10', { selector: 'strong' })).toBeInTheDocument();- expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.queryByText('Thinking')).not.toBeInTheDocument();expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled();expect(screen.getAllByText('Any bookings today?')).toHaveLength(1);});+ it('streams the answer with a caret, then shows the saved one in its place', async () => {+ server.messages = [row('m1', 'user', 'Any bookings today?', { run_id: 'r1' })];+ server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];+ renderPane();+ expect(await screen.findByText('Thinking')).toBeInTheDocument();+ runEvents(+ frame(2, 'text.started', { message_id: 'r1.0.1' }),+ frame(3, 'text.content', { message_id: 'r1.0.1', delta: 'Two bookings:\n\n' }),+ frame(4, 'text.content', { message_id: 'r1.0.1', delta: '- 10:00 **Priya**' }),+ );+ expect(await screen.findByText('Priya', { selector: 'strong' })).toBeInTheDocument();+ expect(screen.getByText('Writing')).toBeInTheDocument();+ const streaming = document.querySelector('.chat-markdown[data-streaming]');+ expect(streaming).not.toBeNull();+ const answer = screen.getByText('Priya', { selector: 'strong' }).closest('[data-turn="assistant"]');++ server.messages = [...server.messages, row('a_r1', 'assistant', 'Two bookings:\n\n- 10:00 **Priya**', { run_id: 'r1' })];+ runEvents(+ frame(5, 'text.ended', { message_id: 'r1.0.1', final: true, reply_message_id: 'a_r1' }),+ frame(6, 'finished', { outcome: { type: 'success' }, result: { reply_message_id: 'a_r1' } }),+ );+ await threadUpdated();+ await waitFor(() => expect(document.querySelector('.chat-markdown[data-streaming]')).toBeNull());+ // One element from the first word to the saved reply.+ expect(screen.getByText('Priya', { selector: 'strong' }).closest('[data-turn="assistant"]')).toBe(answer);+ expect(screen.getAllByText('Priya', { selector: 'strong' })).toHaveLength(1);+ });++ it('shows the steps while they run and what they came to afterwards', async () => {+ server.messages = [row('m1', 'user', 'Check my calendar', { run_id: 'r1' })];+ server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];+ renderPane();+ await screen.findByText('Thinking');+ runEvents(frame(2, 'step.started', { step_id: 'c1', step_name: 'Checked Google Calendar' }));+ expect(screen.getByRole('button', { name: /Working…/ })).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Checked Google Calendar')).toBeInTheDocument();+ runEvents(frame(3, 'step.finished', { step_id: 'c1', state: 'done', detail: '3 events on Saturday', duration_ms: 900 }));+ expect(screen.getByText('3 events on Saturday')).toBeInTheDocument();++ server.messages = [+ ...server.messages,+ row('a_r1', 'assistant', 'You have three.', {+ run_id: 'r1',+ run: { run_id: 'r1', state: 'finished', outcome: 'success', steps: [{ step_id: 'c1', name: 'Checked Google Calendar', state: 'done', detail: '3 events on Saturday' }], duration_ms: 4_000 },+ }),+ ];+ runEvents(frame(4, 'finished', { outcome: { type: 'success' }, result: { reply_message_id: 'a_r1' }, duration_ms: 4_000, step_count: 1 }));+ await threadUpdated();+ expect(await screen.findByText('You have three.')).toBeInTheDocument();+ // Still open above the answer; it says how long and how many.+ const done = screen.getByRole('button', { name: 'Worked for 4s · 1 step' });+ expect(done).toHaveAttribute('aria-expanded', 'true');+ fireEvent.click(done);+ expect(done).toHaveAttribute('aria-expanded', 'false');+ });++ it('keeps the steps of an answer read back closed until opened', async () => {+ const run = { run_id: 'r1', state: 'finished', outcome: 'success', steps: [{ step_id: 'c1', name: 'Searched the web', state: 'done' }], duration_ms: 2_000 };+ server.messages = [row('m1', 'user', 'Find a florist', { run_id: 'r1', run }), row('a_r1', 'assistant', 'Try Bloom.', { run_id: 'r1', run })];+ renderPane();+ const steps = await screen.findByRole('button', { name: 'Worked for 2s · 1 step' });+ expect(steps).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByText('Searched the web')).not.toBeInTheDocument();+ fireEvent.click(steps);+ expect(screen.getByText('Searched the web')).toBeInTheDocument();+ });++ it('stops the answer from the Stop button or Esc', async () => {+ server.messages = [row('m1', 'user', 'Write me an essay', { run_id: 'r1' })];+ server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];+ const stopped: unknown[] = [];+ const answer = sendRequest.getMockImplementation()!;+ sendRequest.mockImplementation(async (kind: string, data: Wire) => {+ if (kind === 'stop_chat_run') {+ stopped.push(data);+ return { success: true, run_id: data.run_id, state: 'stopping' };+ }+ return answer(kind, data);+ });+ renderPane();+ await screen.findByText('Thinking');+ expect(screen.getByText('Esc')).toBeInTheDocument();++ fireEvent.keyDown(box(), { key: 'Escape' });+ await waitFor(() => expect(stopped).toEqual([{ run_id: 'r1' }]));+ expect(await screen.findByText('Stopping…')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Stopping' })).toBeDisabled();+ // Pressing it again changes nothing while it stops.+ fireEvent.keyDown(box(), { key: 'Escape' });+ expect(stopped).toHaveLength(1);++ runEvents(frame(2, 'custom', { name: 'opencompany.stopping', value: {} }), frame(3, 'finished', { outcome: { type: 'stopped' }, result: { no_reply: true } }));+ expect(await screen.findByText('You stopped this reply.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Send' })).toBeInTheDocument();+ });++ it('says so when Stop did not reach the server', async () => {+ server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];+ server.messages = [row('m1', 'user', 'Hi', { run_id: 'r1' })];+ const answer = sendRequest.getMockImplementation()!;+ sendRequest.mockImplementation(async (kind: string, data: Wire) => {+ if (kind === 'stop_chat_run') throw new Error('socket closed');+ return answer(kind, data);+ });+ const chat = host();+ renderPane(chat);+ fireEvent.click(await screen.findByRole('button', { name: 'Stop reply' }));+ await waitFor(() => expect(chat.notify).toHaveBeenCalledWith('Couldn’t stop the reply. Try again.', 'error'));+ });+it('says why a run failed, with what to do about it', async () => {server.messages = [row('m1', 'user', 'Book Priya in', { run_id: 'r1' })];server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];renderPane();- expect(await screen.findByText('Working…')).toBeInTheDocument();+ expect(await screen.findByText('Thinking')).toBeInTheDocument();runEvents(frame(2, 'failed', { message: 'Calendar said no', code: 'run_failed', hint: 'Reconnect Google' }));expect(screen.getByText('Maya couldn’t answer.')).toBeInTheDocument();expect(screen.getByText('Calendar said no')).toBeInTheDocument();expect(screen.getByText('Reconnect Google')).toBeInTheDocument();- expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.queryByText('Thinking')).not.toBeInTheDocument();});it('shows how an earlier run ended after a reload', async () => {@@ -188,10 +300,10 @@ describe('ChatPane', () => {await write('Call me back');fireEvent.keyDown(box(), { key: 'Enter' });expect(await screen.findByText('Waiting for you to resume Maya.')).toBeInTheDocument();- expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.queryByText('Thinking')).not.toBeInTheDocument();runEvents(frame(1, 'started', { kind: 'message' }));- expect(await screen.findByText('Working…')).toBeInTheDocument();+ expect(await screen.findByText('Thinking')).toBeInTheDocument();});it('puts a message that did not go back in the box, and lets the host say why', async () => {diff --git a/client/src/features/chat/__tests__/copy.test.ts b/client/src/features/chat/__tests__/copy.test.tsindex 6a77cdfd..a2de5d52 100644--- a/client/src/features/chat/__tests__/copy.test.ts+++ b/client/src/features/chat/__tests__/copy.test.ts@@ -1,12 +1,12 @@/*** What a turn says: when a message was written, why a run did not answer,- * and what a working run is doing.+ * what a working run is doing and showing, and its steps.*/import { describe, expect, it } from 'vitest';-import { emptyRun } from '@/lib/agui/reduceRun';+import { emptyRun, type RunSnapshot, type RunStep } from '@/lib/agui/reduceRun';import { timeLabel } from '../thread/timeLabel';-import { failureLines, liveLabel, streamedText } from '../turns/runCopy';+import { failureLines, liveLabel, liveText, stepDetail, workLabel, writingRate } from '../turns/runCopy';describe('timeLabel', () => {const now = new Date(2026, 8, 28, 15, 30);@@ -58,20 +58,52 @@ describe('failureLines', () => {describe('a working run', () => {it('says what it is doing', () => {const working = { ...emptyRun('r1', 'w1'), state: 'running' as const };- expect(liveLabel(working, false)).toBe('Working…');- expect(liveLabel(working, true)).toBe('Writing…');+ expect(liveLabel(working, false)).toBe('Thinking');+ expect(liveLabel(working, true)).toBe('Writing');expect(liveLabel({ ...working, state: 'stopping' }, true)).toBe('Stopping…');});- it('shows the reply it streamed, not its narration', () => {- const run = {- ...emptyRun('r1', 'w1'),- segments: [- { messageId: 'n', text: 'Let me look.', final: false },- { messageId: 'a', text: 'Two bookings', final: null },- ],- };- expect(streamedText(run)).toBe('Two bookings');- expect(streamedText(null)).toBe('');+ it('says how fast the answer comes, once a second has passed', () => {+ expect(writingRate(400, 2_000)).toBe('· 50 tok/s');+ expect(writingRate(400, 500)).toBeNull();+ expect(writingRate(0, 5_000)).toBeNull();+ });++ it('shows the latest text until the answer comes, then the answer', () => {+ const run = (segments: RunSnapshot['segments']) => ({ ...emptyRun('r1', 'w1'), segments });+ const narration = { messageId: 'n', text: 'Let me look.', final: false };+ expect(liveText(run([narration]))).toEqual({ text: 'Let me look.', streaming: false, narration: true });+ expect(liveText(run([narration, { messageId: 'a', text: 'Two bookings', final: null }]))).toEqual({+ text: 'Two bookings',+ streaming: true,+ narration: false,+ });+ expect(liveText(run([narration, { messageId: 'a', text: 'Two bookings.', final: true }]))).toEqual({+ text: 'Two bookings.',+ streaming: false,+ narration: false,+ });+ expect(liveText(null)).toEqual({ text: '', streaming: false, narration: false });+ expect(liveText(run([{ messageId: 'a', text: ' ', final: null }])).text).toBe('');+ });+});++describe('working steps', () => {+ const step = (stepId: string, state: RunStep['state'], detail?: string): RunStep => ({ stepId, name: stepId, state, ...(detail ? { detail } : {}) });++ it('say “Working…” while they come, then how long and how many', () => {+ const steps = [step('a', 'done'), step('b', 'failed'), step('c', 'skipped')];+ expect(workLabel(steps, true, null)).toBe('Working…');+ expect(workLabel(steps, false, 12_400)).toBe('Worked for 12s · 2 steps');+ expect(workLabel([step('a', 'done')], false, 200)).toBe('Worked for 1s · 1 step');+ expect(workLabel(steps, false, 125_000)).toBe('Worked for 2m 5s · 2 steps');+ expect(workLabel(steps, false, null)).toBe('Worked for 1s · 2 steps');+ });++ it('say what each step found', () => {+ expect(stepDetail(step('a', 'done', '3 events on Saturday'))).toBe('3 events on Saturday');+ expect(stepDetail(step('a', 'done'))).toBeNull();+ expect(stepDetail(step('a', 'failed', 'quota'))).toBe('Failed · quota');+ expect(stepDetail(step('a', 'skipped', 'x'))).toBe('Skipped');});});diff --git a/client/src/features/chat/__tests__/model.test.ts b/client/src/features/chat/__tests__/model.test.tsindex c45f81e5..7db1c092 100644--- a/client/src/features/chat/__tests__/model.test.ts+++ b/client/src/features/chat/__tests__/model.test.ts@@ -38,6 +38,8 @@ const messageRun = (runId: string, state: MessageRun['state'], error: MessageRunstate,outcome: state === 'finished' ? 'success' : null,error,+ steps: [],+ durationMs: null,});function shape(turns: ReturnType<typeof buildTurns>) {@@ -143,4 +145,37 @@ describe('buildTurns', () => {});expect(shape(turns)).toEqual(['user:m9', 'assistant:-:queued', 'assistant:-:running']);});++ it('keeps a run’s steps on its first turn, working and after', () => {+ const steps = [{ stepId: 'c1', name: 'Searched the web', state: 'done' as const }];+ const user = message('m1', 'user', { runId: 'r1' });+ const working = buildTurns([user], { r1: run('r1', { state: 'running', steps }) });+ const live = working[1];+ expect(live.kind === 'assistant' && live.work).toEqual({ steps, live: true, durationMs: null });++ const answers = [user, message('a1', 'assistant', { runId: 'r1' }), message('a2', 'assistant', { runId: 'r1' })];+ const done = buildTurns(answers, {+ r1: run('r1', { state: 'finished', steps, startedAt: '2026-10-03T09:00:00Z', finishedAt: '2026-10-03T09:00:12Z' }),+ });+ expect(done.map((turn) => (turn.kind === 'assistant' ? turn.work : undefined))).toEqual([+ undefined,+ { steps, live: false, durationMs: 12_000 },+ null,+ ]);+ // A run that took no steps has none to show.+ const plain = buildTurns([user, message('a1', 'assistant', { runId: 'r1' })], { r1: run('r1', { state: 'finished' }) });+ expect(plain[1].kind === 'assistant' && plain[1].work).toBeNull();+ });++ it('reads the steps a thread sent after a reload', () => {+ const withSteps: MessageRun = {+ ...messageRun('r1', 'finished'),+ steps: [{ stepId: 'c1', name: 'Checked Google Calendar', state: 'done', detail: '3 events' }],+ durationMs: 8_000,+ };+ const thread = [message('m1', 'user', { runId: 'r1', run: withSteps }), message('a1', 'assistant', { runId: 'r1', run: withSteps })];+ const turns = buildTurns(thread, knownRuns('w1', thread, {}, true));+ const answer = turns[1];+ expect(answer.kind === 'assistant' && answer.work).toEqual({ steps: withSteps.steps, live: false, durationMs: 8_000 });+ });});diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsxindex d3c759f9..636e4b8c 100644--- a/client/src/features/chat/composer/Composer.tsx+++ b/client/src/features/chat/composer/Composer.tsx@@ -1,15 +1,17 @@/*** The message box (design handoff chat, "Composer"): a text box that grows* with what is written, up to `--h-chat-composer-max`, then scrolls; and- * Send. Enter sends, Shift+Enter starts a new line, and the Enter that- * confirms an input method's composition never sends (lib/composerKeys).+ * Send, which becomes Stop while the employee is answering. Enter sends,+ * Shift+Enter starts a new line, and the Enter that confirms an input+ * method's composition never sends (lib/composerKeys). Esc stops an answer+ * (ChatPane).** What is written lives in the composer store per conversation, so it* survives switching to another employee and back. While the employee is* still answering the last message the box takes text but Send waits.*/-import { ArrowUp } from 'lucide-react';+import { ArrowUp, Square } from 'lucide-react';import type { KeyboardEvent, RefObject } from 'react';import { Button } from '@/components/ui/button';import { Textarea } from '@/components/ui/textarea';@@ -26,12 +28,16 @@ export interface ComposerProps {/** A message is on its way, or the employee is still answering one. */busy: boolean;onSend: () => void;+ /** Stops the answer under way; absent while there is none. */+ onStop?: () => void;+ /** The answer is already stopping. */+ stopping?: boolean;compact: boolean;/** The text box, for the host's focus requests. */boxRef: RefObject<HTMLTextAreaElement | null>;}-export function Composer({ sessionId, name, ready, busy, onSend, compact, boxRef }: ComposerProps) {+export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef }: ComposerProps) {const draft = useComposerDraft(sessionId);const setText = useComposerStore((state) => state.setText);useAutoGrow(boxRef, draft.text);@@ -43,7 +49,20 @@ export function Composer({ sessionId, name, ready, busy, onSend, compact, boxRefif (canSend) onSend();};- const send = (+ const iconSize = compact ? 'size-3.5' : 'size-4';+ const button = onStop ? (+ <Button+ variant="invert"+ size="icon"+ disabled={stopping}+ onClick={onStop}+ aria-label={stopping ? 'Stopping' : 'Stop reply'}+ title={stopping ? 'Stopping…' : 'Stop (Esc)'}+ className={cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5')}+ >+ <Square aria-hidden fill="currentColor" strokeWidth={0} className={compact ? 'size-2.75' : 'size-3'} />+ </Button>+ ) : (<Buttonvariant="invert"size="icon"@@ -53,7 +72,7 @@ export function Composer({ sessionId, name, ready, busy, onSend, compact, boxReftitle={busy ? `${name} is still answering` : 'Send (Enter)'}className={cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5')}>- <ArrowUp aria-hidden strokeWidth={2.25} className={compact ? 'size-3.5' : 'size-4'} />+ <ArrowUp aria-hidden strokeWidth={2.25} className={iconSize} /></Button>);@@ -78,7 +97,7 @@ export function Composer({ sessionId, name, ready, busy, onSend, compact, boxRefcompact ? 'py-1 text-sm leading-normal' : 'py-1.5 text-md leading-normal',)}/>- {compact ? send : <div className="flex items-center justify-end gap-1.5">{send}</div>}+ {compact ? button : <div className="flex items-center justify-end gap-1.5">{button}</div>}</div>);}diff --git a/client/src/features/chat/data/schemas.ts b/client/src/features/chat/data/schemas.tsindex cb43031f..99c10cd3 100644--- a/client/src/features/chat/data/schemas.ts+++ b/client/src/features/chat/data/schemas.ts@@ -8,16 +8,19 @@import { z } from 'zod';import type { RunError, RunState } from '@/lib/agui/events';import { parseError } from '@/lib/agui/events';-import { snapshotFromWire, type RunSnapshot } from '@/lib/agui/reduceRun';+import { snapshotFromWire, stepsFromWire, type RunSnapshot, type RunStep } from '@/lib/agui/reduceRun';const RUN_STATES = ['queued', 'pending', 'running', 'stopping', 'finished', 'error', 'stopped'] as const;-/** How the run a message started or answers ended (or is going). */+/** How the run a message started or answers ended (or is going), what the+ * employee did on the way and how long it took. */export interface MessageRun {runId: string;state: RunState;outcome: string | null;error: RunError | null;+ steps: RunStep[];+ durationMs: number | null;}const messageRunSchema = z@@ -26,6 +29,8 @@ const messageRunSchema = zstate: z.enum(RUN_STATES).catch('finished'),outcome: z.string().nullable().catch(null),error: z.record(z.string(), z.unknown()).nullable().catch(null),+ steps: z.unknown().optional(),+ duration_ms: z.number().nonnegative().nullable().optional().catch(null),}).transform((run): MessageRun => ({@@ -33,6 +38,8 @@ const messageRunSchema = zstate: run.state,outcome: run.outcome,error: run.error ? parseError(run.error) : null,+ steps: stepsFromWire(run.steps),+ durationMs: run.duration_ms ?? null,}),);diff --git a/client/src/features/chat/data/stop.ts b/client/src/features/chat/data/stop.tsnew file mode 100644index 00000000..f60e39d3--- /dev/null+++ b/client/src/features/chat/data/stop.ts@@ -0,0 +1,43 @@+/**+ * Stopping the run that is answering (`stop_chat_run`). One nothing picked+ * up yet ends at once; a working one stops at its next step and keeps what+ * it wrote. The run's own events say what happens next; the server's answer+ * is applied at once too, so the Stop button settles without waiting for+ * them. A run that ended meanwhile (`not_stoppable`) is not a failure.+ */++import { useMutation } from '@tanstack/react-query';+import { useWebSocketActions } from '@/contexts/WebSocketContext';+import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';+import { useChatRunStore } from '@/stores/chatRunStore';++type StopReply = { success?: boolean; error?: string; state?: string };++export function useStopChatRun(sessionId: string, onFailed?: () => void) {+ const { sendRequest } = useWebSocketActions();+ return useMutation<string, Error, RunSnapshot>({+ mutationFn: async (run) => {+ let reply: StopReply | undefined;+ try {+ reply = await sendRequest<StopReply>('stop_chat_run', { run_id: run.runId });+ } catch {+ throw new Error('transport');+ }+ if (reply?.success === false) throw new Error(reply.error || 'stop_failed');+ return typeof reply?.state === 'string' ? reply.state : 'stopping';+ },+ onSuccess: (state, run) => {+ const store = useChatRunStore.getState();+ const current = store.sessions[sessionId]?.runs[run.runId] ?? run;+ if (!isLiveRun(current)) return;+ if (state === 'stopped') {+ store.upsertRun({ ...current, state: 'stopped', outcome: { type: 'stopped', interrupts: [] }, result: { noReply: true } });+ } else if (state === 'stopping' && current.state !== 'stopping') {+ store.upsertRun({ ...current, state: 'stopping' });+ }+ },+ onError: (error) => {+ if (error.message !== 'not_stoppable') onFailed?.();+ },+ });+}diff --git a/client/src/features/chat/markdown/ReplyMarkdown.tsx b/client/src/features/chat/markdown/ReplyMarkdown.tsxindex 56acc385..68ba0f61 100644--- a/client/src/features/chat/markdown/ReplyMarkdown.tsx+++ b/client/src/features/chat/markdown/ReplyMarkdown.tsx@@ -4,6 +4,11 @@* chunk: the thread loads it lazily, so the markdown stack stays out of the* first load. Links open in a new tab, and images from outside the workspace* wait for the owner (CHAT_MARKDOWN_COMPONENTS).+ *+ * While the answer streams (`streaming`), it is rendered block by block+ * (markdown/blocks.ts): a finished block renders once, only the growing last+ * one again with each delta, and a caret follows the text+ * (`.chat-markdown[data-streaming]` in index.css).*/import Prism from 'prismjs';@@ -13,10 +18,12 @@ import 'prismjs/components/prism-markdown';import 'prismjs/components/prism-python';import 'prismjs/components/prism-typescript';import 'prismjs/components/prism-yaml';+import { memo, useMemo } from 'react';import ReactMarkdown, { type Components } from 'react-markdown';import remarkBreaks from 'remark-breaks';import remarkGfm from 'remark-gfm';import { cn } from '@/lib/utils';+import { markdownBlocks } from './blocks';import { CHAT_MARKDOWN_COMPONENTS } from './components';const REMARK_PLUGINS = [remarkGfm, remarkBreaks];@@ -58,12 +65,21 @@ const CodeBlock: Components['code'] = ({ node: _node, className, children, ...prconst COMPONENTS: Components = { ...CHAT_MARKDOWN_COMPONENTS, code: CodeBlock };-export default function ReplyMarkdown({ text, className }: { text: string; className?: string }) {+const Block = memo(function Block({ text }: { text: string }) {return (- <div className={cn('chat-markdown min-w-0', className)}>- <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={COMPONENTS}>- {text}- </ReactMarkdown>+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={COMPONENTS}>+ {text}+ </ReactMarkdown>+ );+});++export default function ReplyMarkdown({ text, streaming = false, className }: { text: string; streaming?: boolean; className?: string }) {+ const blocks = useMemo(() => (streaming ? markdownBlocks(text) : [text]), [text, streaming]);+ return (+ <div className={cn('chat-markdown min-w-0', className)} data-streaming={streaming || undefined}>+ {blocks.map((block, index) => (+ <Block key={index} text={block} />+ ))}</div>);}diff --git a/client/src/features/chat/markdown/blocks.ts b/client/src/features/chat/markdown/blocks.tsnew file mode 100644index 00000000..d3ccc5ce--- /dev/null+++ b/client/src/features/chat/markdown/blocks.ts@@ -0,0 +1,36 @@+/**+ * A streaming answer cut into its blocks: at blank lines, never inside a+ * fenced code block. While the answer streams, ReplyMarkdown renders each+ * finished block once and re-renders only the last, which is still growing.+ */++const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;+const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/;++export function markdownBlocks(text: string): string[] {+ const blocks: string[] = [];+ let current: string[] = [];+ let fence: string | null = null;+ for (const line of text.split('\n')) {+ if (fence !== null) {+ current.push(line);+ const close = FENCE_CLOSE.exec(line)?.[1];+ if (close && close[0] === fence[0] && close.length >= fence.length) fence = null;+ continue;+ }+ const open = FENCE_OPEN.exec(line)?.[1];+ if (open) {+ fence = open;+ current.push(line);+ continue;+ }+ if (line.trim() === '') {+ if (current.length > 0) blocks.push(current.join('\n'));+ current = [];+ continue;+ }+ current.push(line);+ }+ if (current.length > 0) blocks.push(current.join('\n'));+ return blocks;+}diff --git a/client/src/features/chat/thread/ChatThread.tsx b/client/src/features/chat/thread/ChatThread.tsxindex f0ce7452..fed5df7e 100644--- a/client/src/features/chat/thread/ChatThread.tsx+++ b/client/src/features/chat/thread/ChatThread.tsx@@ -50,6 +50,8 @@ export interface ChatThreadProps {emptyState?: ReactNode;liveNote?: string | null;compact: boolean;+ /** Esc stops a working run here, so its status line says so. */+ canStop?: boolean;onScrolledChange?: (scrolled: boolean) => void;}@@ -64,6 +66,7 @@ export function ChatThread({emptyState,liveNote,compact,+ canStop = false,onScrolledChange,}: ChatThreadProps) {const scrollRef = useRef<HTMLDivElement>(null);@@ -192,11 +195,13 @@ export function ChatThread({<AssistantTurnmessage={turn.message}run={turn.run}+ work={turn.work}persona={persona}now={now}latest={latest}compact={compact}liveNote={liveNote}+ canStop={canStop}/>)}</div>diff --git a/client/src/features/chat/thread/model.ts b/client/src/features/chat/thread/model.tsindex fa38481b..5f74ef87 100644--- a/client/src/features/chat/thread/model.ts+++ b/client/src/features/chat/thread/model.ts@@ -11,18 +11,30 @@* run ended before the subscription; `useThreadRunReconcile` reads it).* - **Turns.** One per message, in order, with a divider wherever the* employee restarted between two messages (their generation, `runKey`,- * changed). A run that is going, failed or was stopped shows on its last- * answer, or, before it has answered, on a turn of its own right after its- * last message (a live run whose messages are out of view goes last).+ * changed). A run that is going, failed or was stopped (or has finished+ * and its answer is on the way) shows on its last answer, or, before it+ * has answered, on a turn of its own right after its last message (a live+ * run whose messages are out of view goes last).* - **Keys.** A message sent from this tab keeps its key when the saved row* replaces it (both carry its `clientMessageId`), and a run's first answer* has the key the run's own turn had, so the text it streamed and the* saved reply are one element.+ * - **Work.** What the employee did on the way (the run's steps, how long it+ * took) goes on that same first turn, so it stays above the answer once the+ * run has ended.*/-import { emptyRun, isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';+import { emptyRun, isLiveRun, workedMs, type RunSnapshot, type RunStep } from '@/lib/agui/reduceRun';import type { ChatMessage, MessageRun } from '../data/schemas';+/** A run's working steps as its turn shows them. */+export interface TurnWork {+ steps: RunStep[];+ /** Still working: the steps are still coming. */+ live: boolean;+ durationMs: number | null;+}+export type ChatTurn =| { kind: 'divider'; key: string }| { kind: 'user'; key: string; message: ChatMessage }@@ -34,6 +46,8 @@ export type ChatTurn =/** The run whose state this turn shows (working, failed, stopped):* set on the run's last turn only. */run: RunSnapshot | null;+ /** The run's steps, on its first turn; null when it took none. */+ work: TurnWork | null;};/** Run failures that are not news: the conversation itself went away. */@@ -51,9 +65,16 @@ function fromMessage(message: ChatMessage, run: MessageRun, sessionId: string):? { type: run.outcome, interrupts: [] }: null,error: run.error,+ steps: run.steps,+ durationMs: run.durationMs,};}+function workOf(run: RunSnapshot | undefined): TurnWork | null {+ if (!run || run.steps.length === 0) return null;+ return { steps: run.steps, live: isLiveRun(run), durationMs: workedMs(run) };+}+/*** Every run the thread refers to, by id, at its freshest.* `synced`: the session's subscription has answered, so `store` knows every@@ -87,9 +108,13 @@ function shows(run: RunSnapshot, answered: boolean): boolean {return !SILENT_FAILURES.has(code) && !(answered && NO_ANSWER_FAILURES.has(code));}if (run.state === 'stopped') return true;- // Finished: only while its answer is still on the way to the thread.+ // Finished: only while its answer is still on the way to the thread, with+ // something to show meanwhile (what it streamed, the steps it took).if (answered || run.result.noReply) return false;- return run.segments.some((segment) => segment.final !== false && segment.text.length > 0);+ return (+ run.segments.some((segment) => segment.final !== false && segment.text.length > 0) ||+ (Boolean(run.result.replyMessageId) && run.steps.length > 0)+ );}function runOrder(run: RunSnapshot): string {@@ -127,29 +152,31 @@ export function buildTurns(messages: readonly ChatMessage[], runs: Readonly<Recoif (message.role === 'user') {turns.push({ kind: 'user', key: `user:${message.clientMessageId ?? message.id}`, message });if (runId && showing.has(runId) && !lastAnswer.has(runId) && lastIndex.get(runId) === index) {- turns.push({ kind: 'assistant', key: `run:${runId}`, message: null, run: runs[runId] });+ turns.push({ kind: 'assistant', key: `run:${runId}`, message: null, run: runs[runId], work: workOf(runs[runId]) });placed.add(runId);keyed.add(runId);}return;}- // A run's first answer takes the key its own turn had.+ // A run's first answer takes the key its own turn had, and its work.let key = `reply:${message.id}`;+ let work: TurnWork | null = null;if (runId && !keyed.has(runId)) {key = `run:${runId}`;+ work = workOf(runs[runId]);keyed.add(runId);}const last = Boolean(runId && lastAnswer.get(runId) === index);const run = runId && last && showing.has(runId) ? runs[runId] : null;if (run) placed.add(run.runId);- turns.push({ kind: 'assistant', key, message, run });+ turns.push({ kind: 'assistant', key, message, run, work });});const unplaced = [...showing].map((runId) => runs[runId]).filter((run) => !placed.has(run.runId) && isLiveRun(run)).sort((a, b) => runOrder(a).localeCompare(runOrder(b)));- for (const run of unplaced) turns.push({ kind: 'assistant', key: `run:${run.runId}`, message: null, run });+ for (const run of unplaced) turns.push({ kind: 'assistant', key: `run:${run.runId}`, message: null, run, work: workOf(run) });return turns;}diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsxindex 0e826ec0..9f739c3e 100644--- a/client/src/features/chat/turns/AssistantTurn.tsx+++ b/client/src/features/chat/turns/AssistantTurn.tsx@@ -1,9 +1,14 @@/*** The employee's side of a turn (design handoff chat, "Assistant row"):- * their avatar on the left and, with no bubble, what they said in markdown.- * While their run works the avatar spins its ring and skeleton lines stand- * in for text that has not come yet, with a status line under; a run that- * waits for Resume, failed or was stopped says so where its answer would be.+ * their avatar on the left and, with no bubble, in order: what they did on+ * the way (the steps disclosure), and what they said in markdown.+ *+ * While their run works the avatar spins its ring; skeleton lines stand in+ * for text that has not come yet; the answer streams in with a caret after+ * it; and a status line says "Thinking" or "Writing · N tok/s" and that Esc+ * stops it. Text written beside tool calls shows muted until the answer+ * replaces it. A run that waits for Resume, failed or was stopped says so+ * where its answer would be.** `chat-msg chat-msg-bot` (on the text only) is the theme hook the stylized* themes paint as a bubble.@@ -16,10 +21,13 @@ import { cn } from '@/lib/utils';import type { ChatMessage } from '../data/schemas';import type { ChatPersona } from '../host';import { ChatAvatar } from '../thread/ChatAvatar';+import type { TurnWork } from '../thread/model';import { timeLabel } from '../thread/timeLabel';-import { failureLines, liveLabel, streamedText } from './runCopy';+import { failureLines, liveLabel, liveText } from './runCopy';import { StatusLine } from './StatusLine';+import { StepsDisclosure } from './StepsDisclosure';import { TurnMeta } from './TurnMeta';+import { useWritingRate } from './useWritingRate';// Its own chunk: the markdown stack stays out of the first load.const ReplyMarkdown = lazy(() => import('../markdown/ReplyMarkdown'));@@ -47,24 +55,34 @@ function Note({ icon, tone = 'muted', children }: { icon: 'alert' | 'pause' | 'sexport function AssistantTurn({message,run,+ work,persona,now,latest,compact,liveNote,+ canStop = false,}: {message: ChatMessage | null;run: RunSnapshot | null;+ work: TurnWork | null;persona: ChatPersona;now: Date;latest: boolean;compact: boolean;/** Said on the status line while the run works (an automatic retry). */liveNote?: string | null;+ /** The pane stops a working run on Esc, so the status line says so. */+ canStop?: boolean;}) {const queued = run?.state === 'queued';const live = Boolean(run && isLiveRun(run) && !queued);- const text = message ? message.text : streamedText(run);+ // A saved answer is the answer; until then, what the run streamed.+ const streamed = liveText(message ? null : run);+ const text = message ? message.text : streamed.text;+ const streaming = live && streamed.streaming;+ const narration = streamed.narration;+ const rate = useWritingRate(text, streaming, now);const failure = run?.state === 'error' ? failureLines(run.error, persona.name) : null;return (@@ -77,16 +95,30 @@ export function AssistantTurn({><ChatAvatar persona={persona} live={live} compact={compact} /><div className="flex min-w-0 flex-1 flex-col gap-2.5">+ {work && <StepsDisclosure work={work} compact={compact} />}{live && !text && <Thinking />}{text && (- <div className={cn('chat-msg chat-msg-bot text-fg-default wrap-anywhere', compact ? 'leading-normal' : 'text-md leading-relaxed')}>+ <div+ data-narration={narration || undefined}+ className={cn(+ 'chat-msg chat-msg-bot wrap-anywhere',+ narration ? 'text-fg-muted' : 'text-fg-default',+ compact ? 'leading-normal' : 'text-md leading-relaxed',+ )}+ ><Suspense fallback={<p className="m-0 whitespace-pre-wrap">{text}</p>}>- <ReplyMarkdown text={text} />+ <ReplyMarkdown text={text} streaming={streaming} /></Suspense></div>)}{live && run && (- <StatusLine label={liveLabel(run, Boolean(text))} note={liveNote} compact={compact} />+ <StatusLine+ label={liveLabel(run, streaming)}+ rate={rate}+ note={liveNote}+ stopHint={canStop && run.state !== 'stopping'}+ compact={compact}+ />)}{queued && (<Note icon="pause">diff --git a/client/src/features/chat/turns/StatusLine.tsx b/client/src/features/chat/turns/StatusLine.tsxindex bd7fe835..09eae180 100644--- a/client/src/features/chat/turns/StatusLine.tsx+++ b/client/src/features/chat/turns/StatusLine.tsx@@ -1,21 +1,48 @@/*** What a working employee is doing, under their turn (design handoff chat,- * "Streaming": three dots and a label). A status region, so a screen reader- * hears it change.+ * "Streaming"): three dots, a label ("Thinking", "Writing"), how fast the+ * answer comes, and, while it can be stopped, that Esc stops it. A status+ * region, so a screen reader hears the label change (the rate and the hint+ * are left out of it).*/import { cn } from '@/lib/utils';-export function StatusLine({ label, note, compact = false }: { label: string; note?: string | null; compact?: boolean }) {+export function StatusLine({+ label,+ note,+ rate,+ stopHint = false,+ compact = false,+}: {+ label: string;+ note?: string | null;+ rate?: string | null;+ stopHint?: boolean;+ compact?: boolean;+}) {return (- <div role="status" className={cn('flex min-w-0 items-center gap-2 font-mono text-xs text-fg-faint', compact && 'text-2xs')}>+ <div className={cn('flex min-w-0 items-center gap-2 font-mono text-xs text-fg-faint', compact && 'text-2xs')}><span aria-hidden className="opencompany-dots flex shrink-0 gap-0.75"><span className="size-1 rounded-full bg-action-tools-ink" /><span className="size-1 rounded-full bg-action-tools-ink" /><span className="size-1 rounded-full bg-action-tools-ink" /></span>- <span className="shrink-0 text-fg-muted">{label}</span>+ <span role="status" className="shrink-0 text-fg-muted">+ {label}+ </span>+ {rate && (+ <span aria-hidden className="shrink-0">+ {rate}+ </span>+ )}{note && <span className="min-w-0 truncate font-body">{note}</span>}+ {stopHint && (+ <span aria-hidden className="ml-auto flex shrink-0 items-center gap-1.5">+ Stop+ <kbd className="rounded-sm border border-border-default bg-bg-panel px-1.25 py-px font-mono text-2xs text-fg-muted">Esc</kbd>+ </span>+ )}</div>);}diff --git a/client/src/features/chat/turns/StepsDisclosure.tsx b/client/src/features/chat/turns/StepsDisclosure.tsxnew file mode 100644index 00000000..437bd116--- /dev/null+++ b/client/src/features/chat/turns/StepsDisclosure.tsx@@ -0,0 +1,87 @@+/**+ * What the employee did while answering (design handoff chat, "working+ * steps"): a pill that says "Working…" while the steps come and "Worked for+ * 12s · 3 steps" after, opening to the list: each step's name, what it found,+ * and a spinner, tick or cross. Open from when the run is seen working;+ * closed when read back later, until the owner opens it.+ */++import { Check, ChevronDown, Minus, X } from 'lucide-react';+import { useState } from 'react';+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';+import type { RunStep } from '@/lib/agui/reduceRun';+import { cn } from '@/lib/utils';+import type { TurnWork } from '../thread/model';+import { stepDetail, workLabel } from './runCopy';++function Spinner({ className }: { className?: string }) {+ return (+ <span+ aria-hidden+ className={cn('opencompany-spinner block shrink-0 rounded-full border-2 border-action-tools-soft border-t-action-tools-ink', className)}+ />+ );+}++function StepIcon({ step }: { step: RunStep }) {+ if (step.state === 'running') return <Spinner className="size-2.5 border-border-default" />;+ if (step.state === 'failed') return <X aria-hidden className="size-3 text-action-stop-ink" strokeWidth={2.2} />;+ if (step.state === 'skipped') return <Minus aria-hidden className="size-3 text-fg-faint" strokeWidth={2.2} />;+ return <Check aria-hidden className="size-3 text-action-run-ink" strokeWidth={2.2} />;+}++function StepRow({ step }: { step: RunStep }) {+ const detail = stepDetail(step);+ return (+ <li+ data-step={step.stepId}+ data-state={step.state}+ className={cn('flex items-start gap-2.5 py-1.25 transition-opacity duration-(--dur-default)', step.state === 'skipped' && 'opacity-40')}+ >+ <span className="grid size-5.5 shrink-0 place-items-center rounded-md border border-border-default bg-bg-panel">+ <StepIcon step={step} />+ </span>+ <span className="flex min-w-0 flex-col gap-px">+ <span className="text-sm font-medium text-fg-default">{step.name}</span>+ {detail && <span className="font-mono text-xs wrap-anywhere text-fg-faint">{detail}</span>}+ </span>+ </li>+ );+}++export function StepsDisclosure({ work, compact = false }: { work: TurnWork; compact?: boolean }) {+ // Open while working, and still open once the answer is in; a run read+ // back later starts closed. The owner's own choice wins either way.+ const [chosen, setChosen] = useState<boolean | null>(work.live ? true : null);+ const open = chosen ?? work.live;+ const label = workLabel(work.steps, work.live, work.durationMs);++ return (+ <Collapsible open={open} onOpenChange={setChosen} className="flex max-w-full flex-col self-start">+ <CollapsibleTrigger+ className={cn(+ 'flex h-7 items-center gap-2 self-start rounded-pill border border-border-default bg-transparent pr-2.5 pl-2 text-xs font-medium whitespace-nowrap text-fg-muted transition-colors duration-(--dur-default) hover:bg-bg-hover hover:text-fg-default',+ compact && 'h-6 text-2xs',+ )}+ >+ {work.live ? (+ <Spinner className="size-3" />+ ) : (+ <Check aria-hidden className="size-3.25 text-action-run-ink" strokeWidth={2.4} />+ )}+ <span className={cn(work.live && 'opencompany-shimmer-text')}>{label}</span>+ <ChevronDown+ aria-hidden+ className={cn('size-3.25 transition-transform duration-(--dur-default) ease-(--ease-spring)', open && 'rotate-180')}+ />+ </CollapsibleTrigger>+ <CollapsibleContent>+ <ol aria-label="Steps" className="m-0 mt-2 mb-0.5 ml-3.25 flex list-none flex-col border-l border-border-default p-0 pl-4">+ {work.steps.map((step) => (+ <StepRow key={step.stepId} step={step} />+ ))}+ </ol>+ </CollapsibleContent>+ </Collapsible>+ );+}diff --git a/client/src/features/chat/turns/runCopy.ts b/client/src/features/chat/turns/runCopy.tsindex 32f79db4..7d23d4a6 100644--- a/client/src/features/chat/turns/runCopy.ts+++ b/client/src/features/chat/turns/runCopy.ts@@ -5,17 +5,34 @@*/import type { RunError } from '@/lib/agui/events';-import type { RunSnapshot } from '@/lib/agui/reduceRun';+import type { RunSnapshot, RunStep } from '@/lib/agui/reduceRun';-/** What a run that has not answered streamed so far: its reply text, not- * the narration beside its tool calls. */-export function streamedText(run: RunSnapshot | null): string {- if (!run) return '';- return run.segments- .filter((segment) => segment.final !== false)- .map((segment) => segment.text)- .join('\n\n')- .trim();+/** The text a run that has not posted its answer shows. */+export interface LiveText {+ text: string;+ /** Still arriving: the caret follows it. */+ streaming: boolean;+ /** Written beside tool calls, not the answer (shown muted until the+ * answer replaces it). */+ narration: boolean;+}++/**+ * The run's answer as it streamed; before any, the latest thing it wrote,+ * which may turn out to be narration beside its tool calls ("Let me check+ * the calendar.") and gives way to the next.+ */+export function liveText(run: RunSnapshot | null): LiveText {+ const none: LiveText = { text: '', streaming: false, narration: false };+ if (!run || run.segments.length === 0) return none;+ const answer = run.segments.filter((segment) => segment.final === true);+ const last = run.segments.at(-1)!;+ if (answer.length > 0 && last.final === true) {+ return { text: answer.map((segment) => segment.text).join('\n\n').trim(), streaming: false, narration: false };+ }+ const text = last.text.trim();+ if (!text) return none;+ return { text, streaming: last.final === null, narration: last.final === false };}/** A failed run in the owner's words: the server's codes for a message@@ -34,8 +51,39 @@ export function failureLines(error: RunError | null, name: string): { headline:}}-/** The status line's label while a run works. */-export function liveLabel(run: RunSnapshot, hasText: boolean): string {+/** The status line's label while a run works (design handoff: "Thinking"+ * until text comes, then "Writing"). */+export function liveLabel(run: RunSnapshot, writing: boolean): string {if (run.state === 'stopping') return 'Stopping…';- return hasText ? 'Writing…' : 'Working…';+ return writing ? 'Writing' : 'Thinking';+}++/** "· 42 tok/s": how fast the answer is coming, a token counted as four+ * characters; null before a second has passed. */+export function writingRate(characters: number, elapsedMs: number): string | null {+ if (characters <= 0 || elapsedMs < 1000) return null;+ return `· ${Math.round(characters / 4 / (elapsedMs / 1000))} tok/s`;+}++function duration(ms: number | null): string {+ const seconds = Math.max(1, Math.round((ms ?? 0) / 1000));+ if (seconds < 60) return `${seconds}s`;+ const minutes = Math.floor(seconds / 60);+ const rest = seconds % 60;+ return rest ? `${minutes}m ${rest}s` : `${minutes}m`;+}++/** The steps disclosure's label: "Working…" while the steps come, then+ * "Worked for 12s · 3 steps" (skipped steps not counted). */+export function workLabel(steps: readonly RunStep[], live: boolean, durationMs: number | null): string {+ if (live) return 'Working…';+ const count = steps.filter((step) => step.state !== 'skipped').length;+ return `Worked for ${duration(durationMs)} · ${count} ${count === 1 ? 'step' : 'steps'}`;+}++/** What a step says under its name. */+export function stepDetail(step: RunStep): string | null {+ if (step.state === 'skipped') return 'Skipped';+ if (step.state === 'failed') return step.detail ? `Failed · ${step.detail}` : 'Failed';+ return step.detail ?? null;}diff --git a/client/src/features/chat/turns/useWritingRate.ts b/client/src/features/chat/turns/useWritingRate.tsnew file mode 100644index 00000000..b6301ef7--- /dev/null+++ b/client/src/features/chat/turns/useWritingRate.ts@@ -0,0 +1,19 @@+/**+ * How fast an answer is streaming ("· 42 tok/s"), measured from when its+ * text first showed in this tab; null when it is not streaming.+ */++import { useEffect, useState } from 'react';+import { writingRate } from './runCopy';++export function useWritingRate(text: string, streaming: boolean, now: Date): string | null {+ const [since, setSince] = useState<{ at: number; characters: number } | null>(null);++ useEffect(() => {+ if (!streaming) setSince(null);+ else if (since === null && text.length > 0) setSince({ at: Date.now(), characters: text.length });+ }, [streaming, text.length, since]);++ if (!streaming || !since) return null;+ return writingRate(text.length - since.characters, now.getTime() - since.at);+}diff --git a/client/src/features/home/__tests__/employeeChat.test.tsx b/client/src/features/home/__tests__/employeeChat.test.tsxindex 8d2d4479..3ffe6452 100644--- a/client/src/features/home/__tests__/employeeChat.test.tsx+++ b/client/src/features/home/__tests__/employeeChat.test.tsx@@ -153,7 +153,7 @@ describe('sending', () => {renderChat(employee());await write('Any bookings today?');fireEvent.keyDown(screen.getByRole('textbox', { name: 'Message Maya' }), { key: 'Enter' });- expect(await screen.findByText('Working…')).toBeInTheDocument();+ expect(await screen.findByText('Thinking')).toBeInTheDocument();// A routine report from another run does not end the wait (Talk bug 9).server.messages = [...server.messages, row(8, 'assistant', 'Daily summary: all quiet.', { run_id: 'r0' })];@@ -161,7 +161,7 @@ describe('sending', () => {await client.invalidateQueries({ queryKey: ['chatThread'] });});expect(await screen.findByText('Daily summary: all quiet.')).toBeInTheDocument();- expect(screen.getByText('Working…')).toBeInTheDocument();+ expect(screen.getByText('Thinking')).toBeInTheDocument();runEvents(frame(1, 'started'), frame(2, 'finished', { outcome: { type: 'success' } }));server.messages = [...server.messages, row(9, 'assistant', 'Two, at 10 and at 3.', { run_id: 'r1' })];@@ -169,7 +169,7 @@ describe('sending', () => {await client.invalidateQueries({ queryKey: ['chatThread'] });});expect(await screen.findByText('Two, at 10 and at 3.')).toBeInTheDocument();- expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.queryByText('Thinking')).not.toBeInTheDocument();});it('says on the status line when the employee will retry', async () => {@@ -197,7 +197,7 @@ describe('sending', () => {await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya isn’t running. Start them first.', { tone: 'error' }));expect(screen.getByRole('log', { name: 'Conversation with Maya' })).not.toHaveTextContent('Hello?');expect(screen.getByRole('textbox', { name: 'Message Maya' })).toHaveValue('Hello?');- expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.queryByText('Thinking')).not.toBeInTheDocument();});it('keeps a message the employee cannot take yet, saying they are still working', async () => {@@ -223,12 +223,14 @@ describe('sending', () => {expect(await screen.findByText('Your message is waiting. Maya will read it when you resume them.')).toBeInTheDocument();expect(screen.getByText('Waiting for you to resume Maya.')).toBeInTheDocument();fireEvent.change(screen.getByRole('textbox', { name: 'Message Maya' }), { target: { value: 'One more' } });- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();+ // The waiting message can be withdrawn meanwhile: Send is Stop.+ expect(screen.queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Stop reply' })).toBeEnabled();// Resumed: the waiting message goes to them now.rerender(employee({}, 'running'));runEvents(frame(1, 'started'));- expect(await screen.findByText('Working…')).toBeInTheDocument();+ expect(await screen.findByText('Thinking')).toBeInTheDocument();});it('gives the box to Start while the employee is not running', async () => {diff --git a/client/src/index.css b/client/src/index.cssindex d9fe7863..1fca27fd 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -656,6 +656,27 @@ html.oc-theme-fade *::after {* bubble; code blocks and tables inside keep their own surfaces unglowed. */.chat-msg-bot pre,.chat-msg-bot table { text-shadow: none; }+/* While an answer streams, a pulsing dot follows its last words (design+ * handoff chat, "Streaming"): at the end of the last block, or of a list's+ * last item. */+.chat-markdown[data-streaming] > :last-child::after,+.chat-markdown[data-streaming] > :is(ul, ol):last-child > li:last-child::after {+ content: '';+ display: inline-block;+ width: 10px;+ height: 10px;+ margin-left: 5px;+ vertical-align: -0.5px;+ border-radius: 50%;+ background: var(--action-tools-ink);+ box-shadow: 0 0 0 3px var(--action-tools-soft), 0 0 14px var(--action-tools-border);+ animation: opencompany-caret-pulse var(--dur-caret, 1000ms) ease-in-out infinite;+}+.chat-markdown[data-streaming] > :is(ul, ol):last-child::after { content: none; }+@media (prefers-reduced-motion: reduce) {+ .chat-markdown[data-streaming] > :last-child::after,+ .chat-markdown[data-streaming] > :is(ul, ol):last-child > li:last-child::after { animation: none; }+}/* ============================================================================* Syntax-highlighting palette — used by react-simple-code-editor + thediff --git a/client/src/lib/agui/reduceRun.ts b/client/src/lib/agui/reduceRun.tsindex 840d0f57..c401161c 100644--- a/client/src/lib/agui/reduceRun.ts+++ b/client/src/lib/agui/reduceRun.ts@@ -54,6 +54,8 @@ export interface RunSnapshot {createdAt: string | null;startedAt: string | null;finishedAt: string | null;+ /** How long it worked, once it has ended and the server said. */+ durationMs: number | null;steps: RunStep[];segments: RunSegment[];outcome: RunOutcome | null;@@ -82,6 +84,7 @@ export function emptyRun(runId: string, sessionId: string): RunSnapshot {createdAt: null,startedAt: null,finishedAt: null,+ durationMs: null,steps: [],segments: [],outcome: null,@@ -90,6 +93,15 @@ export function emptyRun(runId: string, sessionId: string): RunSnapshot {};}+/** How long a run worked: what the server said, else from its start and+ * end; null while either is unknown. */+export function workedMs(run: Pick<RunSnapshot, 'durationMs' | 'startedAt' | 'finishedAt'>): number | null {+ if (run.durationMs !== null) return run.durationMs;+ if (!run.startedAt || !run.finishedAt) return null;+ const span = Date.parse(run.finishedAt) - Date.parse(run.startedAt);+ return Number.isFinite(span) && span >= 0 ? span : null;+}+const RUN_KINDS: readonly RunKind[] = ['message', 'edit', 'regenerate', 'action', 'resume'];const RUN_STATES: readonly RunState[] = ['queued', 'pending', 'running', 'stopping', 'finished', 'error', 'stopped'];const STEP_STATES: readonly StepState[] = ['running', 'done', 'failed', 'skipped'];@@ -112,7 +124,9 @@ function oneOf<T extends string>(value: unknown, options: readonly T[], fallbackreturn typeof value === 'string' && (options as readonly string[]).includes(value) ? (value as T) : fallback;}-function wireSteps(raw: unknown): RunStep[] {+/** A run's steps as the server stores and sends them; unreadable ones are+ * left out. */+export function stepsFromWire(raw: unknown): RunStep[] {if (!Array.isArray(raw)) return [];return raw.flatMap((item) => {if (!isRecord(item)) return [];@@ -162,7 +176,8 @@ export function snapshotFromWire(raw: unknown): RunSnapshot | null {createdAt: textOrNull(raw.created_at),startedAt: textOrNull(raw.started_at),finishedAt: textOrNull(raw.finished_at),- steps: wireSteps(raw.steps),+ durationMs: typeof raw.duration_ms === 'number' && raw.duration_ms >= 0 ? raw.duration_ms : null,+ steps: stepsFromWire(raw.steps),segments: wireSegments(raw.segments),outcome,result: parseResult(raw.result),@@ -214,6 +229,7 @@ export function applyRunEvent(run: RunSnapshot, event: RunEvent): RunSnapshot {outcome: event.outcome,result: event.result,finishedAt: event.time ?? run.finishedAt,+ durationMs: event.durationMs,};case 'failed':return { ...next, state: 'error', error: event.error, finishedAt: event.time ?? run.finishedAt };diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex edb2353b..dc480d93 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -449,24 +449,30 @@ sending and drafts belong to the chat (wire and client rules inowner's OK follow the conversation (the host's `afterThread`).- **Working** follows the run the message started, not timers: from themoment the server admits it, the avatar spins its ring and skeleton lines- stand where the answer will be, with "Working…" under them, until that run- ends, whatever else lands meanwhile (a routine report does not end it). A- run that failed says so where the answer would be ("{Name} didn't pick up- this message.", "…took too long to answer.", or "{Name} couldn't answer."- with the error and its hint), also after a reload; a late answer replaces a- failure that only said none came. While the talk agent waits to retry after- a failed attempt, its retry message sits on the status line- (`useRetryNote`, from the agent's node status).+ stand where the answer will be, with "Thinking" under them, until that run+ ends, whatever else lands meanwhile (a routine report does not end it). The+ talk agent's answer streams in as it is written ("Writing · N tok/s", a+ caret after the text), and the apps it uses show above it as steps+ ("Working…", then "Worked for 12s · 3 steps"). A run that failed says so+ where the answer would be ("{Name} didn't pick up this message.", "…took too+ long to answer.", or "{Name} couldn't answer." with the error and its hint),+ also after a reload; a late answer replaces a failure that only said none+ came. While the talk agent waits to retry after a failed attempt, its retry+ message sits on the status line (`useRetryNote`, from the agent's node+ status).+- **Stop.** While the run works, Send is Stop, and Esc stops it too: the+ answer so far stays, marked "You stopped this reply." A message still+ waiting for Resume is withdrawn the same way.- **The box** follows the control state the way `send_chat_message` does(`talkMode` in `presentation.ts`):- *send* (running, starting, resuming): a message shows at once- ("Sending…") and goes to the employee; Send then waits until the run+ ("Sending…") and goes to the employee; Send is then Stop until the runends, since overlapping runs would each save over the other'sconversation (the server refuses a second message with`run_in_progress`).- *queue* (paused, pausing): one message waits for Resume ("Your message iswaiting…" above the box, "Waiting for you to resume {Name}." in the- thread), and Send waits until it has been answered.+ thread), and Send is Stop until it has been answered or withdrawn.- *start* (never started, ready, resetting, failed): no box; a line saysthey can't read messages, beside their main action (Start, Start again,or what they are missing), which the Workspace header offers too.@@ -545,8 +551,8 @@ otherwise (a chat trigger that feeds no agent counts here). While ageneration is live the summary reads the running snapshot, whose node ids arethe ones that report status; otherwise the saved graph. `talk.agent_node_id`is the agent that answers. It stays out of `watch_node_ids`, and `useLiveTask`-skips it: while it works, the conversation shows "Working…", and the-Workspace's task line stays on their other work.+skips it: while it works, the conversation shows it working (its steps and+streamed answer), and the Workspace's task line stays on their other work.### Turn on Talk and Apply