Multiplayer agent harness for work.
Improve chat streaming, scrolling, and recovery
Joshua France3d04f4251568
diff --git a/docs/qa/chat-streaming/README.md b/docs/qa/chat-streaming/README.mdnew file mode 100644index 000000000..294a3235d--- /dev/null+++ b/docs/qa/chat-streaming/README.md@@ -0,0 +1,23 @@+# Chat streaming and recovery QA++These screenshots use the real browser UI and isolated local core/Postgres with synthetic arithmetic prompts. No UI or API responses are mocked. The unchanged main frontend and updated frontend display the same saved conversation at the same window size. The local instance is not publicly reachable, so screenshots provide the review demo.++## Before++The latest prompt occupies several lines, and narration and tool summaries remain outside a single completed-work disclosure.++++## After++The latest prompt starts as a two-line preview with Show more. Completed work collapses into one timed disclosure while the answer remains visible.++++Expanding the disclosure shows narration and commands in their original order.++++## Interaction checks++Live browser checks covered streamed prose, code and tables; manual scroll-away and selection; opening and closing split panes during streaming; Stop followed by reload and another turn; queued-message editing with attachments; approval decisions and duration; a 25-second connection outage; and expanded full tool output after reload. Backend-specific cancellation and transport races have deterministic regression coverage. Screenshots demonstrate the resting layout; they do not establish timing behavior by themselves.diff --git a/docs/qa/chat-streaming/after.png b/docs/qa/chat-streaming/after.pngnew file mode 100644index 000000000..bc91cbd27Binary files /dev/null and b/docs/qa/chat-streaming/after.png differdiff --git a/docs/qa/chat-streaming/before.png b/docs/qa/chat-streaming/before.pngnew file mode 100644index 000000000..41b995ae2Binary files /dev/null and b/docs/qa/chat-streaming/before.png differdiff --git a/docs/qa/chat-streaming/work-expanded.png b/docs/qa/chat-streaming/work-expanded.pngnew file mode 100644index 000000000..f5d9c6787Binary files /dev/null and b/docs/qa/chat-streaming/work-expanded.png differdiff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.mdindex af26d4db0..ebf2a7ee9 100644--- a/plugins/web-ui/README.md+++ b/plugins/web-ui/README.md@@ -1,6 +1,6 @@# Web UI plugin-An end-user web surface with a custom ChatGPT/Claude-style chat shell, stitched to the+An end-user web surface with a custom chat shell, connected to theplatform core. It still uses Pi's `Agent` state machine and selected Pi web utilitiesfor markdown, attachment loading, and model metadata, but the visible conversation UI isowned by this plugin. Two processes:@@ -156,8 +156,8 @@ the CSS media queries, the composer, and the split canvas.alongside the light/dark choice.The UI drives Pi's `Agent` with a custom `streamFn` (`src/core-bridge.ts`) instead ofmounting Pi's stock `AgentInterface`.-- **Slash-command skill picker** — type `/` at the start of the composer for a Codex-style- autofill of the **skills** available to you (B6): icon · name · description · scope, with the+- **Slash-command skill picker** — type `/` at the start of the composer to browse the+ **skills** available to you (B6): icon · name · description · scope, with thetyped letters emboldened. Arrow/Tab/Enter to choose (it inserts `/<name> `), Esc/click-out todismiss. The list is the signed-in principal's _visible_ skills — the same set the agent getsmaterialized into a DM turn — fetched once per session via the server's `/api/skills` proxydiff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 24cf6bea3..2ba8ace1e 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -2403,6 +2403,15 @@ const apiRoutes: readonly WebRoute[] = [);},},+ {+ method: "PATCH",+ path: "/api/runs/:id/input",+ handle: async (c) => {+ const body = await readJson<{ text?: unknown; expectedText?: unknown }>(c.req, c.res, false);+ if (!body) return;+ return relayCore(c.res, "PATCH", `/v1/runs/${encodeURIComponent(c.params.id!)}/input`, JSON.stringify(body));+ },+ },{method: "POST",path: "/api/runs/:id/withdraw",diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex e0dbe4154..0d56eae4e 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -14,6 +14,7 @@ import type { AssistantMessage, TextContent } from "@earendil-works/pi-ai";import type { UserMessageWithAttachments } from "@earendil-works/pi-web-ui";import { markdown } from "./message-markdown";import { html, nothing, render, type TemplateResult } from "lit";+import { repeat } from "lit/directives/repeat.js";import {Activity,Ban,@@ -47,6 +48,7 @@ import {} from "lucide";import {continuableMessages,+ messagesWithStreaming,withBase,type SessionPin,activeRunForThread,@@ -82,6 +84,7 @@ import {type CoreSession,type DeliveredFile,type HistorySystemNote,+ type HistoryApprovalDecision,type PendingApproval,type SessionBackgroundOutput,type SessionBackgroundView,@@ -95,6 +98,9 @@ import {} from "./core-bridge";import {buildTimeline,+ messageWorkTimeline,+ streamingTextTail,+ currentTextPhase,postSpeechText,toolCategory,toolRowKind,@@ -822,10 +828,11 @@ export function createChatSurface(ctx.composer.setQueuedRuns(threadRef, active.queued);if (!active.runId || !active.run || runIsTerminal(active.run)) return drawActiveChat(agent);const recorded = (agent.state.messages.at(-1) as { role?: string } | undefined)?.role === "user";- if (!recorded && !next) agent.state.messages = [...agent.state.messages, resumeAnchor()];+ if (active.run.input) agent.state.messages = continuableMessages(agent.state.messages, active.run.input).messages;+ else if (!recorded && !next) agent.state.messages = [...agent.state.messages, resumeAnchor()];agent.streamFn = makeRunResumeStreamFn(active.runId, active.run, onWork, runSlot);try {- await (next && !recorded ? agent.prompt(next.text) : agent.continue());+ await (!active.run.input && next && !recorded ? agent.prompt(next.text) : agent.continue());} catch (err) {if (agent === chatState.agent) ctx.composer.state.error = errMessage(err, "Could not follow the queued message.");} finally {@@ -864,15 +871,12 @@ export function createChatSurface(onStarted?: () => void,): Promise<boolean> {if (agent !== chatState.agent || appState.currentView !== "chats" || agent.state.isStreaming) return false;- // Pull the transcript before attaching so the turn's triggering user message- // (written by core, not by this tab) is on screen while the run streams.await refreshTranscriptFromEntries(agent);if (agent !== chatState.agent || agent.state.isStreaming) return false;- const { messages: msgs, popped } = continuableMessages(agent.state.messages);+ if (!initialRun) initialRun = await api<RunPoll>(`/api/runs/${encodeURIComponent(runId)}`);+ if (agent !== chatState.agent || agent.state.isStreaming) return false;+ const { messages: msgs, popped } = continuableMessages(agent.state.messages, initialRun.input);agent.state.messages = msgs;- // Seed the resumed stream with the assistant text we just removed so the- // model's already-visible words (e.g. its opening ack) don't blink out- // while we re-attach to the live run.const seedText = popped.map((m) => messageText(m).trim()).filter(Boolean)@@ -1017,7 +1021,7 @@ export function createChatSurface(}</div>${backgroundActivityStrip()} ${approvals.length ? ctx.composer.composerApprovalPanel(approvals) : nothing}- <section class="chat-scroll readonly-scroll">+ <section class="chat-scroll readonly-scroll" tabindex="0" aria-label="Conversation">${pinnedStrip()}<div class="message-stack">${inheritedHeader()}@@ -1305,6 +1309,7 @@ export function createChatSurface(if (agent.state.isStreaming || chatState.resolvingApprovals.size > 0) {const work = chatState.liveWork ?? { status: "thinking", activity: [] };if (runSlot.stopGeneration === runSlot.generation) return "Stopping…";+ if (currentTextPhase(work)?.phase === "final_answer") return "Responding…";const summary = liveWorkSummary(work);if (!summary) return "Thinking…";return summary.detail ? `${summary.label}: ${summary.detail}` : summary.label;@@ -1363,7 +1368,7 @@ export function createChatSurface(}${glanceTier || ctx.pane || editingApp ? nothing : sessionTopbar()}${glanceTier ? paneGlance(agent, messages, glanceTier) : nothing}- <section class="chat-scroll">+ <section class="chat-scroll" tabindex="0" aria-label="Conversation">${pinnedStrip()}<div class="message-stack ${emptyChat ? "empty-stack" : ""}">${showWelcome ? welcomeGreeting(!messages.length) : nothing} ${inheritedHeader()}@@ -1400,6 +1405,7 @@ export function createChatSurface(`,chatState.host,);+ transcriptViewport.afterRender();const host = chatState.host;requestAnimationFrame(() => {if (chatState.host !== host || chatState.agent !== agent || !host.isConnected) return;@@ -1484,9 +1490,7 @@ export function createChatSurface(}function visibleMessages(agent: Agent): AgentMessage[] {- const out = [...agent.state.messages];- if (agent.state.streamingMessage) out.push(agent.state.streamingMessage);- return out;+ return messagesWithStreaming(agent.state.messages, agent.state.streamingMessage);}function settledChatMessage(@@ -1578,10 +1582,10 @@ export function createChatSurface(<div class="message-bubble user-bubble ${deleted ? "deleted-bubble" : ""}"><div class="pin-content">${isReadOnlySlackView() ? slackWireBubble(messageText(message)) : markdown(messageText(message))}- ${attachments.length ? html`<div class="message-files">${attachments.map(userAttachmentBadge)}</div>` : nothing}${edited || deleted ? html`<span class="revision-badge">(${deleted ? "deleted" : "edited"})</span>` : nothing}</div><button class="pin-toggle" type="button" hidden aria-expanded="false">Show more</button>+ ${attachments.length ? html`<div class="message-files">${attachments.map(userAttachmentBadge)}</div>` : nothing}</div>${sendFailure@@ -1597,6 +1601,21 @@ export function createChatSurface(</article>`;}+ if (role === "approval-decision") {+ const decision = message as unknown as HistoryApprovalDecision;+ let label = "Approval denied";+ if (decision.approved) {+ const labels: Record<string, string> = {+ once: "Approved once",+ session: "Approved for this session",+ always: "Approved always",+ };+ label = labels[decision.scope ?? "once"] ?? "Approved";+ }+ return html`<article class="message-row system-note-row" data-index=${index}>+ <div class="system-note">${label}: <code>${decision.command}</code></div>+ </article>`;+ }if (role === "system-note") {const note = message as unknown as HistorySystemNote;const who = note.speaker ?? "The user";@@ -1615,10 +1634,12 @@ export function createChatSurface(if (role === "assistant") {const msg = message as AssistantMessage;if ((msg as AssistantWork).retryableSend) return nothing;- const work = isStreaming ? null : (msg as AssistantWork).work;+ const work = (msg as AssistantWork).work;const text = assistantDisplayText(messageText(msg)).trim();const hasText = Boolean(text);- const showWork = shouldShowApprovalWork(msg, work, text) && shouldShowWork(work, hasText);+ const showWork =+ shouldShowApprovalWork(msg, work, text) &&+ shouldShowWork(work, isStreaming || msg.stopReason === "error" || msg.stopReason === "aborted" ? "" : text);const deliveredFiles = (msg as AssistantWork).deliveredFiles;const hasVisibleContent =showWork ||@@ -1629,8 +1650,8 @@ export function createChatSurface(return html`<article class="message-row assistant-row ${isStreaming ? "streaming" : ""}" data-index=${index}><div class="assistant-body">- ${showWork ? workBlock(work, isStreaming) : nothing} ${assistantContent(msg, isStreaming, showWork)}- ${assistantFileList(deliveredFiles)}+ ${showWork ? workBlock(work, isStreaming, msg.stopReason === "aborted" || msg.stopReason === "error" ? "" : text, (msg as AssistantWork).streamingBaseline ?? "") : nothing}+ ${assistantContent(msg, isStreaming, showWork)} ${assistantFileList(deliveredFiles)}${msg.stopReason === "error" && msg.errorMessage ? html`<div class="composer-error inline">${msg.errorMessage}</div>` : nothing}${msg.stopReason === "aborted" ? html`<div class="stopped-note">${icon(Ban, 13)}<span>Stopped</span></div>` : nothing}${isStreaming ? nothing : messageMeta(msg, index)}@@ -1808,7 +1829,13 @@ export function createChatSurface(const parts: TemplateResult[] = [];for (const [chunkIndex, chunk] of message.content.entries()) {if (chunk.type === "text") {- for (const [partIndex, part] of setupContent(assistantDisplayText(chunk.text)).entries()) {+ const work = (message as AssistantWork).work;+ const phase = work ? currentTextPhase(work) : null;+ const streamingFinal = isStreaming && phase?.phase === "final_answer";+ const text = streamingFinal ? chunk.text.slice(phase.streamOffset) : chunk.text;+ for (const [partIndex, part] of setupContent(+ assistantDisplayText(isStreaming && hasWork && !streamingFinal ? "" : text),+ ).entries()) {if (part.type !== "text") {if (!(message as AssistantWork).persisted) continue;parts.push(@@ -1829,7 +1856,9 @@ export function createChatSurface(const body = links.length ? stripConnectorLinks(shown, links) : shown;if (body.trim())parts.push(- html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}" dir="auto">${markdown(body)}</div>`,+ html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}" dir="auto">+ ${markdown(body, isStreaming, streamingFinal ? ((message as AssistantWork).streamingBaseline ?? "").slice(phase.streamOffset) : ((message as AssistantWork).streamingBaseline ?? ""))}+ </div>`,);for (const link of links) parts.push(connectorWidget(link));}@@ -1901,11 +1930,8 @@ export function createChatSurface(syncWorkTicker();}- function shouldShowWork(work: WorkBlock | null | undefined, hasText: boolean): work is WorkBlock {- if (!work) return false;- if (work.activity.length > 0) return true;- if (work.pendingApprovals?.length) return true;- return work.status === "thinking" && !hasText;+ function shouldShowWork(work: WorkBlock | null | undefined, finalText: string): work is WorkBlock {+ return Boolean(work && (messageWorkTimeline(work, finalText).length || work.pendingApprovals?.length));}function shouldShowApprovalWork(@@ -2201,6 +2227,7 @@ export function createChatSurface(if (!agent.state.isStreaming && chatState.resolvingApprovals.size === 0) return nothing;const work = chatState.liveWork ?? { status: "thinking", activity: [] };if (work.status !== "thinking" && work.status !== "working") return nothing;+ if (currentTextPhase(work)?.phase === "final_answer" || shouldShowWork(work, "")) return nothing;const stopping = runSlot.stopGeneration === runSlot.generation;const summary = stopping ? null : liveWorkSummary(work);const expandable = Boolean(summary?.detail);@@ -2291,72 +2318,48 @@ export function createChatSurface(function workLabel(work: WorkBlock): string {if (work.stale && (work.status === "thinking" || work.status === "working")) return "Interrupted, resuming…";+ if (currentTextPhase(work)?.phase === "final_answer") return workedLabel("Worked", workSeconds(work));if (work.status === "thinking") return "Thinking";const secs = workSeconds(work);- return work.status === "working" ? `Working for ${secs}s` : workedLabel("Worked", secs);- }-- function workBlock(work: WorkBlock, isStreaming: boolean): TemplateResult {- if (work.status === "thinking" && !work.activity.length) {- return html`<div class="work work-thinking">- <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>- </div>`;- }- const timeline = buildTimeline(work);- const rows = timeline.length- ? html`<div class="work-rows">${timeline.map((it) => renderTimelineItem(it, work))}</div>`- : nothing;- const body = html`<div class="work-divider"></div>- ${rows}`;- if (isStreaming || work.status === "working" || work.status === "thinking") {- return html`<div class="work work-working">- <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>- ${body}- </div>`;- }- const openFolds = !!work.pendingApprovals?.length;- const parts: TemplateResult[] = [];- let seg: TimelineItem[] = [];- const flushSeg = (): void => {- if (!seg.length) return;- const items = seg;- seg = [];- parts.push(- html`<details class="work-fold" ?open=${openFolds}>- <summary class="work-head">${segmentSummaryLabel(items, work)}${icon(ChevronRight, 14)}</summary>- <div class="work-divider"></div>- <div class="work-rows">${items.map((it) => renderTimelineItem(it, work))}</div>- </details>`,- );- };- for (const it of timeline) {- const speech = it.kind === "tool" ? postSpeechText(it.row) : null;- const demoted = it.kind === "text" && (it.activity.payload as { demoted?: boolean } | null)?.demoted === true;- // Closing self-logs after a successful surface post are bookkeeping, not- // another piece of visible work. Keeping them in the transcript is useful- // for audit/replay, but rendering them creates an empty "Worked" fold.- if (demoted) continue;- if (it.kind === "text") {- flushSeg();- const text = ((it.activity.payload as { text?: string } | null)?.text ?? "").trim();- if (text) parts.push(html`<div class="work-said">${markdown(text)}</div>`);- } else if (speech) {- flushSeg();- parts.push(html`<div class="work-said">${markdown(speech)}</div>`);- } else {- seg.push(it);- }- }- flushSeg();- return parts.length ? html`<div class="work work-${work.status}">${parts}</div>` : html``;- }-- function segmentSummaryLabel(items: TimelineItem[], work: WorkBlock): string {- const tools = items.filter((it) => it.kind === "tool").length;- if (tools > 0) return `${tools} tool call${tools === 1 ? "" : "s"}`;- const secs = workSeconds(work);- if (work.status === "failed") return secs > 0 ? `Failed after ${secs}s` : "Failed";- return workedLabel("Worked", secs);+ return workedLabel(work.status === "working" ? "Working" : "Worked", secs);+ }++ function workBlock(work: WorkBlock, isStreaming: boolean, text: string, baseline: string): TemplateResult {+ const active =+ isStreaming &&+ currentTextPhase(work)?.phase !== "final_answer" &&+ (work.status === "working" || work.status === "thinking");+ const replies: string[] = [];+ const timeline = messageWorkTimeline(work, active ? "" : text).filter((item) => {+ const speech = item.kind === "tool" ? postSpeechText(item.row) : null;+ if (speech === null) return true;+ replies.push(speech);+ return false;+ });+ const tail = active ? streamingTextTail(text, work.activity) : "";+ const stopping = active && runSlot.stopGeneration === runSlot.generation;+ const label = stopping ? "Stopping…" : workLabel(work);+ const fold =+ timeline.length || tail.trim() || work.pendingApprovals?.length+ ? html`<details class="work work-fold work-${work.status}" ?open=${active || !!work.pendingApprovals?.length}>+ <summary class="work-head">${sheenLabel(label, active)}${icon(ChevronRight, 14)}</summary>+ <div class="work-divider"></div>+ <div class="work-rows">+ ${repeat(+ timeline,+ (item) => {+ if (item.kind === "tool")+ return `tool:${item.row.call?.seq ?? item.row.result?.seq ?? item.row.approval?.seq}`;+ if (item.kind === "approval") return `approval:${item.approval.requestId}`;+ return `${item.kind}:${item.activity.seq}`;+ },+ (item) => renderTimelineItem(item, work),+ )}+ ${tail.trim() ? html`<div class="work-said streaming-text live-stream">${markdown(tail, true, streamingTextTail(baseline, work.activity))}</div>` : nothing}+ </div>+ </details>`+ : nothing;+ return html`${fold}${replies.map((reply) => html`<div class="streaming-text" dir="auto">${markdown(reply)}</div>`)}`;}function approvalSummaryView(a: PendingApproval, expanded = false): TemplateResult {@@ -2411,8 +2414,6 @@ export function createChatSurface(if (item.kind === "thinking") return thinkingRow(item.activity);if (item.kind === "text") return messageRow(item.activity);if (item.kind === "approval") return approvalMarker(item.approval);- const speech = postSpeechText(item.row);- if (speech) return messageRow({ ...item.row.call!, payload: { text: speech } });return toolRow(item.row, work, status, stale);}@@ -2596,7 +2597,7 @@ export function createChatSurface(}function toolPayloadText(payload: ToolPayload, omitted: string[] = []): string {- const hidden = new Set(["tool", "callId", ...omitted]);+ const hidden = new Set(["tool", "callId", "workStartedAt", "workFinishedAt", ...omitted]);const entries = Object.entries(payload as Record<string, unknown>).filter(([key, value]) => !hidden.has(key) && value !== undefined,);@@ -2623,7 +2624,10 @@ export function createChatSurface(const input = toolPayloadText(call);const hasExecOutput =toolCategory({ ...result, ...call, tool }) === "execute" && toolExecutionOutput(result) !== null;- const output = toolPayloadText(result, hasExecOutput ? ["stdout", "stderr", "code", "timedOut", "result"] : []);+ const output = toolPayloadText(result, [+ "isError",+ ...(hasExecOutput ? ["stdout", "stderr", "code", "timedOut", "result"] : []),+ ]);return html`<div class="tool-disclosure">${toolPayloadCard("Input", input)} ${hasExecOutput ? execOutputCard(result, work, activity) : nothing}${toolPayloadCard("Result", output)}@@ -2667,7 +2671,7 @@ export function createChatSurface(</div>`;}let label = knownMeta ? meta.attempted : `Tried ${name}`;- if (kind === "approval") label = "Approval needed";+ if (kind === "approval") label = row.pending ? "Approval needed" : "Approval requested";else if (kind === "running") {const active = knownMeta ? meta.active : name;label = stale ? `${active} — interrupted` : active;@@ -2678,7 +2682,10 @@ export function createChatSurface(const base = kind === "approval" ? "" : toolDetail(tool, call, result);const attempts = row.attempts && row.attempts > 1 ? `${row.attempts} attempts` : "";const detail = [base, why, attempts].filter(Boolean).join(" · ");- const visible = detail || label;+ let statusLabel = "";+ if (kind === "failed") statusLabel = "Failed";+ else if (kind === "approval" && detail) statusLabel = label;+ const visible = [statusLabel, detail || label].filter(Boolean).join(" · ");const classes = ["tool-row", `tool-${kind}`].join(" ");const head = html`<span class="tool-icon">${icon(meta.icon, 13)}</span><span class="tool-label" title=${detail ? `${label}: ${detail}` : label}>${visible}</span>`;diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex f145d2a02..1235073aa 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -26,6 +26,7 @@ import {import {api,ApiError,+ editQueuedRun,approvalBlocksComposer,latestTranscriptSeq,MAX_ATTACHMENT_BYTES,@@ -291,6 +292,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {const pastedTextIds = new Set<string>();const queuedRuns = new Map<string, QueuedRun[]>();+ let queuedEdit: { runId: string; threadRef: string; original: string; text: string; saving: boolean } | null = null;function queuedRunsFor(threadRef: string | null): QueuedRun[] {return (threadRef ? queuedRuns.get(threadRef) : undefined) ?? [];@@ -762,7 +764,9 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function queuedStrip(agent: Agent): TemplateResult | typeof nothing {- const queued = queuedRunsFor(ctx.chat.state.threadRef);+ const queued = [...queuedRunsFor(ctx.chat.state.threadRef)];+ if (queuedEdit?.threadRef === ctx.chat.state.threadRef && !queued.some((q) => q.runId === queuedEdit?.runId))+ queued.push({ runId: queuedEdit.runId, text: queuedEdit.original });if (!queued.length) return nothing;const steerable =agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption()?.harnessId ?? "");@@ -773,33 +777,103 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {};return html`<div class="queued-strip" role="list" aria-label="Queued messages">- ${queued.map(- (q) => html`- <div class="queued-chip" role="listitem">- <span class="queued-tag">Queued</span>- <span class="queued-text" dir="auto" ${tip(q.text || "Files, no text")}- >${q.text || (q.hasAttachments ? "(files)" : "")}</span- >- <button- type="button"- class="queued-steer"- ?disabled=${!steerable || q.hasAttachments}- ${tip(steerTip(q))}- @click=${() => void steerQueued(agent, q)}- >- ${icon(CornerDownRight, 13)}<span>Steer</span>- </button>- <button- type="button"- class="chip-x"- aria-label="Remove queued message"- ${tip("Remove")}- @click=${() => void removeQueued(agent, q)}- >- ${icon(X, 13)}- </button>- </div>- `,+ ${queued.map((q) =>+ queuedEdit?.runId === q.runId && queuedEdit.threadRef === ctx.chat.state.threadRef+ ? html` <div class="queued-chip queued-editing" role="listitem">+ <textarea+ class="queued-edit-input"+ aria-label="Edit queued message"+ rows="3"+ .value=${live(queuedEdit.text)}+ ?disabled=${queuedEdit.saving}+ @input=${(event: Event) => {+ if (queuedEdit) queuedEdit.text = (event.target as HTMLTextAreaElement).value;+ }}+ @keydown=${(event: KeyboardEvent) => {+ if (event.isComposing || queuedEdit?.saving) return;+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ cancelQueuedEdit(agent);+ } else if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ event.stopPropagation();+ void saveQueuedEdit(agent);+ }+ }}+ ></textarea>+ <button+ type="button"+ class="queued-steer"+ aria-keyshortcuts="Control+Enter Meta+Enter"+ ?disabled=${queuedEdit.saving}+ @click=${() => void saveQueuedEdit(agent)}+ >+ Save+ </button>+ <button+ type="button"+ class="queued-steer"+ ?disabled=${queuedEdit.saving}+ @click=${() => cancelQueuedEdit(agent)}+ >+ Cancel+ </button>+ </div>`+ : html`+ <div class="queued-chip" role="listitem">+ <span class="queued-tag">Queued</span>+ <span class="queued-text" dir="auto" ${tip(q.text || "Files, no text")}+ >${q.text || (q.hasAttachments ? "(files)" : "")}</span+ >+ <button+ type="button"+ class="queued-steer"+ ?disabled=${!steerable || q.hasAttachments}+ ${tip(steerTip(q))}+ @click=${() => void steerQueued(agent, q)}+ >+ ${icon(CornerDownRight, 13)}<span>Steer</span>+ </button>+ <button+ type="button"+ class="queued-steer"+ aria-label="Edit queued message"+ @click=${() => {+ const edit = (queuedEdit = {+ runId: q.runId,+ threadRef: ctx.chat.state.threadRef!,+ original: q.text,+ text: q.text,+ saving: false,+ });+ ctx.chat.drawActiveChat(agent);+ requestAnimationFrame(() => {+ if (+ queuedEdit !== edit ||+ ctx.chat.state.threadRef !== edit.threadRef ||+ ctx.chat.state.agent !== agent+ )+ return;+ const input = ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".queued-edit-input");+ input?.focus();+ input?.setSelectionRange(input.value.length, input.value.length);+ });+ }}+ >+ Edit+ </button>+ <button+ type="button"+ class="chip-x"+ aria-label="Remove queued message"+ ${tip("Remove")}+ @click=${() => void removeQueued(agent, q)}+ >+ ${icon(X, 13)}+ </button>+ </div>+ `,)}</div>`;@@ -1886,6 +1960,42 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}}+ function cancelQueuedEdit(agent: Agent): void {+ if (queuedEdit?.saving) return;+ queuedEdit = null;+ composerState.error = "";+ ctx.chat.drawActiveChat(agent);+ focusComposerEnd();+ }++ async function saveQueuedEdit(agent: Agent): Promise<void> {+ const edit = queuedEdit;+ if (!edit || edit.saving) return;+ edit.saving = true;+ composerState.error = "";+ ctx.chat.drawActiveChat(agent);+ try {+ await editQueuedRun(edit.runId, edit.text, edit.original);+ setQueuedRuns(+ edit.threadRef,+ queuedRunsFor(edit.threadRef).map((q) => (q.runId === edit.runId ? { ...q, text: edit.text } : q)),+ );+ if (queuedEdit === edit) {+ queuedEdit = null;+ if (ctx.chat.state.threadRef === edit.threadRef && ctx.chat.state.agent === agent) focusComposerEnd();+ }+ } catch (error) {+ if (ctx.chat.state.threadRef === edit.threadRef)+ composerState.error =+ error instanceof ApiError && error.status === 409+ ? "That message changed or already started. Your edit was not saved."+ : errMessage(error, "Could not edit the queued message.");+ } finally {+ edit.saving = false;+ if (ctx.chat.state.threadRef === edit.threadRef) ctx.chat.drawActiveChat(agent);+ }+ }+async function removeQueued(agent: Agent, queued: QueuedRun): Promise<void> {const threadRef = ctx.chat.state.threadRef;if (!threadRef) return;@@ -1995,6 +2105,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {clearComposerDom(agent);try {if (ctx.chat.state.normalStreamFn) agent.streamFn = ctx.chat.state.normalStreamFn;+ ctx.chat.scrollToBottom();await agent.prompt(userSendMessage(text, attachments.length ? attachments : undefined));restoreBlockedSend(agent, sentFromThread, text, attachments);restoreFailedAttachments(agent, text, attachments);diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 308948b2f..25d6e75c9 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -1,3 +1,4 @@+import { streamedAnswer } from "./timeline.ts";import { EventType } from "@tanstack/ai/client";import { fetchServerSentEvents, StreamProcessor } from "@tanstack/ai-client";import { postCallText, postResultOk } from "./surface-post.ts";@@ -373,6 +374,7 @@ export interface SessionEntry {| "user"| "assistant"| "thinking"+ | "text_start"| "text"| "tool_call"| "tool_result"@@ -391,7 +393,7 @@ export interface SessionEntry {export interface ToolActivity {seq: number;parentSeq: number | null;- type: "tool_call" | "tool_result" | "approval_request" | "approval_resolved" | "thinking" | "text";+ type: "tool_call" | "tool_result" | "approval_request" | "approval_resolved" | "thinking" | "text" | "text_start";payload: unknown;createdAt: number;truncated?: boolean;@@ -406,6 +408,15 @@ export interface WorkBlock {pendingApprovals?: PendingApproval[];}+export function workPausedForApproval(work: WorkBlock): boolean {+ const last = work.activity.at(-1);+ return (+ last?.type === "approval_request" ||+ ((last?.type === "tool_result" || last?.type === "tool_call") &&+ (last.payload as { blocked?: unknown } | null)?.blocked === "needs_approval")+ );+}+export interface PendingApproval {requestId: string;command: string;@@ -428,6 +439,7 @@ export interface ApprovalDecision {}export type AssistantWork = AssistantMessage & {persisted?: boolean;+ streamingBaseline?: string;work?: WorkBlock;deliveredFiles?: DeliveredFile[];retryableSend?: boolean;@@ -438,6 +450,13 @@ export type AssistantWork = AssistantMessage & {export interface RunPoll {status: "pending" | "running" | "done" | "failed";+ input?: {+ runId: string;+ seq: number | null;+ text: string;+ createdAt: number;+ attachments?: Array<{ name: string; mimetype: string; sizeBytes: number }>;+ };result: {status: string;reply?: string;@@ -482,10 +501,49 @@ export function resumeAnchor(): AgentMessage {return { role: "user", content: "", resumeAnchor: true } as unknown as AgentMessage;}-export function continuableMessages(messages: AgentMessage[]): { messages: AgentMessage[]; popped: AgentMessage[] } {+export function continuableMessages(+ messages: AgentMessage[],+ input?: RunPoll["input"],+): { messages: AgentMessage[]; popped: AgentMessage[] } {const kept = messages.slice();const popped: AgentMessage[] = [];- while (kept.length && (kept[kept.length - 1] as { role?: string }).role === "assistant") popped.unshift(kept.pop()!);+ if (+ input &&+ !kept.some((message) => {+ const user = message as unknown as HistoryUserMessage;+ return (+ (user.role === "user" || user.role === "user-with-attachments") &&+ (user.runId === input.runId || (input.seq !== null && user.entrySeq === input.seq))+ );+ })+ ) {+ const user: HistoryUserMessage = {+ role: "user",+ runId: input.runId,+ content: input.text,+ timestamp: input.createdAt,+ ...(input.attachments?.length+ ? {+ attachments: input.attachments.map((attachment, index) => ({+ id: `${input.runId}:${index}`,+ type: attachment.mimetype.startsWith("image/") ? ("image" as const) : ("document" as const),+ fileName: attachment.name,+ mimeType: attachment.mimetype,+ size: attachment.sizeBytes,+ })),+ }+ : {}),+ };+ return { messages: [...kept, user as AgentMessage], popped };+ }+ while (kept.length && (kept[kept.length - 1] as { role?: string }).role === "assistant") {+ const work = (kept.at(-1) as AssistantWork).work;+ if (!input && work && workPausedForApproval(work)) {+ kept.push(resumeAnchor());+ break;+ }+ popped.unshift(kept.pop()!);+ }return { messages: kept.length ? kept : [resumeAnchor()], popped };}@@ -882,6 +940,10 @@ export async function queueTurn(return { runId: submit.runId, text, ...(attachments.length ? { hasAttachments: true } : {}) };}+export async function editQueuedRun(runId: string, text: string, expectedText: string): Promise<void> {+ await api(runPath(runId, "/input"), { method: "PATCH", body: JSON.stringify({ text, expectedText }) });+}+export async function withdrawRun(runId: string): Promise<boolean> {const r = await api<{ withdrawn?: boolean }>(runPath(runId, "/withdraw"), { method: "POST" });return r.withdrawn === true;@@ -1111,6 +1173,8 @@ async function drive(});if (submit.runId) {+ const message = agent.state.messages.find((message) => idempotencyKey && sendKeyOf(message) === idempotencyKey);+ if (message) (message as unknown as HistoryUserMessage).runId = submit.runId;await followRun(stream, partial, submit.runId, signal, notify, undefined, slot, gen);return;}@@ -1157,6 +1221,9 @@ async function resumeDrive(): Promise<void> {const gen = beginSubmit(slot);const partial = baseAssistant(model);+ const snapshotText = initialRun?.partial ?? "";+ (partial as AssistantWork).streamingBaseline =+ snapshotText.length > (seedText?.length ?? 0) ? snapshotText : (seedText ?? "");const work: WorkBlock = { status: "thinking", activity: [] };(partial as AssistantWork).work = work;const notify = (): void => onWork?.(work);@@ -1311,8 +1378,7 @@ function applyRun(notify?.();}if (res?.stopped) {- if (res.reply && res.reply.length > st.acc.length) pushDelta(stream, partial, st, res.reply);- abortStream(stream, partial);+ abortStream(stream, partial, res.reply);return "terminal";}if (res?.reply) {@@ -1504,9 +1570,11 @@ function fail(): void {const block = partial.content[0];const soFar = block?.type === "text" ? block.text : "";+ const work = (partial as AssistantWork).work;+ const text = work ? streamedAnswer(soFar, work) : soFar;const error: AssistantMessage = {...partial,- content: [{ type: "text", text: soFar }],+ content: [{ type: "text", text }],stopReason: "error",errorMessage,...(retryableSend ? { retryableSend: true } : {}),@@ -1515,7 +1583,7 @@ function fail(stream.end(error);}-function abortStream(stream: AssistantMessageEventStream, partial: AssistantMessage): void {+function abortStream(stream: AssistantMessageEventStream, partial: AssistantMessage, reply?: string): void {const work = (partial as AssistantWork).work;if (work && work.status !== "complete") {work.status = "failed";@@ -1525,7 +1593,7 @@ function abortStream(stream: AssistantMessageEventStream, partial: AssistantMessconst soFar = block?.type === "text" ? block.text : "";const error: AssistantMessage = {...partial,- content: [{ type: "text", text: soFar }],+ content: [{ type: "text", text: reply ?? (work ? streamedAnswer(soFar, work) : soFar) }],stopReason: "aborted",errorMessage: "aborted",};@@ -1542,7 +1610,7 @@ function pushDelta(stream: AssistantMessageEventStream, partial: AssistantMessag}function finish(stream: AssistantMessageEventStream, partial: AssistantMessage, st: Acc, reply: string): void {- const finalText = reply.length >= st.acc.length ? reply : st.acc;+ const finalText = reply;if (finalText.length > st.acc.length) pushDelta(stream, partial, st, finalText);const block = partial.content[0];if (block?.type === "text") block.text = finalText;@@ -1582,6 +1650,7 @@ const ACTIVITY_TYPES = new Set<string>(["approval_request","approval_resolved","thinking",+ "text_start","text",]);@@ -1595,7 +1664,9 @@ interface HistoryAttachment {}interface HistoryUserMessage {- role: "user";+ role: "user" | "user-with-attachments";+ runId?: string;+ entrySeq?: number;content: string;timestamp?: number;attachments?: HistoryAttachment[];@@ -1641,6 +1712,76 @@ export interface HistorySystemNote {timestamp?: number;}+export interface HistoryApprovalDecision {+ role: "approval-decision";+ requestId?: string;+ approved: boolean;+ command: string;+ scope?: string;+ timestamp: number;+}++function approvalDecisionMessage(+ entry: Pick<SessionEntry, "type" | "payload" | "createdAt">,+): HistoryApprovalDecision | null {+ if (entry.type !== "approval_resolved") return null;+ const decision = entry.payload as {+ requestId?: unknown;+ approved?: unknown;+ command?: unknown;+ scope?: unknown;+ } | null;+ if (typeof decision?.approved !== "boolean" || typeof decision.command !== "string") return null;+ return {+ role: "approval-decision",+ approved: decision.approved,+ command: decision.command,+ ...(typeof decision.requestId === "string" ? { requestId: decision.requestId } : {}),+ ...(typeof decision.scope === "string" ? { scope: decision.scope } : {}),+ timestamp: entry.createdAt,+ };+}++export function messagesWithStreaming(messages: AgentMessage[], streaming?: AgentMessage | null): AgentMessage[] {+ const source = streaming ? [...messages, streaming] : messages;+ const out: AgentMessage[] = [];+ const recorded = source.filter(+ (message) => (message as { role: string }).role === "approval-decision",+ ) as unknown as HistoryApprovalDecision[];+ for (const message of source) {+ for (const activity of (message as AssistantWork).work?.activity ?? []) {+ const decision = approvalDecisionMessage(activity);+ if (!decision) continue;+ const exists = recorded.some((existing) =>+ decision.requestId+ ? existing.requestId === decision.requestId && existing.timestamp === decision.timestamp+ : existing.timestamp === decision.timestamp &&+ existing.command === decision.command &&+ existing.approved === decision.approved,+ );+ if (!exists) {+ out.push(decision as unknown as AgentMessage);+ recorded.push(decision);+ }+ }+ out.push(message);+ }+ return out.map((message) => {+ const assistant = message as AssistantWork;+ const work = assistant.work;+ if (!work?.pendingApprovals?.length) return message;+ const requestedAt = work.activity.length+ ? Math.max(...work.activity.map((activity) => activity.createdAt))+ : assistant.timestamp;+ const pendingApprovals = work.pendingApprovals.filter(+ (approval) =>+ !recorded.some((decision) => decision.requestId === approval.requestId && decision.timestamp >= requestedAt),+ );+ if (pendingApprovals.length === work.pendingApprovals.length) return message;+ return { ...assistant, work: { ...work, pendingApprovals } };+ });+}+function messageRevisionPayload(payload: unknown): HistorySystemNote | null {const p = payload as { kind?: unknown; action?: unknown; ts?: unknown; text?: unknown; name?: unknown } | null;if (p?.kind !== "message_revision") return null;@@ -1709,8 +1850,9 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):at?: number,closed = false,timing?: { startedAt?: number; finishedAt?: number },+ stopped = false,): void => {- if (!text && !pending.length && !deliveryFiles.length) return;+ if (!text && !pending.length && !deliveryFiles.length && !stopped) return;const deliveredSilence = (a: ToolActivity): boolean => {if (a.type !== "tool_result") return false;const p = a.payload as { tool?: string; silent?: boolean; ok?: boolean } | null;@@ -1720,8 +1862,12 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):if (lastText >= 0) {const segment = ((pending[lastText]!.payload as { text?: string } | null)?.text ?? "").trim();if (text) {- if (segment === text.trim()) pending.splice(lastText, 1);- } else if (closed && segment && !pending.some(deliveredSilence)) {+ if (+ segment === text.trim() &&+ (pending[lastText]!.payload as { phase?: string } | null)?.phase !== "commentary"+ )+ pending.splice(lastText, 1);+ } else if (closed && !stopped && segment && !pending.some(deliveredSilence)) {text = segment;pending.splice(lastText, 1);}@@ -1734,17 +1880,20 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):provider: model?.provider ?? "unknown",model: model?.id ?? "unknown",usage: zeroUsage(),- stopReason: "stop",+ stopReason: stopped ? "aborted" : "stop",timestamp: at ?? pending[pending.length - 1]?.createdAt,};- if (pending.length)+ if (pending.length) {+ const boundary = pending.findLast(+ (entry) => typeof (entry.payload as { workStartedAt?: unknown } | null)?.workStartedAt === "number",+ )?.payload as { workStartedAt: number } | undefined;msg.work = {status: "complete",-- startedAt: timing?.startedAt ?? pending[0]?.createdAt,+ startedAt: timing?.startedAt ?? boundary?.workStartedAt ?? pending[0]?.createdAt,finishedAt: timing?.finishedAt ?? at ?? pending[pending.length - 1]?.createdAt,activity: pending,};+ }if (deliveryFiles.length) msg.deliveredFiles = deliveryFiles;out.push(msg as AgentMessage);pending = [];@@ -1763,8 +1912,19 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):ts?: string;workStartedAt?: number;workFinishedAt?: number;+ stopped?: boolean;+ runId?: string;} | null;const text = payload?.text ?? "";+ if (e.type === "approval_resolved") {+ const decision = approvalDecisionMessage(e);+ if (decision) {+ spillHeldPosts();+ flushWork("", e.createdAt);+ out.push(decision as unknown as AgentMessage);+ }+ continue;+ }if (ACTIVITY_TYPES.has(e.type)) {const activity: ToolActivity = {seq: e.seq ?? out.length,@@ -1807,15 +1967,19 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):}if (e.type === "user") {if (payload?.hidden) continue;- posted = false;- spillHeldPosts();- flushWork("", e.createdAt, Boolean(payload?.steered));+ if (!payload?.steered) {+ posted = false;+ spillHeldPosts();+ flushWork("", e.createdAt);+ }const atts = payload?.attachments ?? [];const userText = userEntryText(e.payload) ?? text;if (text || atts.length) {const mail = subagentMailOf(e.payload);const msg: HistoryUserMessage = {role: "user",+ ...(typeof payload?.runId === "string" ? { runId: payload.runId } : {}),+ ...(e.seq !== undefined ? { entrySeq: e.seq } : {}),content: userText,timestamp: e.createdAt,...(mail ? { subagentMail: mail } : {}),@@ -1841,7 +2005,7 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):...(typeof payload?.workStartedAt === "number" ? { startedAt: payload.workStartedAt } : {}),...(typeof payload?.workFinishedAt === "number" ? { finishedAt: payload.workFinishedAt } : {}),};- if (text || pending.length || heldPosts.size) {+ if (text || pending.length || heldPosts.size || payload?.stopped) {spillHeldPosts();if (posted && text) {pending.push({@@ -1851,9 +2015,9 @@ export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>):payload: { text, demoted: true },createdAt: e.createdAt,});- flushWork("", e.createdAt, false, timing);+ flushWork("", e.createdAt, false, timing, payload?.stopped === true);} else {- flushWork(text, e.createdAt, !posted, timing);+ flushWork(text, e.createdAt, !posted, timing, payload?.stopped === true);}}posted = false;diff --git a/plugins/web-ui/src/html-escape.ts b/plugins/web-ui/src/html-escape.tsnew file mode 100644index 000000000..813333e7c--- /dev/null+++ b/plugins/web-ui/src/html-escape.ts@@ -0,0 +1,3 @@+export function escapeHtml(text: string): string {+ return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);+}diff --git a/plugins/web-ui/src/lazy-hljs.ts b/plugins/web-ui/src/lazy-hljs.tsindex 05ff11c67..a77e17033 100644--- a/plugins/web-ui/src/lazy-hljs.ts+++ b/plugins/web-ui/src/lazy-hljs.ts@@ -1,3 +1,5 @@+import { escapeHtml } from "./html-escape.ts";+type HighlightResult = { value: string };type Hljs = {registerLanguage: (name: string, lang: unknown) => void;@@ -12,10 +14,6 @@ let loading: Promise<void> | null = null;const LANGS = ["javascript", "typescript", "python", "xml", "css", "json", "bash", "sql", "markdown"] as const;const LANG_ALIASES: Record<string, string> = { html: "xml" };-function escapeHtml(text: string): string {- return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);-}-function rerenderMountedBlocks(): void {if (typeof document === "undefined") return;for (const el of document.querySelectorAll("code-block")) {diff --git a/plugins/web-ui/src/lazy-katex.ts b/plugins/web-ui/src/lazy-katex.tsindex 52bec87db..28ed96dd3 100644--- a/plugins/web-ui/src/lazy-katex.ts+++ b/plugins/web-ui/src/lazy-katex.ts@@ -1,12 +1,10 @@+import { escapeHtml } from "./html-escape.ts";+type Katex = { renderToString: (text: string, opts?: object) => string };let real: Katex | null = null;let loading: Promise<void> | null = null;-function escapeHtml(text: string): string {- return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);-}-function rerenderMountedBlocks(): void {if (typeof document === "undefined") return;for (const el of document.querySelectorAll("markdown-block, qm-markdown")) {diff --git a/plugins/web-ui/src/markdown-sanitize.ts b/plugins/web-ui/src/markdown-sanitize.tsindex 6223b8763..b3e621f9e 100644--- a/plugins/web-ui/src/markdown-sanitize.ts+++ b/plugins/web-ui/src/markdown-sanitize.ts@@ -1,4 +1,5 @@import { marked } from "marked";+import { escapeHtml } from "./html-escape.ts";import DOMPurify, { type Config } from "dompurify";export const MARKDOWN_SANITIZE_CONFIG: Config = {@@ -40,6 +41,9 @@ export function installMarkdownSanitizer(options: { shared?: boolean } = {}): voif (installed) return;installed = true;marked.use({+ walkTokens(token) {+ if (token.type === "html") token.text = escapeHtml(token.text);+ },hooks: {postprocess: (html: string) =>String(diff --git a/plugins/web-ui/src/message-markdown.ts b/plugins/web-ui/src/message-markdown.tsindex 9398cd87d..9b22f34d5 100644--- a/plugins/web-ui/src/message-markdown.ts+++ b/plugins/web-ui/src/message-markdown.ts@@ -3,6 +3,11 @@ import { html, type TemplateResult } from "lit";import { normalizePlainTextFences } from "./text-code";import { escapeLoneDollars } from "./markdown-dollars";-export function markdown(text: string): TemplateResult {- return html`<qm-markdown dir="auto" .content=${escapeLoneDollars(normalizePlainTextFences(text))}></qm-markdown>`;+export function markdown(text: string, isStreaming = false, streamingBaseline = ""): TemplateResult {+ return html`<qm-markdown+ dir="auto"+ .isStreaming=${isStreaming}+ .streamingBaseline=${escapeLoneDollars(normalizePlainTextFences(streamingBaseline))}+ .content=${escapeLoneDollars(normalizePlainTextFences(text))}+ ></qm-markdown>`;}diff --git a/plugins/web-ui/src/shared-session.ts b/plugins/web-ui/src/shared-session.tsindex 0dcd67413..078b4cb66 100644--- a/plugins/web-ui/src/shared-session.ts+++ b/plugins/web-ui/src/shared-session.ts@@ -37,7 +37,7 @@ render(><a class="btn compact" href=${base}>Open ${brandName()}${icon(ArrowUpRight, 14)}</a></div></header>- <main class="chat-scroll readonly-scroll">+ <main class="chat-scroll readonly-scroll" tabindex="0" aria-label="Conversation"><div class="message-stack">${transcript@@ -47,35 +47,35 @@ render(<div class=${message.role === "user" ? "message-bubble user-bubble" : "assistant-body"}><div class=${message.role === "user" ? "pin-content" : "shared-message-content"}>${markdown(message.text)}- ${- message.attachments?.length- ? html`<div class="message-files">- ${message.attachments.map((file) => {- const href = `${location.pathname}/files/${encodeURIComponent(file.id)}`;- const inlineImage = /^image\/(png|jpeg|gif|webp|avif)$/.test(file.mimetype);- if (inlineImage && message.role !== "user") {- return html`<a- class="file-image"- href=${href}- download=${file.name}- rel="noreferrer"- ><img src=${`${href}?inline=1`} alt=${file.name} loading="lazy"- /></a>`;- }- return chipBadge(- inlineImage ? FileImage : File,- file.name,- file.sizeBytes,- inlineImage ? `${href}?inline=1` : href,- !inlineImage,- );- })}- </div>`- : ""- }</div>- ${message.role === "assistant" ? html`<div class="message-meta"><button class="msg-copy" aria-label="Copy message" title="Copy" @click=${(e: Event) => void copyText(message.text, e.currentTarget as HTMLButtonElement)}>${icon(Copy, 13)}</button></div>` : ""}${message.role === "user" ? html`<button class="pin-toggle" type="button" hidden aria-expanded="false">Show more</button>` : ""}+ ${+ message.attachments?.length+ ? html`<div class="message-files">+ ${message.attachments.map((file) => {+ const href = `${location.pathname}/files/${encodeURIComponent(file.id)}`;+ const inlineImage = /^image\/(png|jpeg|gif|webp|avif)$/.test(file.mimetype);+ if (inlineImage && message.role !== "user") {+ return html`<a+ class="file-image"+ href=${href}+ download=${file.name}+ rel="noreferrer"+ ><img src=${`${href}?inline=1`} alt=${file.name} loading="lazy"+ /></a>`;+ }+ return chipBadge(+ inlineImage ? FileImage : File,+ file.name,+ file.sizeBytes,+ inlineImage ? `${href}?inline=1` : href,+ !inlineImage,+ );+ })}+ </div>`+ : ""+ }+ ${message.role === "assistant" ? html`<div class="message-meta"><button class="msg-copy" aria-label="Copy message" title="Copy" @click=${(e: Event) => void copyText(message.text, e.currentTarget as HTMLButtonElement)}>${icon(Copy, 13)}</button></div>` : ""}</div>${message.role === "user" ? html`<div class="message-meta"><button class="msg-copy" aria-label="Copy message" title="Copy" @click=${(e: Event) => void copyText(message.text, e.currentTarget as HTMLButtonElement)}>${icon(Copy, 13)}</button></div>` : ""}</article>diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex d1fa82beb..4ad9b9226 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -1876,21 +1876,19 @@ button.subagent-chip:hover {overflow-anchor: none;}-.streaming-text .tok-in {- animation: tok-in 0.42s ease-out both;+qm-markdown .tok-in {+ animation: tok-in 0.18s ease-out both;}@keyframes tok-in {from {opacity: 0;- filter: blur(1.5px);}to {opacity: 1;- filter: blur(0);}}@media (prefers-reduced-motion: reduce) {- .streaming-text .tok-in {+ qm-markdown .tok-in {animation: none;}}@@ -1933,20 +1931,10 @@ button.subagent-chip:hover {.user-bubble > .pin-content {display: flow-root;}-.message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content {+.message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded) .user-bubble > .pin-content {position: relative;- max-height: var(--pin-clamp, 320px);+ max-height: 2lh;overflow: hidden;- mask-image: linear-gradient(to bottom, #000 calc(100% - 18px), transparent);-}-.message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content::after {- content: "";- position: absolute;- inset: auto 0 0;- height: 18px;- backdrop-filter: blur(2px);- mask-image: linear-gradient(to bottom, transparent, #000);- pointer-events: none;}.message-stack .user-row.pin-expanded .user-bubble > .pin-content {max-height: var(--pin-expanded-max);@@ -2002,6 +1990,23 @@ button.subagent-chip:hover {font-size: 12px;line-height: 1.2;}+.queued-editing {+ flex-wrap: wrap;+ justify-content: flex-end;+}+.queued-edit-input {+ flex-basis: 100%;+ width: 100%;+ min-width: 0;+ resize: vertical;+ padding: 8px;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--background);+ color: var(--foreground);+ font: inherit;+ line-height: 1.5;+}.queued-chip + .queued-chip {margin-top: -10px;}@@ -2277,6 +2282,8 @@ button.subagent-chip:hover {.work summary.work-head {list-style: none;cursor: pointer;+ padding-bottom: 8px;+ border-bottom: 1px solid var(--border);}.work summary.work-head::-webkit-details-marker {display: none;@@ -2299,9 +2306,8 @@ button.subagent-chip:hover {transform: rotate(90deg);}.work-divider {- height: 1px;- background: var(--border);- margin: 8px 0 10px;+ height: 0;+ margin: 0 0 10px;}.work-rows {display: flex;@@ -9932,11 +9938,7 @@ h3.ambient-field-label {.mini-convo-body .message-stack {width: 100%;}-.mini-convo-body- .message-stack- .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits)- .user-bubble- > .pin-content {+.mini-convo-body .message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded) .user-bubble > .pin-content {max-height: 100px;}.mini-convo-missing {diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.tsindex 75b62292f..65779e5bc 100644--- a/plugins/web-ui/src/split.ts+++ b/plugins/web-ui/src/split.ts@@ -1,4 +1,5 @@import { openSessionShare } from "./session-share";+import { preserveTranscriptScroll } from "./transcript-viewport";import { html, nothing, render, type TemplateResult } from "lit";import { ref } from "lit/directives/ref.js";import {@@ -198,6 +199,14 @@ function buildDock(): DockviewApi {disableFloatingGroups: true,});const inner = dockEl.querySelector(":scope > .dv-dockview") as HTMLElement | null;+ let restoreScroll = () => {};+ api.onWillMutateLayout(() => {+ restoreScroll = preserveTranscriptScroll(host);+ });+ api.onDidMutateLayout(() => {+ restoreScroll();+ restoreScroll = () => {};+ });const box = (inner ?? dockEl).getBoundingClientRect();if (box.width > 0) api.layout(box.width, box.height, true);const holdTileCap = (e: DockviewWillDropEvent): void => {@@ -240,6 +249,7 @@ function buildDock(): DockviewApi {});api.onDidMaximizedGroupChange(() => {for (const a of groupActions) a.draw();+ persistSoon();});dockEl.addEventListener("pointerdown", (e) => {if (!(e.target instanceof Element) || !e.target.closest(".dv-sash")) return;diff --git a/plugins/web-ui/src/stable-markdown.ts b/plugins/web-ui/src/stable-markdown.tsindex ea8fbdd35..5c5f184e9 100644--- a/plugins/web-ui/src/stable-markdown.ts+++ b/plugins/web-ui/src/stable-markdown.ts@@ -3,12 +3,23 @@ import { MarkdownBlock } from "@mariozechner/mini-lit/dist/MarkdownBlock.js";import "@mariozechner/mini-lit/dist/CodeBlock.js";import { ReactiveElement, render, type PropertyValues } from "lit";import morphdom from "morphdom";+import { marked, type Tokens } from "marked";export class StableMarkdown extends ReactiveElement {- static properties = { content: {}, isThinking: { type: Boolean } };+ static properties = {+ content: {},+ isThinking: { type: Boolean },+ isStreaming: { type: Boolean },+ streamingBaseline: {},+ };declare content: string;declare isThinking: boolean;+ declare isStreaming: boolean;+ declare streamingBaseline: string;+ private baselineText = "";+ private renderedText = "";+ private readonly fades = new Map<HTMLElement, ReturnType<typeof setTimeout>>();private readonly renderer = new MarkdownBlock();private readonly staging = document.createElement("div");@@ -16,6 +27,9 @@ export class StableMarkdown extends ReactiveElement {super();this.content = "";this.isThinking = false;+ this.isStreaming = false;+ this.streamingBaseline = "";+ this.renderer.escapeHtml = false;}protected createRenderRoot(): HTMLElement {@@ -28,36 +42,179 @@ export class StableMarkdown extends ReactiveElement {this.style.display = "block";}+ disconnectedCallback(): void {+ this.clearFades();+ super.disconnectedCallback();+ }++ private textNodes(root: Node): Text[] {+ const result: Text[] = [];+ const visit = (node: Node): void => {+ if (node.nodeType === Node.TEXT_NODE) {+ if (node.textContent?.trim() || node.parentElement?.closest("p, h1, h2, h3, h4, h5, h6, li, td, th"))+ result.push(node as Text);+ } else if (+ node.nodeType !== Node.ELEMENT_NODE ||+ !["code-block", "svg", "style", "script"].includes((node as Element).localName)+ )+ node.childNodes.forEach(visit);+ };+ visit(root);+ return result;+ }++ private finishFade(span: HTMLElement): void {+ if (!this.fades.has(span)) return;+ span.classList.remove("tok-in");+ clearTimeout(this.fades.get(span));+ this.fades.delete(span);+ }++ private clearFades(): void {+ for (const span of this.fades.keys()) this.finishFade(span);+ }++ private prepareFades(target: HTMLElement, animate: boolean): void {+ const nodes = this.textNodes(target);+ const text = nodes.map((node) => node.data).join("");+ if (this.baselineText.length > this.renderedText.length && this.baselineText.startsWith(this.renderedText))+ this.renderedText = this.baselineText;+ const ranges: Array<{ start: number; end: number; active: boolean }> = [];+ let offset = 0;+ if (!animate) this.clearFades();+ if (text.startsWith(this.renderedText)) {+ for (const node of this.textNodes(this)) {+ if (node.parentElement?.classList.contains("stream-chunk"))+ ranges.push({ start: offset, end: offset + node.length, active: this.fades.has(node.parentElement) });+ offset += node.length;+ }+ if (animate && text.length > this.renderedText.length)+ ranges.push({ start: this.renderedText.length, end: text.length, active: true });+ } else this.clearFades();+ offset = 0;+ for (const node of nodes) {+ const end = offset + node.length;+ const fragments: Node[] = [];+ let consumed = 0;+ for (const range of ranges) {+ const start = Math.max(offset, range.start) - offset;+ const stop = Math.min(end, range.end) - offset;+ if (stop <= start) continue;+ if (start > consumed) fragments.push(document.createTextNode(node.data.slice(consumed, start)));+ const span = document.createElement("span");+ span.className = range.active ? "stream-chunk tok-in" : "stream-chunk";+ span.textContent = node.data.slice(start, stop);+ fragments.push(span);+ consumed = stop;+ }+ if (fragments.length) {+ if (consumed < node.length) fragments.push(document.createTextNode(node.data.slice(consumed)));+ node.replaceWith(...fragments);+ }+ offset = end;+ }+ this.renderedText = text;+ }++ private streamingContent(content: string): string {+ if (!this.isStreaming || !content.includes("|")) return content;+ const normalized = content.replace(/\r\n?/g, "\n");+ if (/\n[\t >]*\n[\t >]*$/.test(normalized)) return content;+ let last = marked.lexer(normalized.trimEnd()).at(-1);+ while (last?.type === "blockquote" || last?.type === "list")+ last =+ last.type === "blockquote"+ ? (last as Tokens.Blockquote).tokens.at(-1)+ : (last as Tokens.List).items.at(-1)?.tokens.at(-1);+ if (!last || (!["paragraph", "text"].includes(last.type) && !(last.type === "heading" && last.raw.includes("\n"))))+ return content;+ const lines = last.raw.trimEnd().split("\n");+ let start = lines.length - 1;+ if (start > 0 && /^[ |:-]+$/.test(lines[start]!) && lines[start - 1]!.includes("|")) start--;+ const header = marked.Lexer.lexInline(lines[start]!);+ if (!header.some((token) => token.type === "text" && token.raw.includes("|"))) return content;+ const source = normalized.trimEnd().split("\n");+ while (/^\s*(>\s*)+$/.test(source.at(-1) ?? "")) source.pop();+ return source.slice(0, source.length - (lines.length - start)).join("\n");+ }+protected update(changed: PropertyValues): void {- this.renderer.content = this.content;- this.renderer.isThinking = this.isThinking;- render(this.renderer.render(), this.staging);- morphdom(this, this.staging.cloneNode(true), {- childrenOnly: true,- onBeforeElUpdated: (current, next) => {- if (current.localName === "code-block") {- for (const name of ["code", "language"]) {- const value = next.getAttribute(name);- if (value !== current.getAttribute(name)) {- if (value === null) current.removeAttribute(name);- else current.setAttribute(name, value);+ const completion = Promise.withResolvers<void>();+ this.dispatchEvent(new window.CustomEvent("qm-content-updating", { bubbles: true, detail: completion.promise }));+ try {+ if (changed.has("streamingBaseline")) {+ const baseline = document.createElement("div");+ this.renderer.content = this.streamingContent(this.streamingBaseline);+ render(this.renderer.render(), baseline);+ this.baselineText = this.textNodes(baseline)+ .map((node) => node.data)+ .join("");+ }+ this.renderer.content = this.streamingContent(this.content);+ this.renderer.isThinking = this.isThinking;+ render(this.renderer.render(), this.staging);+ const target = this.staging.cloneNode(true) as HTMLElement;+ const animate = this.isStreaming && !window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;+ this.prepareFades(target, animate);+ morphdom(this, target, {+ childrenOnly: true,+ onBeforeElUpdated: (current, next) => {+ if (current.localName === "code-block") {+ for (const name of ["code", "language"]) {+ const value = next.getAttribute(name);+ if (value !== current.getAttribute(name)) {+ if (value === null) current.removeAttribute(name);+ else current.setAttribute(name, value);+ }}+ return false;+ }+ for (let i = 0; i < current.childNodes.length; i++) {+ const from = current.childNodes[i];+ const to = next.childNodes[i];+ if (from?.nodeType !== Node.TEXT_NODE || to?.nodeType !== Node.TEXT_NODE) continue;+ const before = from.nodeValue ?? "";+ const after = to.nodeValue ?? "";+ if (after.length > before.length && after.startsWith(before))+ (from as Text).appendData(after.slice(before.length));}- return false;- }- for (let i = 0; i < current.childNodes.length; i++) {- const from = current.childNodes[i];- const to = next.childNodes[i];- if (from?.nodeType !== Node.TEXT_NODE || to?.nodeType !== Node.TEXT_NODE) continue;- const before = from.nodeValue ?? "";- const after = to.nodeValue ?? "";- if (after.length > before.length && after.startsWith(before))- (from as Text).appendData(after.slice(before.length));- }- return !current.isEqualNode(next);- },- });- super.update(changed);+ return !current.isEqualNode(next);+ },+ });+ for (const span of this.querySelectorAll<HTMLElement>("span.tok-in")) {+ if (this.fades.has(span)) continue;+ span.addEventListener("animationend", () => this.finishFade(span), { once: true });+ this.fades.set(+ span,+ setTimeout(() => this.finishFade(span), 220),+ );+ }+ for (const [span, timer] of this.fades) {+ if (this.contains(span)) continue;+ clearTimeout(timer);+ this.fades.delete(span);+ }+ super.update(changed);+ const updated = (): void => {+ this.dispatchEvent(new window.Event("qm-content-updated", { bubbles: true }));+ completion.resolve();+ };+ const codeUpdates = [...this.querySelectorAll<ReactiveElement>("code-block")].map((code) => code.updateComplete);+ if (codeUpdates.length) {+ void Promise.allSettled(codeUpdates)+ .then(() =>+ Promise.allSettled(+ [...this.querySelectorAll<ReactiveElement>("code-block copy-button")].map(+ (button) => button.updateComplete,+ ),+ ),+ )+ .then(updated, updated);+ } else updated();+ } catch (error) {+ completion.resolve();+ throw error;+ }}}diff --git a/plugins/web-ui/src/timeline.ts b/plugins/web-ui/src/timeline.tsindex 6620f83eb..88daf177c 100644--- a/plugins/web-ui/src/timeline.ts+++ b/plugins/web-ui/src/timeline.ts@@ -166,12 +166,15 @@ function buildTimelineUncached(work: WorkBlock): TimelineItem[] {const rowByCallId = new Map<string, ToolRowModel>();let open: ToolRowModel | null = null;for (const a of work.activity) {+ if (a.type === "text_start") continue;if (a.type === "thinking") {items.push({ kind: "thinking", activity: a });open = null;} else if (a.type === "text") {items.push({ kind: "text", activity: a });open = null;+ } else if (a.type === "approval_resolved") {+ open = null;} else if (a.type === "tool_call") {const row: ToolRowModel = { call: a, result: null };const cid = callIdOf(a);@@ -253,3 +256,58 @@ export function sessionToolView(} else if (action === "read") detail = result.status ?? "";return { action, chipTitle, ...(sessionId ? { sessionId } : {}), detail };}++export function currentTextPhase(work: WorkBlock): {+ phase: "commentary" | "final_answer";+ streamOffset: number;+ startedAt: number;+} | null {+ const entry = work.activity.findLast((activity) => activity.type === "text_start");+ if (!entry) return null;+ const payload = entry.payload as { phase?: unknown; streamOffset?: unknown } | null;+ if (+ (payload?.phase !== "commentary" && payload?.phase !== "final_answer") ||+ typeof payload.streamOffset !== "number" ||+ !Number.isSafeInteger(payload.streamOffset) ||+ payload.streamOffset < 0+ )+ return null;+ return { phase: payload.phase, streamOffset: payload.streamOffset, startedAt: entry.createdAt };+}++export function streamedAnswer(text: string, work: WorkBlock): string {+ const phase = currentTextPhase(work);+ return phase?.phase === "final_answer" ? text.slice(phase.streamOffset) : streamingTextTail(text, work.activity);+}++export function streamingTextTail(text: string, activity: ToolActivity[]): string {+ let tail = text;+ for (const entry of activity) {+ if (entry.type !== "text") continue;+ const spoken = ((entry.payload as { text?: string } | null)?.text ?? "").trim();+ if (!spoken) continue;+ const candidate = tail.trimStart();+ if (candidate.startsWith(spoken)) tail = candidate.slice(spoken.length).replace(/^\s*?\n\n/, "");+ else if (spoken.startsWith(candidate)) return "";+ else break;+ }+ return tail;+}++export function messageWorkTimeline(work: WorkBlock, finalText: string): TimelineItem[] {+ const timeline = buildTimeline(work);+ const lastText = finalText.trim() ? timeline.findLastIndex((item) => item.kind === "text") : -1;+ return timeline.filter((item, index) => {+ if (item.kind === "thinking") {+ const payload = item.activity.payload as { thinking?: string; redacted?: boolean } | null;+ return !payload?.redacted && Boolean(payload?.thinking?.trim());+ }+ if (item.kind !== "text") return true;+ const payload = item.activity.payload as { text?: string; demoted?: boolean; phase?: string } | null;+ return (+ !payload?.demoted &&+ Boolean(payload?.text?.trim()) &&+ !(index === lastText && payload?.phase !== "commentary" && payload?.text?.trim() === finalText.trim())+ );+ });+}diff --git a/plugins/web-ui/src/transcript-viewport.ts b/plugins/web-ui/src/transcript-viewport.tsindex 079005e62..cf88b9e9f 100644--- a/plugins/web-ui/src/transcript-viewport.ts+++ b/plugins/web-ui/src/transcript-viewport.ts@@ -1,3 +1,31 @@+export function preserveTranscriptScroll(root: HTMLElement): () => void {+ const snapshots = [...root.querySelectorAll<HTMLElement>(".chat-scroll")]+ .filter((element) => element.clientHeight > 0)+ .map((element) => {+ const top = element.getBoundingClientRect().top;+ const anchor = [+ ...element.querySelectorAll<HTMLElement>(".message-stack :is(p, h1, h2, h3, h4, h5, h6, pre, li, table)"),+ ].find((node) => !node.closest(".user-row") && node.getBoundingClientRect().bottom > top);+ return {+ element,+ scrollTop: element.scrollTop,+ bottom: element.scrollHeight - element.clientHeight - element.scrollTop <= 1,+ anchor,+ offset: anchor ? anchor.getBoundingClientRect().top - top : 0,+ };+ });+ return () => {+ for (const snapshot of snapshots) {+ const { element, anchor } = snapshot;+ if (!root.contains(element) || element.clientHeight === 0) continue;+ if (snapshot.bottom) element.scrollTop = element.scrollHeight;+ else if (anchor && element.contains(anchor))+ element.scrollTop += anchor.getBoundingClientRect().top - element.getBoundingClientRect().top - snapshot.offset;+ else element.scrollTop = snapshot.scrollTop;+ }+ };+}+export function createTranscriptViewport() {let scroller: HTMLElement | null = null;let pins: HTMLElement | null = null;@@ -14,6 +42,7 @@ export function createTranscriptViewport() {let observer: ResizeObserver | null = null;let following = false;let frame: number | null = null;+ const contentUpdates = new Set<Promise<void>>();function setFollowing(value: boolean): void {following = value;@@ -33,8 +62,7 @@ export function createTranscriptViewport() {function clearPrompt(): void {if (content) content.scrollTop = 0;- prompt?.classList.remove("stuck", "sticky-disabled", "pin-expanded", "pin-fits");- prompt?.style.removeProperty("--pin-clamp");+ prompt?.classList.remove("stuck", "sticky-disabled", "pin-expanded");prompt?.style.removeProperty("--pin-expanded-max");const toggle = prompt?.querySelector<HTMLButtonElement>(".pin-toggle");if (toggle) toggle.hidden = true;@@ -44,19 +72,13 @@ export function createTranscriptViewport() {function syncPrompt(): void {if (!scroller || !prompt || !content) return;- prompt.style.setProperty(- "--pin-clamp",- `${Math.round(Math.min(320, Math.max(96, scroller.clientHeight * 0.35)))}px`,- );prompt.classList.toggle("pin-expanded", expanded);- // Measure at the normal clamp before deciding whether collapsing saves a useful amount.- prompt.classList.remove("pin-fits");- const clipped = !expanded && content.scrollHeight > content.clientHeight + 24;- prompt.classList.toggle("pin-fits", !expanded && !clipped);+ const clipped = !expanded && content.scrollHeight > content.clientHeight + 1;const toggle = prompt.querySelector<HTMLButtonElement>(".pin-toggle");if (toggle) {toggle.hidden = !clipped && !expanded;- toggle.textContent = expanded ? "Show less" : "Show more";+ const label = expanded ? "Show less" : "Show more";+ if (toggle.textContent !== label) toggle.textContent = label;toggle.setAttribute("aria-expanded", String(expanded));}}@@ -100,7 +122,7 @@ export function createTranscriptViewport() {}function onScroll(): void {- if (!scroller) return;+ if (!scroller || contentUpdates.size > 0) return;const atBottom = scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop <= 1;const reachedPreviousBottom =scroller.scrollTop > lastTop &&@@ -124,11 +146,30 @@ export function createTranscriptViewport() {}function beforeRender(): void {- if (!scroller) return;+ if (!scroller || contentUpdates.size > 0) return;if (scroller.scrollTop !== lastTop) onScroll();measureBottom();}+ function onContentUpdating(event: Event): void {+ beforeRender();+ const completion = (event as CustomEvent<Promise<void>>).detail;+ contentUpdates.add(completion);+ const complete = (): void => {+ if (contentUpdates.delete(completion) && contentUpdates.size === 0) afterRender();+ };+ void completion.then(complete, complete);+ }++ function afterRender(): void {+ if (!scroller || !following || contentUpdates.size > 0) return;+ lastTop = scroller.scrollTop;+ measureBottom();+ if (frame !== null) cancelAnimationFrame(frame);+ frame = null;+ follow();+ }+function onWheel(event: WheelEvent): void {if (!scroller) return;if (event.deltaY < 0 && scroller.scrollTop > 0) cancelFollow();@@ -145,23 +186,32 @@ export function createTranscriptViewport() {setFollowing(true);}+ function onKeyDown(event: KeyboardEvent): void {+ clearInput();+ if (event.target !== scroller || event.key !== "End" || event.shiftKey || event.altKey) return;+ event.preventDefault();+ follow(true);+ }+function dispose(): void {clearInput();if (frame !== null) cancelAnimationFrame(frame);frame = null;observer?.disconnect();observer = null;+ scroller?.removeEventListener("qm-content-updating", onContentUpdating);scroller?.removeEventListener("scroll", onScroll);scroller?.removeEventListener("wheel", onWheel);scroller?.removeEventListener("click", onClick);scroller?.removeEventListener("pointerdown", clearInput);- scroller?.removeEventListener("keydown", clearInput);+ scroller?.removeEventListener("keydown", onKeyDown);scroller?.style.removeProperty("--chat-sticky-top");scroller?.style.removeProperty("overflow-anchor");clearPrompt();scroller = pins = prompt = stack = content = null;lastTop = lastBottom = previousBottom = bottomChangedAt = 0;following = false;+ contentUpdates.clear();}function sync(element: HTMLElement | null): void {@@ -173,11 +223,12 @@ export function createTranscriptViewport() {lastTop = scroller?.scrollTop ?? 0;lastBottom = previousBottom = scroller ? scroller.scrollHeight - scroller.clientHeight : 0;setFollowing(false);+ scroller?.addEventListener("qm-content-updating", onContentUpdating);scroller?.addEventListener("scroll", onScroll, { passive: true });scroller?.addEventListener("wheel", onWheel, { passive: true });scroller?.addEventListener("click", onClick);scroller?.addEventListener("pointerdown", clearInput);- scroller?.addEventListener("keydown", clearInput);+ scroller?.addEventListener("keydown", onKeyDown);if (typeof ResizeObserver !== "undefined") {observer = new ResizeObserver(() => {beforeRender();@@ -227,12 +278,12 @@ export function createTranscriptViewport() {if (frame !== null) cancelAnimationFrame(frame);frame = null;}- if (!scroller || !following || frame !== null) return;+ if (!scroller || !following || contentUpdates.size > 0 || frame !== null) return;const element = scroller;const priorTop = element.scrollTop;frame = requestAnimationFrame(() => {frame = null;- if (element !== scroller || !element.isConnected || !following) return;+ if (element !== scroller || !element.isConnected || !following || contentUpdates.size > 0) return;if (element.scrollTop < priorTop && element.scrollHeight - element.clientHeight - element.scrollTop > 1)return cancelFollow();element.scrollTop = element.scrollHeight;@@ -241,5 +292,5 @@ export function createTranscriptViewport() {});}- return { sync, follow, beforeRender, dispose };+ return { sync, follow, beforeRender, afterRender, dispose };}diff --git a/plugins/web-ui/src/work-duration.ts b/plugins/web-ui/src/work-duration.tsindex ca2a55163..65f4eb779 100644--- a/plugins/web-ui/src/work-duration.ts+++ b/plugins/web-ui/src/work-duration.ts@@ -1,11 +1,16 @@-import type { WorkBlock } from "./core-bridge";+import { currentTextPhase } from "./timeline.ts";+import { goalElapsedLabel } from "./goal-strip.ts";+import { workPausedForApproval, type WorkBlock } from "./core-bridge.ts";export function workSeconds(work: WorkBlock): number {const times = work.activity.map((a) => a.createdAt).filter((t) => typeof t === "number" && t > 0);const start = work.startedAt ?? (times.length ? Math.min(...times) : null);if (start == null) return 0;const live = work.status === "thinking" || work.status === "working";- let end = work.finishedAt;+ const phase = currentTextPhase(work);+ const last = work.activity.at(-1);+ let end = workPausedForApproval(work) ? last!.createdAt : work.finishedAt;+ if (phase?.phase === "final_answer") end = phase.startedAt;if (end == null) {if (live) end = Date.now();else end = times.length ? Math.max(...times, start) : start;@@ -14,5 +19,5 @@ export function workSeconds(work: WorkBlock): number {}export function workedLabel(prefix: string, secs: number): string {- return secs > 0 ? `${prefix} for ${secs}s` : prefix;+ return secs > 0 ? `${prefix} for ${goalElapsedLabel(0, secs * 1000)}` : prefix;}diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.tsindex 315715ef9..7cd6ec831 100644--- a/plugins/web-ui/test/approval-handoff.test.ts+++ b/plugins/web-ui/test/approval-handoff.test.ts@@ -12,6 +12,21 @@ function deferred<T>() {return { promise, resolve };}+function deferredRun() {+ const completion = deferred<Response>();+ let initial = true;+ return {+ resolve: completion.resolve,+ response() {+ if (initial) {+ initial = false;+ return Promise.resolve(Response.json({ status: "running", result: null }));+ }+ return completion.promise;+ },+ };+}+async function until(check: () => boolean): Promise<void> {for (let i = 0; i < 200; i++) {if (check()) return;@@ -55,7 +70,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"let modelDeleted = false;let pending = [approval];let decision = deferred<Response>();- let continuation = deferred<Response>();+ let continuation = deferredRun();const handoff = deferred<void>();let refreshGate: ReturnType<typeof deferred<void>> | undefined;let submitted = false;@@ -86,7 +101,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"return decision.promise;}if (path.includes("/api/runs/active")) return Response.json({ runId: null, queued: [] });- if (path === "/api/runs/r1") return continuation.promise;+ if (path === "/api/runs/r1") return continuation.response();if (path === "/api/runs/q1") return Response.json({ status: "done", result: { status: "ok", reply: "done" } });if (path === "/api/turn") return Response.json({ runId: "q1" });if (path === "/api/runs/q1/withdraw") return Response.json({ withdrawn: true });@@ -188,7 +203,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"click("Deny");await until(() => requests.some((r) => r.path === "/api/approvals/a2"));pending = [];- continuation = deferred<Response>();+ continuation = deferredRun();continuation.resolve(Response.json({ status: "done", result: { status: "refused", reason: "approval denied" } }));decision.resolve(Response.json({ runId: "r1" }));await until(() => !chat.state.agent!.state.isStreaming && chat.state.resolvingApprovals.size === 0);@@ -208,7 +223,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"submitted = false;pending = [approval];decision = deferred<Response>();- continuation = deferred<Response>();+ continuation = deferredRun();mount();click("Allow once");decision.resolve(Response.json({ runId: "r1" }));@@ -224,7 +239,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"submitted = false;pending = [approval];decision = deferred<Response>();- continuation = deferred<Response>();+ continuation = deferredRun();mount();click("Allow once");decision.resolve(Response.json({ runId: "r1" }));diff --git a/plugins/web-ui/test/history.test.ts b/plugins/web-ui/test/history.test.tsindex daf33b41b..ba41f47d1 100644--- a/plugins/web-ui/test/history.test.ts+++ b/plugins/web-ui/test/history.test.ts@@ -1,9 +1,12 @@+import { buildTimeline, messageWorkTimeline } from "../src/timeline.ts";import { test } from "node:test";import assert from "node:assert/strict";import { JSDOM } from "jsdom";import type { AgentMessage } from "@earendil-works/pi-agent-core";import {attachPendingApprovals,+ continuableMessages,+ messagesWithStreaming,currentEarlierCount,entriesToMessages,forkOriginDetails,@@ -15,6 +18,95 @@ import {type SessionEntry,} from "../src/core-bridge.ts";+test("approval decisions remain visible history events instead of unresolved tool rows", () => {+ const messages = entriesToMessages([+ { type: "user", seq: 1, createdAt: 1, payload: { text: "show help" } },+ { type: "tool_result", seq: 2, createdAt: 2, payload: { tool: "execute", blocked: "needs_approval" } },+ { type: "assistant", seq: 3, createdAt: 3, payload: { text: "" } },+ { type: "approval_resolved", seq: 4, createdAt: 4, payload: { command: "rm -r --help", approved: false } },+ {+ type: "approval_resolved",+ seq: 5,+ createdAt: 5,+ payload: { command: "rm -r --help", approved: true, scope: "once" },+ },+ ]);+ assert.deepEqual(messages.slice(-2), [+ { role: "approval-decision", command: "rm -r --help", approved: false, timestamp: 4 },+ { role: "approval-decision", command: "rm -r --help", approved: true, scope: "once", timestamp: 5 },+ ]);+});++test("steering keeps the active turn together through hydration and tool completion", () => {+ const entries: SessionEntry[] = [+ { type: "user", payload: { text: "start" }, createdAt: 1, seq: 1 },+ { type: "text", payload: { text: "Working", phase: "commentary" }, createdAt: 2, seq: 2 },+ { type: "tool_call", payload: { tool: "execute", callId: "one", command: "sleep 40" }, createdAt: 3, seq: 3 },+ { type: "user", payload: { text: "change direction", steered: true }, createdAt: 4, seq: 4 },+ { type: "user", payload: { text: "finish briefly", steered: true }, createdAt: 5, seq: 5 },+ ];+ const active = entriesToMessages(entries);+ assert.deepEqual(+ active.map((message) => message.role),+ ["user", "user", "user", "assistant"],+ );+ const resumed = continuableMessages(active);+ assert.deepEqual(+ resumed.messages.map((message) => message.role),+ ["user", "user", "user"],+ );+ assert.equal(resumed.popped.length, 1);+ assert.deepEqual(+ (resumed.popped[0] as AssistantWork).work?.activity.map((entry) => entry.seq),+ [2, 3],+ );+ const finished = entriesToMessages([+ ...entries,+ { type: "tool_result", payload: { tool: "execute", callId: "one", code: 0 }, createdAt: 6, seq: 6 },+ { type: "assistant", payload: { text: "Done" }, createdAt: 7, seq: 7 },+ ]);+ assert.deepEqual(+ finished.map((message) => message.role),+ ["user", "user", "user", "assistant"],+ );+ const work = (finished.at(-1) as AssistantWork).work!;+ assert.deepEqual(+ work.activity.map((entry) => entry.seq),+ [2, 3, 6],+ );+ const tools = buildTimeline(work).filter((item) => item.kind === "tool");+ assert.equal(tools.length, 1);+ assert.equal(tools[0]!.row.call?.seq, 3);+ assert.equal(tools[0]!.row.result?.seq, 6);+});++test("steering preserves an in-flight post and does not promote its closing narration", () => {+ const messages = entriesToMessages([+ { type: "user", payload: { text: "start" }, createdAt: 1, seq: 1 },+ {+ type: "tool_call",+ payload: { tool: "web", action: "post", text: "Delivered", callId: "one" },+ createdAt: 2,+ seq: 2,+ },+ { type: "user", payload: { text: "finish briefly", steered: true }, createdAt: 3, seq: 3 },+ { type: "tool_result", payload: { tool: "web", action: "post", ok: true, callId: "one" }, createdAt: 4, seq: 4 },+ { type: "user", payload: { text: "no more posts", steered: true }, createdAt: 5, seq: 5 },+ { type: "text", payload: { text: "Finished posting" }, createdAt: 6, seq: 6 },+ { type: "assistant", payload: { text: "" }, createdAt: 7, seq: 7 },+ ]);+ const replies = messages.filter((message) => message.role === "assistant") as AssistantWork[];+ assert.equal(replies.length, 2);+ assert.deepEqual(+ replies.map((message) => message.content),+ [[{ type: "text", text: "Delivered" }], [{ type: "text", text: "" }]],+ );+ assert.deepEqual(+ replies[1]!.work?.activity.map((entry) => entry.seq),+ [6],+ );+});+test("fork provenance separates inherited entries at the boundary", () => {const entries: SessionEntry[] = [{ type: "user", payload: { text: "old" }, createdAt: 1, seq: 1 },@@ -879,6 +971,7 @@ test("a surface post renders as the reply bubble; the closing self-log demotes t);const trailer = msgs[2] as AssistantWork & { content: Array<{ text?: string }> };assert.equal(trailer.content[0]?.text ?? "", "", "the self-log is not a reply bubble");+ assert.deepEqual(messageWorkTimeline(trailer.work!, ""), [], "the demoted-only trailer has no visible work fold");assert.ok(JSON.stringify(trailer.work?.activity ?? []).includes("Replied in thread"),"the self-log survives as work narration",@@ -1411,3 +1504,86 @@ test("a surface post's sent files render as delivered files on the reply bubble""the attachments the post actually sent are surfaced on the message",);});++for (const text of ["Partial answer", "", "(stopped)"]) {+ test(`stopped history retains its state without promoting commentary: ${text || "empty"}`, () => {+ const entries: SessionEntry[] = [+ { seq: 1, type: "user", payload: { text: "check" }, createdAt: 1 },+ { seq: 2, type: "text", payload: { text: "Checking.", phase: "commentary" }, createdAt: 2 },+ { seq: 3, type: "assistant", payload: { text, stopped: true }, createdAt: 3 },+ ];+ const messages = entriesToMessages(entries);+ const answer = messages.find((message) => message.role === "assistant") as AssistantWork;+ assert.equal(answer.stopReason, "aborted");+ assert.deepEqual(answer.content, [{ type: "text", text }]);+ assert.equal(answer.work?.activity.length, 1);+ assert.equal(messageWorkTimeline(answer.work!, text)[0]?.kind, "text");+ });+}++test("live approval decisions are outside tool folds and reconcile by request identity", () => {+ const entry = {+ type: "approval_resolved" as const,+ seq: 8,+ parentSeq: null,+ createdAt: 100,+ payload: { requestId: "approval-1", command: "help", approved: true, scope: "once" },+ };+ const streaming = {+ role: "assistant",+ content: [{ type: "text", text: "" }],+ work: { status: "working", activity: [entry] },+ } as unknown as AgentMessage;+ const live = messagesWithStreaming([], streaming);+ assert.equal(live.length, 2);+ assert.equal((live[0] as { role: string }).role, "approval-decision");+ assert.equal(live[1], streaming);+ assert.deepEqual(messagesWithStreaming([streaming]), live);+ assert.deepEqual(buildTimeline((streaming as AssistantWork).work!), []);+ const history = entriesToMessages([entry]);+ assert.deepEqual(messagesWithStreaming(history, streaming), [...history, streaming]);+ const repeated = {+ ...streaming,+ work: { status: "working", activity: [{ ...entry, seq: 9, createdAt: 200 }] },+ } as unknown as AgentMessage;+ assert.equal(messagesWithStreaming(history, repeated).length, 3);+ const denied = { ...entry, payload: { ...entry.payload, requestId: "approval-2", approved: false } };+ const denialStream = { ...streaming, work: { status: "complete", activity: [denied] } } as unknown as AgentMessage;+ assert.equal(messagesWithStreaming(history, denialStream).length, 3);+});++test("a recorded decision clears stale approval labels without consuming a later request", () => {+ const pending = { requestId: "same-command", command: "help" };+ const blocked = (createdAt: number) =>+ ({+ role: "assistant",+ content: [{ type: "text", text: "" }],+ timestamp: createdAt,+ work: {+ status: "complete",+ pendingApprovals: [pending],+ activity: [{ seq: 1, parentSeq: null, type: "tool_result", payload: { blocked: "needs_approval" }, createdAt }],+ },+ }) as unknown as AgentMessage;+ const decision = {+ type: "approval_resolved" as const,+ seq: 2,+ parentSeq: null,+ createdAt: 200,+ payload: { requestId: pending.requestId, command: pending.command, approved: false },+ };+ const old = blocked(100);+ const fresh = blocked(300);+ const streaming = {+ role: "assistant",+ content: [],+ work: { status: "working", activity: [decision] },+ } as unknown as AgentMessage;+ const visible = messagesWithStreaming([old, fresh], streaming);+ assert.deepEqual((visible[0] as AssistantWork).work?.pendingApprovals, []);+ assert.equal(visible[1], fresh);+ assert.deepEqual((old as AssistantWork).work?.pendingApprovals, [pending]);+ const history = messagesWithStreaming([old, ...entriesToMessages([decision]), fresh]);+ assert.deepEqual((history[0] as AssistantWork).work?.pendingApprovals, []);+ assert.equal(history.at(-1), fresh);+});diff --git a/plugins/web-ui/test/layout-thrash.test.ts b/plugins/web-ui/test/layout-thrash.test.tsindex 5485cfffd..77f0bed79 100644--- a/plugins/web-ui/test/layout-thrash.test.ts+++ b/plugins/web-ui/test/layout-thrash.test.ts@@ -23,7 +23,7 @@ test("a box-size change re-arms the composer measure via ResizeObserver (fires atest("bottom-follow's skip path performs zero layout reads", () => {const fn = viewport.slice(viewport.indexOf(" function follow("));- const skip = fn.indexOf("if (!scroller || !following || frame !== null) return;");+ const skip = fn.indexOf("if (!scroller || !following || contentUpdates.size > 0 || frame !== null) return;");const firstRead = fn.indexOf("const priorTop = element.scrollTop;");assert.ok(skip >= 0 && skip < firstRead);assert.match(viewport, /if \(changed\) syncSticky\(\);/);diff --git a/plugins/web-ui/test/pinned-composer-polish.test.ts b/plugins/web-ui/test/pinned-composer-polish.test.tsindex e6816abf6..6cb31f230 100644--- a/plugins/web-ui/test/pinned-composer-polish.test.ts+++ b/plugins/web-ui/test/pinned-composer-polish.test.ts@@ -51,14 +51,11 @@ test("queued cards tuck beneath the next card just as the queue tucks beneath thassert.match(stacked, /margin-top: -10px;/);});-test("only collapsed overflowing prompt content gets the soft cutoff", () => {- const selector =- ".message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded):not(.pin-fits) .user-bubble > .pin-content";+test("collapsed prompt content uses a readable two-line cutoff", () => {+ const selector = ".message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded) .user-bubble > .pin-content";const rule = css.slice(css.indexOf(`${selector} {`)).split("}")[0] ?? "";- const overlay = css.slice(css.indexOf(`${selector}::after {`)).split("}")[0] ?? "";- assert.match(rule, /position: relative;/);- assert.match(rule, /mask-image: linear-gradient\(to bottom, #000 calc\(100% - 18px\), transparent\);/);- assert.match(overlay, /height: 18px;/);- assert.match(overlay, /backdrop-filter: blur\(2px\);/);- assert.match(overlay, /pointer-events: none;/);+ assert.match(rule, /max-height: 2lh;/);+ assert.match(rule, /overflow: hidden;/);+ assert.doesNotMatch(rule, /mask-image|blur/);+ assert.equal(css.includes(`${selector}::after`), false);});diff --git a/plugins/web-ui/test/pinned-prompt-collapse.test.ts b/plugins/web-ui/test/pinned-prompt-collapse.test.tsindex d35bdee0a..2a95110e0 100644--- a/plugins/web-ui/test/pinned-prompt-collapse.test.ts+++ b/plugins/web-ui/test/pinned-prompt-collapse.test.ts@@ -25,8 +25,7 @@ function fixture() {const limit = row.style.getPropertyValue("--pin-expanded-max");return Math.min(fullHeight, limit ? parseFloat(limit) : fullHeight);}- if (row.classList.contains("pin-fits")) return fullHeight;- return Math.min(fullHeight, parseFloat(row.style.getPropertyValue("--pin-clamp")) || 320);+ return Math.min(fullHeight, 46.5);},},});@@ -90,7 +89,7 @@ function fixture() {test("long prompts clamp to the pane and expand or collapse through their button", () => {const f = fixture();try {- assert.equal(f.row.style.getPropertyValue("--pin-clamp"), "105px");+ assert.equal(f.content.clientHeight, 46.5);assert.equal(f.toggle.hidden, false);f.toggle.click();assert.equal(f.row.classList.contains("pin-expanded"), true);@@ -104,13 +103,13 @@ test("long prompts clamp to the pane and expand or collapse through their button}});-test("pane resizes respect the minimum and maximum preview heights", () => {+test("pane resizes keep the compact preview height", () => {const f = fixture();try {f.resize(100);- assert.equal(f.row.style.getPropertyValue("--pin-clamp"), "96px");+ assert.equal(f.content.clientHeight, 46.5);f.resize(2000);- assert.equal(f.row.style.getPropertyValue("--pin-clamp"), "320px");+ assert.equal(f.content.clientHeight, 46.5);} finally {f.close();}@@ -219,7 +218,7 @@ test("expanding a scrolled prompt stays sticky with a bounded scrollable body",f.toggle.click();assert.equal(f.content.scrollTop, 0);assert.equal(f.row.classList.contains("stuck"), true);- assert.equal(f.content.clientHeight, 105);+ assert.equal(f.content.clientHeight, 46.5);assert.equal(f.scroller.scrollTop, 500);} finally {f.close();@@ -265,3 +264,21 @@ test("an expanded prompt stays in flow when its chrome alone cannot fit", () =>f.close();}});++test("repeated prompt measurement preserves the disclosure text node", () => {+ const f = fixture();+ try {+ const label = f.toggle.firstChild;+ for (const height of [300, 200, 500]) {+ f.resize(height);+ assert.equal(f.toggle.firstChild, label);+ }+ f.toggle.click();+ const expandedLabel = f.toggle.firstChild;+ assert.notEqual(expandedLabel, label);+ f.resize(400);+ assert.equal(f.toggle.firstChild, expandedLabel);+ } finally {+ f.close();+ }+});diff --git a/plugins/web-ui/test/post-reply-recovery.test.ts b/plugins/web-ui/test/post-reply-recovery.test.tsindex 5c7a9fdd4..1a51f4781 100644--- a/plugins/web-ui/test/post-reply-recovery.test.ts+++ b/plugins/web-ui/test/post-reply-recovery.test.ts@@ -194,10 +194,19 @@ test("post replies remain visible in new and continuing conversations", async (tif (wait) await settle();requests.length = 0;}- const shown = (text: string) =>- [...host.querySelectorAll(".assistant-body > .streaming-text, .work-said")].some((el) =>+ const shownReplies = (text: string) => {+ const matches = [...host.querySelectorAll(".assistant-body > .streaming-text, .work-message")].filter((el) =>el.textContent?.includes(text),);+ for (const match of matches)+ assert.equal(+ match.closest("details:not([open])"),+ null,+ "delivered replies must remain visible outside closed work",+ );+ return matches;+ };+ const shown = (text: string) => shownReplies(text).length > 0;async function postTurn(index: number, fails = false) {const text = `Confirmed answer ${index}`;const seq = index * 3;@@ -226,6 +235,9 @@ test("post replies remain visible in new and continuing conversations", async (t...activity,];transcriptFails = fails;+ run.emit("run", { status: "running", result: null, activity });+ await settle();+ assert.equal(shownReplies(text).length, 1, "a confirmed post is visible while the turn continues");run.emit("done", { status: "done", result: { status: "silent", sessionId: row.id }, activity });await turn;await settle();@@ -273,13 +285,7 @@ test("post replies remain visible in new and continuing conversations", async (tdelivery.emit("delivery", { threadRef: row.threadRef });await settle();for (let i = 0; i < 3; i++) {- assert.equal(- [...host.querySelectorAll(".assistant-body > .streaming-text, .work-said")].filter((el) =>- el.textContent?.includes(`Confirmed answer ${i}`),- ).length,- 1,- "refresh must not duplicate a displayed post",- );+ assert.equal(shownReplies(`Confirmed answer ${i}`).length, 1, "refresh must not duplicate a displayed post");}});function deferredTranscript(recorded: SessionEntry[]) {@@ -385,13 +391,20 @@ test("post replies remain visible in new and continuing conversations", async (tconst run = FakeEventSource.instances.findLast((es) => es.url === "/api/runs/r1/events")!;run.onopen?.();transcriptFails = true;+ run.emit("run", { status: "running", result: null, activity });+ await settle();+ assert.deepEqual(+ shownReplies(answer).map((el) => el.textContent?.trim()),+ [answer],+ );+ assert.deepEqual(+ shownReplies("Second confirmed reply").map((el) => el.textContent?.trim()),+ ["Second confirmed reply"],+ );run.emit("done", { status: "done", result: { status: "silent", sessionId: row.id }, activity });await turn;await settle();- const count = (text: string) =>- [...host.querySelectorAll(".assistant-body > .streaming-text, .work-said")].filter((el) =>- el.textContent?.includes(text),- ).length;+ const count = (text: string) => shownReplies(text).length;assert.equal(count(answer), 1);assert.equal(count("Second confirmed reply"), 1);entries = [diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.tsindex f17a4cd5c..50f5a8309 100644--- a/plugins/web-ui/test/queue-by-default.test.ts+++ b/plugins/web-ui/test/queue-by-default.test.ts@@ -222,7 +222,7 @@ test("settling a turn follows the next queued run instead of sending it", () =>assert.doesNotMatch(fn, /queueTurn/, "it never submits anything");assert.match(fn,- /await \(next && !recorded \? agent\.prompt\(next\.text\) : agent\.continue\(\)\)/,+ /await \(!active\.run\.input && next && !recorded \? agent\.prompt\(next\.text\) : agent\.continue\(\)\)/,"an already-recorded turn is resumed, never prompted a second time onto the screen",);assert.match(fn, /await refreshTranscriptFromEntries\(agent\)/);diff --git a/plugins/web-ui/test/resume-without-user-message.test.ts b/plugins/web-ui/test/resume-without-user-message.test.tsindex 8bf9b6ecc..3031013f7 100644--- a/plugins/web-ui/test/resume-without-user-message.test.ts+++ b/plugins/web-ui/test/resume-without-user-message.test.ts@@ -2,7 +2,7 @@ import { test } from "node:test";import assert from "node:assert/strict";import { readFileSync } from "node:fs";import type { AgentMessage } from "@earendil-works/pi-web-ui";-import { continuableMessages, resumeAnchor, runIsTerminal } from "../src/core-bridge.ts";+import { continuableMessages, entriesToMessages, resumeAnchor, runIsTerminal } from "../src/core-bridge.ts";const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");@@ -10,6 +10,60 @@ const assistant = (text: string): AgentMessage =>({ role: "assistant", content: [{ type: "text", text }] }) as unknown as AgentMessage;const user = (text: string): AgentMessage => ({ role: "user", content: text }) as unknown as AgentMessage;+test("approval continuation preserves the paused work without seeding its text into the new reply", () => {+ const history = entriesToMessages([+ { type: "user", seq: 0, createdAt: 10, payload: { text: "show help" } },+ { type: "text", seq: 1, createdAt: 11, payload: { text: "Checking help", phase: "commentary" } },+ { type: "tool_call", seq: 2, createdAt: 12, payload: { command: "help" } },+ { type: "tool_result", seq: 3, parentSeq: 2, createdAt: 13, payload: { blocked: "needs_approval" } },+ ]);+ const resumed = continuableMessages(history);+ assert.deepEqual(resumed.messages.slice(0, history.length), history);+ assert.deepEqual(resumed.popped, []);+ assert.deepEqual(resumed.messages.at(-1), resumeAnchor());+ const continuing = continuableMessages([...history, assistant("New continuation")]);+ assert.deepEqual(continuing.messages, resumed.messages);+ assert.deepEqual(continuing.popped, [assistant("New continuation")]);+});++test("a pending run restores its input without consuming the previous reply", () => {+ const earlier = [user("repeat"), assistant("Earlier answer")];+ const restored = continuableMessages(earlier, {+ runId: "pending",+ seq: null,+ text: "repeat",+ createdAt: 20,+ attachments: [{ name: "notes.txt", mimetype: "text/plain", sizeBytes: 50 }],+ });+ assert.deepEqual(restored.messages.slice(0, 2), earlier);+ assert.deepEqual(restored.popped, []);+ assert.deepEqual(restored.messages[2], {+ role: "user",+ runId: "pending",+ content: "repeat",+ timestamp: 20,+ attachments: [{ id: "pending:0", type: "document", fileName: "notes.txt", mimeType: "text/plain", size: 50 }],+ });+});++test("a recorded input wins over an older pending snapshot without text-based deduplication", () => {+ const messages = entriesToMessages([+ { type: "user", seq: 0, createdAt: 20, payload: { text: "original", runId: "run" } },+ { type: "text", seq: 1, createdAt: 21, payload: { text: "Working", phase: "commentary" } },+ { type: "user", seq: 2, createdAt: 22, payload: { text: "steer", runId: "run", steered: true } },+ ]);+ const resumed = continuableMessages(messages, { runId: "run", seq: null, text: "stale", createdAt: 19 });+ assert.equal(resumed.messages.length, 2);+ assert.equal(resumed.popped.length, 1);+ assert.equal((resumed.messages[0] as { content: unknown }).content, "original");+});++test("legacy run boundaries at sequence zero also identify the recorded input", () => {+ const messages = entriesToMessages([{ type: "user", seq: 0, createdAt: 20, payload: { text: "recorded" } }]);+ const resumed = continuableMessages(messages, { runId: "legacy", seq: 0, text: "request", createdAt: 19 });+ assert.deepEqual(resumed.messages, messages);+});+test("a window holding nothing the person said still yields a continuable conversation", () => {const { messages, popped } = continuableMessages([assistant("tool churn"), assistant("more churn")]);assert.equal(messages.length, 1);@@ -43,7 +97,10 @@ test("neither attach path refuses a live run over the shape of the loaded transcconst body = resume.slice(0, resume.indexOf("agent.streamFn = makeRunResumeStreamFn"));assert.doesNotMatch(body, /if \(!msgs\.length\) return false;/, "resume no longer bails on an anchorless window");assert.doesNotMatch(body, /if \(!agent\.state\.messages\.length\) return false;/, "nor on an empty one");- assert.match(body, /const \{ messages: msgs, popped \} = continuableMessages\(agent\.state\.messages\);/);+ assert.match(+ body,+ /const \{ messages: msgs, popped \} = continuableMessages\(agent\.state\.messages, initialRun\.input\);/,+ );const follow = chat.slice(chat.indexOf("async function followNextQueuedRun"));const followBody = follow.slice(0, follow.indexOf("agent.streamFn = makeRunResumeStreamFn"));diff --git a/plugins/web-ui/test/rtl-direction.test.ts b/plugins/web-ui/test/rtl-direction.test.tsindex 0f0bfa936..c000f89bc 100644--- a/plugins/web-ui/test/rtl-direction.test.ts+++ b/plugins/web-ui/test/rtl-direction.test.ts@@ -17,9 +17,9 @@ test("settled and streaming transcript blocks select direction from their contenassert.match(chat, /import \{ markdown \} from "\.\/message-markdown"/);assert.match(messageMarkdown,- /<qm-markdown\s+dir="auto"\s+\.content=\$\{escapeLoneDollars\(normalizePlainTextFences\(text\)\)\}/,+ /<qm-markdown\s+dir="auto"[^>]*?\.content=\$\{escapeLoneDollars\(normalizePlainTextFences\(text\)\)\}/,);- assert.match(chat, /\$\{markdown\(body\)\}/);+ assert.match(chat, /\$\{markdown\(body, isStreaming, /);assert.match(chat, /class="streaming-text \$\{isStreaming \? "live-stream" : ""\}" dir="auto"/);});diff --git a/plugins/web-ui/test/run-connection.test.ts b/plugins/web-ui/test/run-connection.test.tsindex 89d69c06c..d7dc252b4 100644--- a/plugins/web-ui/test/run-connection.test.ts+++ b/plugins/web-ui/test/run-connection.test.ts@@ -1,6 +1,16 @@import assert from "node:assert/strict";import { test, type TestContext } from "node:test";-import { makeRunResumeStreamFn } from "../src/core-bridge.ts";+import { Agent } from "@earendil-works/pi-agent-core";+import {+ continuableMessages,+ makeCoreStreamFn,+ makeRunResumeStreamFn,+ messagesWithStreaming,+ resumeAnchor,+ RUN_IDLE_MS,+ setClock,+ userSendMessage,+} from "../src/core-bridge.ts";import type { Api, Context, Model } from "@earendil-works/pi-ai";const model = { id: "m", api: "anthropic", provider: "anthropic" } as unknown as Model<Api>;@@ -8,6 +18,47 @@ const flush = async () => {for (let i = 0; i < 100; i++) await Promise.resolve();};+for (const withAttachments of [false, true]) {+ test(`a timed-out send reconnects to its original input${withAttachments ? " with attachments" : ""}`, async (t) => {+ let time = 0;+ setClock(() => time);+ t.after(() => setClock(() => Date.now()));+ const attachments = withAttachments+ ? [{ id: "notes", type: "document", fileName: "notes.txt", mimeType: "text/plain", size: 5, content: "bm90ZXM=" }]+ : undefined;+ const input = userSendMessage("Check my document", attachments);+ const agent = new Agent({ initialState: { model, messages: [input] } });+ t.mock.method(globalThis, "fetch", async (url: unknown) => {+ if (String(url).includes("/api/blobs")) return Response.json({ blobId: "notes-blob", sizeBytes: 5 });+ if (String(url).endsWith("/api/turn")) return Response.json({ status: "queued", runId: "r" });+ assert.equal((input as unknown as { runId?: string }).runId, "r");+ time = RUN_IDLE_MS + 1;+ return Response.json({ status: "running", result: null });+ });+ agent.streamFn = makeCoreStreamFn("web:u:reconnect", agent);+ await agent.continue();+ const failed = agent.state.messages.at(-1);+ assert.equal((failed as { stopReason?: string }).stopReason, "error");+ const resumed = continuableMessages(agent.state.messages, {+ runId: "r",+ seq: 10,+ text: "Check my document",+ createdAt: 1,+ });+ assert.deepEqual(resumed.messages, [input]);+ assert.deepEqual(resumed.popped, [failed]);+ assert.deepEqual((resumed.messages[0] as unknown as { attachments?: unknown[] }).attachments, attachments);+ agent.state.messages = resumed.messages;+ agent.streamFn = makeRunResumeStreamFn("r", { status: "done", result: { status: "ok", reply: "Done" } });+ await agent.continue();+ assert.equal(agent.state.messages.length, 2);+ assert.equal(agent.state.messages[0], input);+ const reply = agent.state.messages[1];+ assert.ok(reply?.role === "assistant");+ assert.deepEqual(reply.content, [{ type: "text", text: "Done" }]);+ });+}+function streamingFetch(t: TestContext) {const original = Object.getOwnPropertyDescriptor(globalThis, "window");Object.defineProperty(globalThis, "window", { configurable: true, value: {} });@@ -188,3 +239,52 @@ test("reply completion waits for final result metadata rather than dropping appr);assert.equal(state.polls, 0);});++test("approval activity reaches the visible transcript before any response text", async (t) => {+ const transport = streamingFetch(t);+ const agent = new Agent({ initialState: { model, messages: [resumeAnchor()] } });+ let projected: ReturnType<typeof messagesWithStreaming> = [];+ agent.streamFn = makeRunResumeStreamFn("r", undefined, () => {+ projected = messagesWithStreaming(agent.state.messages, agent.state.streamingMessage);+ });+ const completion = agent.continue();+ await flush();+ transport.send({+ type: "CUSTOM",+ name: "run",+ value: {+ status: "running",+ result: null,+ activity: [+ {+ seq: 57,+ parentSeq: null,+ type: "approval_resolved",+ payload: { requestId: "a", command: "help", approved: true, scope: "once" },+ createdAt: 100,+ },+ ],+ },+ });+ await flush();+ const beforeCompletion = projected.map((message) => (message as { role: string }).role);+ transport.send({+ type: "CUSTOM",+ name: "run",+ value: {+ status: "done",+ result: { status: "ok", reply: "Done" },+ activity: [+ {+ seq: 57,+ parentSeq: null,+ type: "approval_resolved",+ payload: { requestId: "a", command: "help", approved: true, scope: "once" },+ createdAt: 100,+ },+ ],+ },+ });+ await completion;+ assert.ok(beforeCompletion.includes("approval-decision"), JSON.stringify(beforeCompletion));+});diff --git a/plugins/web-ui/test/stable-markdown.test.ts b/plugins/web-ui/test/stable-markdown.test.tsindex 82a1bc407..0feba0ecc 100644--- a/plugins/web-ui/test/stable-markdown.test.ts+++ b/plugins/web-ui/test/stable-markdown.test.ts@@ -23,12 +23,61 @@ installMarkdownSanitizer();async function mount(content: string): Promise<InstanceType<typeof StableMarkdown>> {const block = new StableMarkdown();+ let layout: Promise<void> | undefined;+ block.addEventListener(+ "qm-content-updating",+ (event) => {+ layout = (event as CustomEvent<Promise<void>>).detail;+ },+ { once: true },+ );document.body.append(block);block.content = content;await block.updateComplete;+ await layout;return block;}+test("rendering works without a global Element constructor", async () => {+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "Element")!;+ Reflect.deleteProperty(globalThis, "Element");+ try {+ const block = await mount("A **formatted** reply");+ assert.equal(block.querySelector("strong")?.textContent, "formatted");+ block.content += " with more text";+ await block.updateComplete;+ assert.match(block.textContent!, /with more text/);+ block.remove();+ } finally {+ Object.defineProperty(globalThis, "Element", descriptor);+ }+});++test("a failed render releases its layout notification and can render again", async (t) => {+ const block = await mount("Before");+ let completed = false;+ block.addEventListener("qm-content-updating", (event) => {+ void (event as CustomEvent<Promise<void>>).detail.then(() => {+ completed = true;+ });+ });+ const render = t.mock.method(block, "querySelectorAll", () => {+ throw new Error("render failed");+ });+ try {+ assert.throws(() => Reflect.get(block, "update").call(block, new Map()), /render failed/);+ await Promise.resolve();+ assert.equal(completed, true);+ render.mock.restore();+ block.content = "After";+ await block.updateComplete;+ assert.equal(block.textContent?.trim(), "After");+ } finally {+ render.mock.restore();+ block.remove();+ }+});+test("appending text preserves existing paragraphs, formatted nodes and selection", async () => {const block = await mount("A **stable phrase** followed by text");const paragraph = block.querySelector("p")!;@@ -99,3 +148,365 @@ test("selection inside a growing text node survives append-only updates", asyncassert.equal(selection.toString(), "growing");assert.equal(el.querySelector("p")!.firstChild, text);});++test("live chunks fade only new text and keep earlier animations and selected text", async () => {+ const block = await mount("Existing paragraph");+ const original = block.querySelector("p")!.firstChild!;+ const selection = window.getSelection()!;+ selection.setBaseAndExtent(original, 0, original, 8);+ block.isStreaming = true;+ block.content += " first chunk";+ await block.updateComplete;+ const first = block.querySelector(".tok-in")!;+ assert.equal(first.textContent, " first chunk");+ assert.equal(selection.toString(), "Existing");+ block.content += " second chunk\n\n**New paragraph**";+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), first);+ assert.deepEqual(+ [...block.querySelectorAll(".tok-in")].map((span) => span.textContent),+ [" first chunk", " second chunk", "New paragraph"],+ );+ assert.equal(block.querySelector("p")!.firstChild, original);+ assert.equal(selection.toString(), "Existing");+ block.remove();+});++test("fade cleanup preserves selection inside incoming text and leaves copy text intact", async () => {+ const block = await mount("Before");+ block.isStreaming = true;+ block.content += " incoming words";+ await block.updateComplete;+ const span = block.querySelector(".tok-in")!;+ const text = span.firstChild!;+ const selection = window.getSelection()!;+ selection.setBaseAndExtent(text, 1, text, 9);+ span.dispatchEvent(new dom.window.Event("animationend"));+ assert.equal(block.querySelector(".tok-in"), null);+ assert.equal(selection.toString(), "incoming");+ assert.equal(block.querySelector("p")!.textContent, "Before incoming words");+ block.remove();+});++test("history, stream completion, disconnect and rewritten content do not replay fades", async () => {+ const block = await mount("History text");+ assert.equal(block.querySelector(".tok-in"), null);+ block.isStreaming = true;+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ block.content += " appended";+ await block.updateComplete;+ assert.ok(block.querySelector(".tok-in"));+ block.isStreaming = false;+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ block.isStreaming = true;+ block.content = "Entirely different **replacement**";+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ block.content += " live suffix";+ await block.updateComplete;+ assert.ok(block.querySelector(".tok-in"));+ block.remove();+ assert.equal(block.querySelector(".tok-in"), null);+ document.body.append(block);+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ block.remove();+});++test("reduced motion shows incoming text immediately", async () => {+ Object.defineProperty(window, "matchMedia", { configurable: true, value: () => ({ matches: true }) });+ const block = await mount("Before");+ block.isStreaming = true;+ block.content += " after";+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ assert.equal(block.querySelector("p")!.textContent, "Before after");+ block.remove();+ Reflect.deleteProperty(window, "matchMedia");+});++test("live markdown formatting and unsafe input retain sanitizer and custom code ownership", async () => {+ const block = await mount("Introduction");+ block.isStreaming = true;+ block.content += "\n\n```js\nlet x = 1;\n```\n\n[unsafe](javascript:alert(1))\n\n<img src=x onerror=alert(1)>";+ await block.updateComplete;+ const code = block.querySelector("code-block")!;+ assert.ok(code);+ assert.equal(code.querySelector(".tok-in"), null);+ assert.equal(block.querySelector("img"), null);+ assert.equal(block.querySelector('[href^="javascript:"]'), null);+ block.content += "\n\nTail";+ await block.updateComplete;+ assert.equal(block.querySelector("code-block"), code);+ block.remove();+});++test("hydrated streaming text is immediately visible and only later appended text fades", async () => {+ const block = new StableMarkdown();+ block.isStreaming = true;+ block.streamingBaseline = "Already **read** this paragraph";+ block.content = block.streamingBaseline;+ document.body.append(block);+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in"), null);+ const strong = block.querySelector("strong");+ block.content += " and now new words";+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in")?.textContent, " and now new words");+ assert.equal(block.querySelector("strong"), strong);+ block.remove();+});++test("a snapshot and new tokens in the first render fade only beyond the hydration baseline", async () => {+ const block = new StableMarkdown();+ block.isStreaming = true;+ block.streamingBaseline = "Existing **formatted** text";+ block.content = block.streamingBaseline + " fresh suffix";+ document.body.append(block);+ await block.updateComplete;+ assert.deepEqual(+ [...block.querySelectorAll(".tok-in")].map((span) => span.textContent),+ [" fresh suffix"],+ );+ block.remove();+});++test("a genuinely new first response chunk still fades without a hydration baseline", async () => {+ const block = new StableMarkdown();+ block.isStreaming = true;+ block.content = "First response";+ document.body.append(block);+ await block.updateComplete;+ assert.equal(block.querySelector(".tok-in")?.textContent, "First response");+ block.remove();+});++test("finished fade text stays mounted across append and completion", async () => {+ const block = await mount("Before");+ block.isStreaming = true;+ block.content += " incoming";+ await block.updateComplete;+ const span = block.querySelector(".tok-in")!;+ const text = span.firstChild!;+ const selection = window.getSelection()!;+ selection.setBaseAndExtent(text, 1, text, 5);+ span.dispatchEvent(new dom.window.Event("animationend"));+ assert.equal(text.parentNode, span);+ assert.ok(span.isConnected);+ assert.equal(selection.toString(), "inco");+ block.content += " more";+ await block.updateComplete;+ assert.equal(span.firstChild, text);+ assert.ok(span.isConnected);+ block.isStreaming = false;+ await block.updateComplete;+ assert.equal(span.firstChild, text);+ assert.ok(span.isConnected);+ assert.equal(selection.toString(), "inco");+ block.remove();+});++test("whitespace chunks preserve text offsets and settled spans", async () => {+ const block = await mount("One");+ block.isStreaming = true;+ let first: Element | null = null;+ for (const chunk of [" ", "two", " ", "three", " and **four**", " five"]) {+ block.content += chunk;+ await block.updateComplete;+ first ??= block.querySelector(".stream-chunk");+ if (first) assert.ok(first.isConnected);+ for (const span of block.querySelectorAll(".tok-in")) span.dispatchEvent(new dom.window.Event("animationend"));+ }+ assert.equal(block.querySelector("p")?.textContent, "One two three and four five");+ block.remove();+});++test("Markdown updates announce their synchronous DOM mutation boundary", async () => {+ const block = await mount("Before");+ const observed: string[] = [];+ const before = () => observed.push(`before:${block.textContent?.trim()}`);+ const after = () => observed.push(`after:${block.textContent?.trim()}`);+ document.body.addEventListener("qm-content-updating", before);+ document.body.addEventListener("qm-content-updated", after);+ try {+ block.content = "After";+ await block.updateComplete;+ assert.deepEqual(observed, ["before:Before", "after:After"]);+ } finally {+ document.body.removeEventListener("qm-content-updating", before);+ document.body.removeEventListener("qm-content-updated", after);+ block.remove();+ }+});++test("Markdown completes its layout boundary after nested code finishes rendering", async () => {+ const block = await mount("```ts\nconst before = 1;\n```");+ const code = block.querySelector("code-block") as HTMLElement & { updateComplete: Promise<unknown> };+ await code.updateComplete;+ await Promise.resolve();+ const observed: string[] = [];+ const done = Promise.withResolvers<void>();+ const after = () => {+ observed.push(code.textContent ?? "");+ done.resolve();+ };+ block.addEventListener("qm-content-updated", after);+ try {+ block.content = "```ts\nconst after = 2;\n```";+ await block.updateComplete;+ await done.promise;+ assert.ok(observed.length >= 1);+ assert.match(observed.at(-1)!, /const after = 2;/);+ } finally {+ block.removeEventListener("qm-content-updated", after);+ block.remove();+ }+});++for (const fence of ["```", "~~~", "````"]) {+ test(`streaming ${fence} fences retain raw code characters before and after closure`, async () => {+ const source = 'type Item<T> = { value: T };\nconst html = "<img src=x onerror=alert(1)> <literal>";';+ const block = await mount(`${fence}typescript\n${source}`);+ const code = block.querySelector("code-block") as HTMLElement & {+ getDecodedCode(): string;+ updateComplete: Promise<unknown>;+ };+ assert.ok(code);+ assert.equal(code.getDecodedCode(), `${source}\n`);+ assert.equal(block.querySelector("img"), null);+ block.content += `\n${fence}`;+ await block.updateComplete;+ await code.updateComplete;+ assert.equal(block.querySelector("code-block"), code);+ assert.equal(code.getDecodedCode(), `${source}\n`);+ block.remove();+ });+}++test("a streamed table never exposes its incomplete header or separator as raw text", async () => {+ const block = await mount("Before\n\n");+ block.isStreaming = true;+ const header = "| Command | Output |\n| --- | --- |";+ for (let length = 1; length <= header.length; length++) {+ block.content = `Before\n\n${header.slice(0, length)}`;+ await block.updateComplete;+ assert.doesNotMatch(block.textContent ?? "", /\|/, `prefix ${length}`);+ }+ assert.deepEqual(+ [...block.querySelectorAll("th")].map((cell) => cell.textContent),+ ["Command", "Output"],+ );+ const table = block.querySelector("table");+ block.content += "\n| alpha | a";+ await block.updateComplete;+ assert.equal(block.querySelector("table"), table);+ assert.deepEqual(+ [...block.querySelectorAll("td")].map((cell) => cell.textContent),+ ["alpha", "a"],+ );+ block.remove();+});++for (const [prefix, linePrefix] of [+ ["Before\n\n", ""],+ ["> Before\n>\n", "> "],+ ["- Before\n\n", " "],+] as const) {+ test(`incomplete tables preserve preceding content inside ${JSON.stringify(linePrefix)}`, async () => {+ const block = await mount(prefix);+ block.isStreaming = true;+ const source = `${linePrefix}| A | B |\n${linePrefix}| --- | --- |`;+ for (let length = 1; length <= source.length; length++) {+ block.content = prefix + source.slice(0, length);+ await block.updateComplete;+ assert.match(block.textContent ?? "", /Before/);+ assert.doesNotMatch(block.textContent ?? "", /\|/, `prefix ${length}`);+ }+ assert.equal(block.querySelectorAll("th").length, 2);+ block.remove();+ });+}++test("alignment markers and borderless table headers settle without raw separators", async () => {+ const block = await mount("");+ block.isStreaming = true;+ const source = "**Left** | Right\r\n:--- | ---:";+ for (let length = 1; length <= source.length; length++) {+ block.content = source.slice(0, length);+ await block.updateComplete;+ assert.doesNotMatch(block.textContent ?? "", /\||---/, `prefix ${length}`);+ }+ assert.deepEqual(+ [...block.querySelectorAll("th")].map((cell) => cell.textContent),+ ["Left", "Right"],+ );+ assert.equal(block.content, source);+ block.remove();+});++test("pipe prose resumes unchanged when a following line rules out a table", async () => {+ const block = await mount("Before\n\n");+ block.isStreaming = true;+ block.content = "Before\n\nA | B";+ await block.updateComplete;+ block.content += "\nThis is ordinary prose.";+ await block.updateComplete;+ assert.match(block.textContent ?? "", /A \| B\s+This is ordinary prose\./);+ assert.equal(block.querySelector("table"), null);+ block.remove();+});++for (const [source, ending] of [+ ["Before\n\nA | B", "\n\n"],+ ["Before\r\n\r\nA | B", "\r\n \t\r\n"],+ ["> Before\n>\n> A | B", "\n>\n> "],+ ["- Before\n\n A | B", "\n \n "],+] as const) {+ test(`a completed pipe paragraph becomes visible before streaming ends: ${JSON.stringify(ending)}`, async () => {+ const block = await mount("");+ block.isStreaming = true;+ block.content = source;+ await block.updateComplete;+ assert.doesNotMatch(block.textContent ?? "", /A \| B/);+ block.content += ending;+ await block.updateComplete;+ assert.match(block.textContent ?? "", /A \| B/);+ assert.equal(block.querySelector("table"), null);+ assert.equal(block.isStreaming, true);+ block.remove();+ });+}++test("literal pipe text is restored when streaming ends and code pipes stay visible", async () => {+ const block = await mount("Before\n\n");+ block.isStreaming = true;+ block.content = "Before\n\n| literal pipe text";+ await block.updateComplete;+ assert.equal(block.textContent?.trim(), "Before");+ block.isStreaming = false;+ await block.updateComplete;+ assert.match(block.textContent ?? "", /\| literal pipe text/);+ block.isStreaming = true;+ for (const content of ["Use `a | b`", "Use a \\| b", "```text\n| A | B |\n|---|"]) {+ block.content = content;+ await block.updateComplete;+ const code = block.querySelector("code-block") as (HTMLElement & { updateComplete: Promise<unknown> }) | null;+ await code?.updateComplete;+ assert.match(block.textContent ?? "", /\|/);+ }+ block.remove();+});++test("literal HTML remains inert while code and autolinks retain Markdown semantics", async () => {+ const block = await mount(+ "<script>alert(1)</script>\n\nA <strong>literal</strong> tag, ``<T> `code` <literal>``, and <https://example.test/>.",+ );+ assert.equal(block.querySelector("script, strong"), null);+ assert.match(block.textContent!, /<script>alert\(1\)<\/script>/);+ assert.match(block.textContent!, /<strong>literal<\/strong>/);+ assert.equal(block.querySelector("code")?.textContent, "<T> `code` <literal>");+ assert.equal(block.querySelector("a")?.href, "https://example.test/");+ block.remove();+});diff --git a/plugins/web-ui/test/stop-confirmation.test.ts b/plugins/web-ui/test/stop-confirmation.test.tsindex 08f8f0529..d23230459 100644--- a/plugins/web-ui/test/stop-confirmation.test.ts+++ b/plugins/web-ui/test/stop-confirmation.test.ts@@ -1,3 +1,4 @@+import { streamingTextTail } from "../src/timeline.ts";import { test, afterEach } from "node:test";import assert from "node:assert/strict";import { setTimeout as sleep } from "node:timers/promises";@@ -110,3 +111,46 @@ test("a stalled stop acknowledgment cannot delay confirmation or report a late eassert.equal(first?.stopReason, "aborted");assert.deepEqual(errors, []);});++test("the authoritative final answer replaces longer accumulated commentary", async () => {+ const commentary = "I will check this carefully.\n\nI will check this carefully.";+ const fn = makeRunResumeStreamFn("finished", {+ status: "done",+ partial: commentary + "\n\nOK",+ result: { status: "ok", reply: "OK" },+ activity: [+ { seq: 1, type: "text", payload: { text: "I will check this carefully." }, createdAt: 1 },+ { seq: 2, type: "text", payload: { text: "I will check this carefully." }, createdAt: 2 },+ ],+ });+ const stream = await fn(model, {} as Context, {});+ const final = (await stream.result()) as AssistantWork;+ assert.deepEqual(final.content, [{ type: "text", text: "OK" }]);+ assert.equal(final.work?.activity.length, 2);+});++test("a failure after commentary preserves only unfinished text outside its work fold", async () => {+ const fn = makeRunResumeStreamFn("failed", {+ status: "failed",+ partial: "Checking.\n\nUnfinished",+ result: { status: "failed", reason: "provider failed" },+ activity: [{ seq: 1, type: "text", payload: { text: "Checking.", phase: "commentary" }, createdAt: 1 }],+ });+ const stream = await fn(model, {} as Context, {});+ const final = (await stream.result()) as AssistantWork;+ assert.equal(final.stopReason, "error");+ const text = final.content[0];+ assert.equal(streamingTextTail(text?.type === "text" ? text.text : "", final.work!.activity), "Unfinished");+});++test("resume carries already visible text as its streaming animation baseline", async () => {+ const fn = makeRunResumeStreamFn(+ "resumed",+ { status: "done", partial: "Existing reply", result: { status: "ok", reply: "Existing reply and new text" } },+ undefined,+ undefined,+ "Existing",+ );+ const stream = await fn(model, {} as Context, {});+ assert.equal(((await stream.result()) as AssistantWork).streamingBaseline, "Existing reply");+});diff --git a/plugins/web-ui/test/timeline.test.ts b/plugins/web-ui/test/timeline.test.tsindex df88bcd8f..ec11da69a 100644--- a/plugins/web-ui/test/timeline.test.ts+++ b/plugins/web-ui/test/timeline.test.ts@@ -1,7 +1,17 @@import { test } from "node:test";import assert from "node:assert/strict";import type { ToolActivity, WorkBlock } from "../src/core-bridge.ts";-import { buildTimeline, toolCategory, toolRowKind, toolExecutionOutput, type ToolRowModel } from "../src/timeline.ts";+import {+ messageWorkTimeline,+ currentTextPhase,+ streamedAnswer,+ streamingTextTail,+ buildTimeline,+ toolCategory,+ toolRowKind,+ toolExecutionOutput,+ type ToolRowModel,+} from "../src/timeline.ts";function act(seq: number, type: ToolActivity["type"], payload: unknown): ToolActivity {return { seq, parentSeq: null, type, payload, createdAt: seq };@@ -369,3 +379,88 @@ test("unscreened execution retains its warning and failure status without parsin"failed",);});++test("recorded narration is consumed once per occurrence while the next block streams", () => {+ const text = "Checking.";+ const activity = [act(1, "text", { text }), act(2, "tool_call", { tool: "lookup" })];+ assert.equal(streamingTextTail(text + "\n\n" + text, activity), text);+ activity.push(act(3, "tool_result", { tool: "lookup" }), act(4, "text", { text }));+ assert.equal(streamingTextTail(text + "\n\n" + text + "\n\nFinal", activity), "Final");+ assert.equal(streamingTextTail("Check", activity), "");+ assert.equal(streamingTextTail("Different reply", activity), "Different reply");+ assert.equal(streamingTextTail(" indented code", []), " indented code");+});++test("one work timeline includes initial and repeated narration but excludes the authoritative final occurrence", () => {+ const activity = [+ act(1, "text", { text: "Same" }),+ act(2, "tool_call", { tool: "lookup", callId: "a" }),+ act(3, "text", { text: "Same" }),+ act(4, "tool_result", { tool: "lookup", callId: "a" }),+ act(5, "text", { text: "Same" }),+ ];+ const work: WorkBlock = { status: "complete", activity };+ const items = messageWorkTimeline(work, "Same");+ assert.deepEqual(+ items.map((item) => item.kind),+ ["text", "tool", "text"],+ );+ assert.equal(activity.length, 5);+ assert.equal(messageWorkTimeline({ ...work, status: "working" }, "").length, 4);+});++test("work projection omits empty and redacted thinking without changing parallel tool pairing", () => {+ const work: WorkBlock = {+ status: "failed",+ activity: [+ act(1, "thinking", { redacted: true, thinking: "secret" }),+ act(2, "thinking", { thinking: " " }),+ act(3, "tool_call", { tool: "a", callId: "a" }),+ act(4, "tool_call", { tool: "b", callId: "b" }),+ act(5, "tool_result", { callId: "b" }),+ act(6, "tool_result", { callId: "a" }),+ ],+ };+ const items = messageWorkTimeline(work, "");+ assert.deepEqual(+ items.map((item) => item.kind),+ ["tool", "tool"],+ );+ assert.equal(items[0]?.kind === "tool" && items[0].row.result?.seq, 6);+ assert.equal(items[1]?.kind === "tool" && items[1].row.result?.seq, 5);+});++test("explicit commentary remains folded even when the final answer repeats it", () => {+ const activity = [act(1, "text", { text: "Same", phase: "commentary" })];+ assert.equal(messageWorkTimeline({ status: "complete", activity }, "Same").length, 1);+});++test("explicit public phases use offsets and never appear as tool rows", () => {+ const work: WorkBlock = {+ status: "working",+ activity: [+ act(1, "text", { text: "Same words", phase: "commentary" }),+ act(2, "text_start", { phase: "final_answer", streamOffset: 12 }),+ ],+ };+ assert.deepEqual(currentTextPhase(work), { phase: "final_answer", streamOffset: 12, startedAt: 2 });+ assert.deepEqual(+ buildTimeline(work).map((item) => item.kind),+ ["text"],+ );+ work.activity.push(act(3, "text_start", { phase: "commentary", streamOffset: 24 }));+ assert.equal(currentTextPhase(work)?.phase, "commentary");+ work.activity.push(act(4, "text_start", { phase: "final_answer", streamOffset: -1 }));+ assert.equal(currentTextPhase(work), null);+});++test("stopped stream projection uses the final boundary even when final text repeats commentary", () => {+ const work: WorkBlock = {+ status: "working",+ activity: [+ act(1, "text", { text: "Same words", phase: "commentary" }),+ act(2, "text_start", { phase: "final_answer", streamOffset: 12 }),+ ],+ };+ assert.equal(streamedAnswer("Same words\n\nSame words again", work), "Same words again");+});diff --git a/plugins/web-ui/test/transcript-viewport.test.ts b/plugins/web-ui/test/transcript-viewport.test.tsindex 0300ba286..700c474e4 100644--- a/plugins/web-ui/test/transcript-viewport.test.ts+++ b/plugins/web-ui/test/transcript-viewport.test.ts@@ -24,7 +24,54 @@ test("stream following never uses smooth scrolling or a near-bottom zone", () =>});import { JSDOM } from "jsdom";-import { createTranscriptViewport } from "../src/transcript-viewport.ts";+import { createTranscriptViewport, preserveTranscriptScroll } from "../src/transcript-viewport.ts";++test("layout mutations preserve bottom following and an earlier reading anchor independently", () => {+ const dom = new JSDOM(+ '<main><section class="chat-scroll"><div class="message-stack"><p>Reading here</p></div></section><section class="chat-scroll"></section></main>',+ );+ const root = dom.window.document.querySelector("main")!;+ const [reading, following] = [...root.querySelectorAll<HTMLElement>("section")];+ const anchor = reading!.querySelector("p")!;+ let height = 1000;+ let anchorTop = 330;+ for (const element of [reading!, following!]) {+ Object.defineProperties(element, { clientHeight: { value: 200 }, scrollHeight: { get: () => height } });+ element.getBoundingClientRect = () => ({ top: 20 }) as DOMRect;+ }+ anchor.getBoundingClientRect = () =>+ ({ top: 20 + anchorTop - reading!.scrollTop, bottom: 100 + anchorTop - reading!.scrollTop }) as DOMRect;+ reading!.scrollTop = 350;+ following!.scrollTop = 800;+ const restore = preserveTranscriptScroll(root);+ reading!.scrollTop = following!.scrollTop = 0;+ anchorTop += 120;+ height += 300;+ restore();+ assert.equal(reading!.scrollTop, 470);+ assert.equal(following!.scrollTop, 1300);+ assert.equal(anchor.getBoundingClientRect().top, 0);+});++test("layout restoration ignores removed panes and falls back when an anchor was replaced", () => {+ const dom = new JSDOM(+ '<main><section class="chat-scroll"><div class="message-stack"><p>Reading</p></div></section><section class="chat-scroll"></section></main>',+ );+ const root = dom.window.document.querySelector("main")!;+ const [reading, removed] = [...root.querySelectorAll<HTMLElement>("section")];+ for (const element of [reading!, removed!]) {+ Object.defineProperties(element, { clientHeight: { value: 200 }, scrollHeight: { value: 1000 } });+ element.scrollTop = 350;+ }+ reading!.querySelector("p")!.getBoundingClientRect = () => ({ top: 10, bottom: 50 }) as DOMRect;+ const restore = preserveTranscriptScroll(root);+ reading!.replaceChildren();+ removed!.remove();+ reading!.scrollTop = removed!.scrollTop = 0;+ restore();+ assert.equal(reading!.scrollTop, 350);+ assert.equal(removed!.scrollTop, 0);+});function fixture() {const dom = new JSDOM(@@ -94,6 +141,10 @@ function fixture() {s.dispatchEvent(new dom.window.Event("scroll"));writes.length = 0;},+ collapse: () => {+ height = 400;+ s.scrollTop = Math.min(s.scrollTop, 200);+ },grow: () => {height += 100;},@@ -324,7 +375,7 @@ test("prompt expansion control belongs inside the bubble in both renderers", ()dom.window.close();}}- assert.match(css, /:not\(\.pin-expanded\):not\(\.pin-fits\)\s+\.user-bubble\s+>\s+\.pin-content \{/);+ assert.match(css, /:not\(\.pin-expanded\)\s+\.user-bubble\s+>\s+\.pin-content \{/);assert.match(css, /\.user-bubble > \.pin-toggle:not\(\[hidden\]\)/);});@@ -360,7 +411,7 @@ test("plain-text copy confirmation can grow beyond its icon width", () => {assert.doesNotMatch(rule, /(?:^|[;{])\s*width:/);});-test("marginal overflow is shown in full without an expansion control", () => {+test("prompt clipping tolerates rounding but discloses any additional text line", () => {const f = fixture();try {f.prompt.innerHTML =@@ -370,18 +421,16 @@ test("marginal overflow is shown in full without an expansion control", () => {let overflow = 5;Object.defineProperties(content, {scrollHeight: { get: () => 160 + overflow },- clientHeight: { get: () => (f.prompt.classList.contains("pin-fits") ? 160 + overflow : 160) },+ clientHeight: { value: 160 },});f.viewport.sync(f.s);- for (overflow of [0, 5, 24, 25, 100, 5]) {+ for (overflow of [0, 1, 2, 23, 100, 1]) {f.resize(30, 50);- assert.equal(toggle.hidden, overflow <= 24);- assert.equal(f.prompt.classList.contains("pin-fits"), overflow <= 24);+ assert.equal(toggle.hidden, overflow <= 1);f.resize(30, 50);- assert.equal(toggle.hidden, overflow <= 24, "stable on repeated measurements");+ assert.equal(toggle.hidden, overflow <= 1, "stable on repeated measurements");}f.viewport.dispose();- assert.equal(f.prompt.classList.contains("pin-fits"), false);} finally {f.close();}@@ -599,3 +648,228 @@ for (const type of ["pointerdown", "keydown"]) {}});}++test("closing live work preserves following through delayed final markdown layout", () => {+ const f = fixture();+ try {+ f.viewport.beforeRender();+ f.viewport.follow();+ f.collapse();+ f.viewport.afterRender();+ f.grow();+ f.resize(30, 50);+ f.flush();+ assert.equal(f.s.scrollTop, 300);+ f.grow();+ f.resize(30, 50);+ f.flush();+ assert.equal(f.s.scrollTop, 400);+ } finally {+ f.close();+ }+});++test("a reader who left the bottom is not pulled back when work closes", () => {+ const f = fixture();+ try {+ f.scroll(100);+ f.viewport.beforeRender();+ f.collapse();+ f.viewport.afterRender();+ f.grow();+ f.resize(30, 50);+ f.flush();+ assert.equal(f.s.scrollTop, 100);+ } finally {+ f.close();+ }+});++test("upward input after work closes still cancels the queued follow", () => {+ const f = fixture();+ try {+ f.viewport.beforeRender();+ f.collapse();+ f.viewport.afterRender();+ f.wheelUp();+ f.scroll(190);+ f.grow();+ f.resize(30, 50);+ f.flush();+ assert.equal(f.s.scrollTop, 190);+ } finally {+ f.close();+ }+});++test("an explicit new send re-arms following after reading older messages", () => {+ const f = fixture();+ try {+ f.scroll(100);+ f.viewport.follow(true);+ f.grow();+ f.flush();+ assert.equal(f.s.scrollTop, 900);+ f.scroll(500);+ f.grow();+ f.viewport.follow();+ f.flush();+ assert.equal(f.s.scrollTop, 500);+ } finally {+ f.close();+ }+});++for (const reading of [false, true]) {+ test(`asynchronous Markdown replacement preserves ${reading ? "reader position" : "following"}`, async () => {+ const f = fixture();+ try {+ if (reading) f.scroll(100);+ f.viewport.beforeRender();+ f.viewport.afterRender();+ const completion = Promise.withResolvers<void>();+ f.prompt.dispatchEvent(+ new f.s.ownerDocument.defaultView!.CustomEvent("qm-content-updating", {+ bubbles: true,+ detail: completion.promise,+ }),+ );+ f.collapse();+ completion.resolve();+ await completion.promise;+ f.grow();+ f.resize(30, 50);+ f.flush();+ assert.equal(f.s.scrollTop, reading ? 100 : 300);+ } finally {+ f.close();+ }+ });+}++test("an in-flight Markdown layout cannot be mistaken for reader scrolling", async () => {+ const f = fixture();+ try {+ const completion = Promise.withResolvers<void>();+ f.prompt.dispatchEvent(+ new f.s.ownerDocument.defaultView!.CustomEvent("qm-content-updating", {+ bubbles: true,+ detail: completion.promise,+ }),+ );+ f.s.scrollTop = 787;+ f.viewport.beforeRender();+ f.grow();+ completion.resolve();+ await completion.promise;+ f.flush();+ assert.equal(f.s.scrollTop, 900);+ } finally {+ f.close();+ }+});++test("following waits for every overlapping render, including rejected updates", async () => {+ const f = fixture();+ try {+ const first = Promise.withResolvers<void>();+ const second = Promise.withResolvers<void>();+ for (const completion of [first, second]) {+ f.prompt.dispatchEvent(+ new f.s.ownerDocument.defaultView!.CustomEvent("qm-content-updating", {+ bubbles: true,+ detail: completion.promise,+ }),+ );+ }+ f.grow();+ first.reject(new Error("render failed"));+ await first.promise.catch(() => {});+ f.flush();+ assert.equal(f.s.scrollTop, 800);+ second.resolve();+ await second.promise;+ f.flush();+ assert.equal(f.s.scrollTop, 900);+ } finally {+ f.close();+ }+});++test("a disposed render cannot release a new render on the same scroller", async () => {+ const f = fixture();+ try {+ const start = () => {+ const completion = Promise.withResolvers<void>();+ f.prompt.dispatchEvent(+ new f.s.ownerDocument.defaultView!.CustomEvent("qm-content-updating", {+ bubbles: true,+ detail: completion.promise,+ }),+ );+ return completion;+ };+ const old = start();+ f.viewport.dispose();+ f.viewport.sync(f.s);+ f.viewport.follow(true);+ f.flush();+ const current = start();+ f.grow();+ old.resolve();+ await old.promise;+ f.flush();+ assert.equal(f.s.scrollTop, 800);+ current.resolve();+ await current.promise;+ f.flush();+ assert.equal(f.s.scrollTop, 900);+ } finally {+ f.close();+ }+});++test("End on the transcript resumes following even when layout grows before scrolling", () => {+ const f = fixture();+ try {+ f.scroll(200);+ const event = new f.s.ownerDocument.defaultView!.KeyboardEvent("keydown", {+ key: "End",+ bubbles: true,+ cancelable: true,+ });+ f.s.dispatchEvent(event);+ assert.equal(event.defaultPrevented, true);+ f.grow();+ f.flush();+ assert.equal(f.s.scrollTop, 900);+ f.grow();+ f.viewport.follow();+ f.flush();+ assert.equal(f.s.scrollTop, 1000);+ } finally {+ f.close();+ }+});++test("End inside a nested control retains the control's native behavior", () => {+ const f = fixture();+ try {+ f.scroll(200);+ const input = f.s.ownerDocument.createElement("textarea");+ f.s.append(input);+ const event = new f.s.ownerDocument.defaultView!.KeyboardEvent("keydown", {+ key: "End",+ bubbles: true,+ cancelable: true,+ });+ input.dispatchEvent(event);+ assert.equal(event.defaultPrevented, false);+ f.grow();+ f.viewport.follow();+ f.flush();+ assert.equal(f.s.scrollTop, 200);+ } finally {+ f.close();+ }+});diff --git a/plugins/web-ui/test/user-message-cap.test.ts b/plugins/web-ui/test/user-message-cap.test.tsindex 6ce0b5d67..0e17d0e4e 100644--- a/plugins/web-ui/test/user-message-cap.test.ts+++ b/plugins/web-ui/test/user-message-cap.test.ts@@ -6,14 +6,14 @@ const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");const shared = readFileSync(new URL("../src/shared-session.ts", import.meta.url), "utf8");-const pinned = String.raw`\.message-stack\s+\.user-row:not\(:has\(~ \.user-row\)\):not\(\.pin-expanded\):not\(\.pin-fits\)\s+\.user-bubble\s+>\s+\.pin-content`;+const pinned = String.raw`\.message-stack\s+\.user-row:not\(:has\(~ \.user-row\)\):not\(\.pin-expanded\)\s+\.user-bubble\s+>\s+\.pin-content`;test("only the collapsed pinned prompt is capped and overflow clips instead of nesting scrollbars", () => {const bubble =css.match(- /\.message-stack\s+\.user-row:not\(:has\(~ \.user-row\)\):not\(\.pin-expanded\):not\(\.pin-fits\)\s+\.user-bubble\s+>\s+\.pin-content \{[^}]*\}/,+ /\.message-stack\s+\.user-row:not\(:has\(~ \.user-row\)\):not\(\.pin-expanded\)\s+\.user-bubble\s+>\s+\.pin-content \{[^}]*\}/,)?.[0] ?? "";- assert.match(bubble, /max-height: var\(--pin-clamp, 320px\);/);+ assert.match(bubble, /max-height: 2lh;/);assert.match(bubble, /overflow: hidden;/);assert.doesNotMatch(css, /\.user-bubble > (?:markdown-block|\.slack-wire-text)\s*\{/);const base = css.match(/\n\.user-bubble \{[^}]*\}/)?.[0] ?? "";diff --git a/plugins/web-ui/test/work-duration-reconciliation.test.ts b/plugins/web-ui/test/work-duration-reconciliation.test.tsindex d6295275b..120ac9220 100644--- a/plugins/web-ui/test/work-duration-reconciliation.test.ts+++ b/plugins/web-ui/test/work-duration-reconciliation.test.ts@@ -8,6 +8,54 @@ const MODEL = { id: "m", api: "anthropic", provider: "anthropic" } as unknown astypeof entriesToMessages>[1];+test("waiting for an approval decision does not count as active work", () => {+ const activity: WorkBlock["activity"] = [+ { seq: 1, parentSeq: null, type: "tool_call", payload: { command: "help" }, createdAt: 101_000 },+ { seq: 2, parentSeq: 1, type: "tool_result", payload: { blocked: "needs_approval" }, createdAt: 108_000 },+ ];+ assert.equal(workSeconds({ status: "working", startedAt: 100_000, activity }), 8);+ assert.equal(workSeconds({ status: "complete", startedAt: 100_000, finishedAt: 700_000, activity }), 8);+ const history = entriesToMessages([+ ...activity,+ { seq: 3, type: "approval_resolved", payload: { command: "help", approved: false }, createdAt: 700_000 },+ ]);+ assert.equal(workSeconds((history[0] as AssistantWork).work!), 7);+ const resumed = [+ ...activity,+ { seq: 4, parentSeq: null, type: "text" as const, payload: { text: "continuing" }, createdAt: 710_000 },+ ];+ assert.equal(workSeconds({ status: "complete", startedAt: 700_000, finishedAt: 715_000, activity: resumed }), 15);+});++for (const type of ["approval_request", "tool_result", "tool_call"] as const) {+ test(`${type} timing preserves initial thinking without counting the approval wait`, () => {+ const activity: WorkBlock["activity"] = [+ { seq: 1, parentSeq: null, type: "tool_call", payload: { command: "help" }, createdAt: 112_000 },+ {+ seq: 2,+ parentSeq: 1,+ type,+ payload: { blocked: "needs_approval", workStartedAt: 100_000, workFinishedAt: 113_000 },+ createdAt: 113_000,+ },+ ];+ const live = workSeconds({ status: "complete", startedAt: 100_000, activity });+ for (const decided of [false, true]) {+ const entries: SessionEntry[] = [...activity];+ if (decided)+ entries.push({+ seq: 3,+ type: "approval_resolved",+ payload: { command: "help", approved: false },+ createdAt: 700_000,+ });+ const work = (entriesToMessages(entries)[0] as AssistantWork).work!;+ assert.equal(workSeconds(work), live);+ assert.equal(workSeconds(work), 13);+ }+ });+}+test("work duration survives a transcript refresh — persisted turn timing wins over activity inference", () => {const runStartedAt = 100_000;const runFinishedAt = 113_000;@@ -93,6 +141,48 @@ test("live and historical rendering consume the same duration helper (source-lev"chat renders via the shared helper",);- assert.match(chat, /`Working for \$\{secs\}s` : workedLabel\("Worked", secs\)/);- assert.match(chat, /function segmentSummaryLabel[\s\S]{0,400}?workSeconds\(work\)/);+ assert.match(chat, /workedLabel\(work.status === "working" \? "Working" : "Worked", secs\)/);+ assert.match(chat, /function workLabel[\s\S]{0,400}?workSeconds\(work\)/);+});++test("live and completed work use compact minute and second labels", () => {+ for (const prefix of ["Working", "Worked"]) {+ for (const [seconds, duration] of [+ [7, "7s"],+ [60, "1m"],+ [65, "1m 5s"],+ [365, "6m 5s"],+ ] as const)+ assert.equal(workedLabel(prefix, seconds), `${prefix} for ${duration}`);+ }+});++test("work duration ends at final-answer start while the run stays active and survives history projection", () => {+ const phase = {+ seq: 3,+ parentSeq: null,+ type: "text_start" as const,+ payload: { phase: "final_answer", streamOffset: 11 },+ createdAt: 108_000,+ };+ const work: WorkBlock = { status: "working", startedAt: 100_000, activity: [phase] };+ assert.equal(workSeconds(work), 8);+ assert.equal(work.status, "working");+ const entries: SessionEntry[] = [+ { seq: 1, type: "user", payload: { text: "check" }, createdAt: 100_000 },+ { seq: 2, type: "text", payload: { text: "Checking.", phase: "commentary" }, createdAt: 102_000 },+ phase,+ {+ seq: 4,+ type: "assistant",+ payload: { text: "All clear.", workStartedAt: 100_000, workFinishedAt: 115_000 },+ createdAt: 115_000,+ },+ ];+ const messages = entriesToMessages(entries, MODEL);+ const answer = messages.find((message) => message.role === "assistant") as AssistantWork;+ assert.ok(answer.work);+ assert.equal(workSeconds(answer.work), 8);+ assert.equal(answer.work.status, "complete");+ assert.equal(answer.work.activity.find((entry) => entry.type === "text_start")?.seq, 3);});diff --git a/plugins/web-ui/test/work-fold-source.test.ts b/plugins/web-ui/test/work-fold-source.test.tsindex b4bcbc6f4..65971642b 100644--- a/plugins/web-ui/test/work-fold-source.test.ts+++ b/plugins/web-ui/test/work-fold-source.test.ts@@ -5,16 +5,12 @@ import test from "node:test";const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");-test("finished turns render mid-turn text OUTSIDE the collapsed fold, at its place in the timeline", () => {- assert.match(chat, /if \(demoted\) continue;\s*\n\s*if \(it\.kind === "text"\) \{\s*\n\s*flushSeg\(\);/);- assert.match(chat, /class="work-said"/);- assert.match(chat, /<details class="work-fold"/);-});--test("the fold summary counts tool calls only — spoken text is never tallied as a hidden 'message'", () => {- assert.match(chat, /function segmentSummaryLabel\(/);- assert.ok(!/message\$\{messages === 1/.test(chat), "old 'N messages' summary should be gone");- assert.match(chat, /it\.kind === "tool"/);+test("live and completed work share one chronological duration fold", () => {+ assert.match(chat, /<details class="work work-fold work-/);+ assert.match(chat, /messageWorkTimeline\(work, active \? "" : text\)/);+ assert.match(chat, /const label = stopping \? "Stopping…" : workLabel\(work\)/);+ assert.match(chat, /\?open=\$\{active \|\| !!work.pendingApprovals\?\.length\}/);+ assert.doesNotMatch(chat, /function segmentSummaryLabel/);});test("promoted speech keeps full reply styling", () => {@@ -24,9 +20,8 @@ test("promoted speech keeps full reply styling", () => {test("a demoted post-delivery self-log remains auditable but is omitted from the UI", () => {const bridge = readFileSync(new URL("../src/core-bridge.ts", import.meta.url), "utf8");assert.match(bridge, /payload: \{ text, demoted: true \}/);- assert.match(chat, /demoted === true/);- assert.match(chat, /if \(demoted\) continue;/);- assert.match(chat, /return parts\.length \? .* : html``;/);+ const timeline = readFileSync(new URL("../src/timeline.ts", import.meta.url), "utf8");+ assert.match(timeline, /!payload\?\.demoted/);});test("the fold chevron rotates when a work-fold is open", () => {@@ -34,7 +29,7 @@ test("the fold chevron rotates when a work-fold is open", () => {});test("expanded tool activity uses a compact log rhythm", () => {- assert.match(css, /\.work-divider \{[\s\S]{0,120}?margin: 8px 0 10px;/);+ assert.match(css, /\.work-divider \{[\s\S]{0,120}?margin: 0 0 10px;/);assert.match(css, /\.work-rows \{[\s\S]{0,120}?gap: 5px;/);assert.match(css, /\.tool-row,[\s\S]{0,220}?font-size: 13px;[\s\S]{0,80}?line-height: 1\.35;/);assert.match(css, /\.tool-row \.tool-summary \{[\s\S]{0,80}?min-height: 24px;/);@@ -65,7 +60,7 @@ test("thinking stays in sequence but is independently collapsible", () => {test("dense activity rows let their icons carry repeated type labels", () => {assert.match(chat, /\$\{preview \|\| "Thinking"\}/);- assert.match(chat, /const visible = detail \|\| label;/);+ assert.match(chat, /if \(kind === "failed"\) statusLabel = "Failed";/);assert.match(chat, />\$\{visible\}<\/span>/);assert.doesNotMatch(chat, />Thinking\$\{preview/);assert.doesNotMatch(chat, />\$\{label\}\$\{detail/);diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 919800c44..9cf2ebf9a 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -60,6 +60,7 @@ export function createTurnMethods(| "syncRunStream"| "activeRunForThread"| "withdrawRun"+ | "editQueuedRun"| "signalRun"| "replayOrphanedRunSignals"> {@@ -620,6 +621,29 @@ export function createTurnMethods(return {status: run.status,result: run.result ? await withAdminLink(run.result) : run.result,+ ...(run.request.surface === "web" &&+ !run.request.approval &&+ !run.request.envelopeWrapped &&+ !(run.request.proactiveOpener && !run.request.text.trim()) &&+ isPersonAuthored(resolveTurnOrigin(run.request).kind)+ ? {+ input: {+ runId: run.id,+ seq: run.turnUserSeq,+ text: run.request.displayText ?? run.request.text ?? "",+ createdAt: run.createdAt,+ ...(run.request.attachments?.length+ ? {+ attachments: run.request.attachments.map(({ name, mimetype, sizeBytes }) => ({+ name,+ mimetype,+ sizeBytes,+ })),+ }+ : {}),+ },+ }+ : {}),startedAt: run.startedAt,finishedAt: run.finishedAt,...(partial ? { partial } : {}),@@ -653,6 +677,22 @@ export function createTurnMethods(return { runId: live.id, ...(queued.length ? { queued } : {}) };},+ async editQueuedRun(runId, text, expectedText, viewer) {+ const run = await deps.runs.get(runId);+ if (!run || (viewer && (!samePerson(run.request.actor.id, viewer) || !(await viewerMayUseRun(run, viewer)))))+ return { edited: false, reason: "not_found" };+ if (+ run.request.surface !== "web" ||+ run.request.envelopeWrapped ||+ !isPersonAuthored(resolveTurnOrigin(run.request).kind)+ )+ return { edited: false, reason: "not_editable" };+ if (!text.trim() && !run.request.attachments?.length) return { edited: false, reason: "empty_text" };+ return (await deps.runs.editPendingText(runId, text, expectedText))+ ? { edited: true }+ : { edited: false, reason: "changed_or_started" };+ },+async withdrawRun(runId, viewer) {const run = await deps.runs.get(runId);if (!run) return { withdrawn: false, reason: "not_found" };diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 057da27eb..bed5afce2 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -278,6 +278,13 @@ export interface App {): Promise<{status: Run["status"];result: TurnResult | null;+ input?: {+ runId: string;+ seq: number | null;+ text: string;+ createdAt: number;+ attachments?: Array<{ name: string; mimetype: string; sizeBytes: number }>;+ };partial?: string;alive?: boolean;stale?: boolean;@@ -295,6 +302,12 @@ export interface App {threadRef: string,viewer?: string,): Promise<{ runId: string; queued?: Array<{ runId: string; text: string; hasAttachments?: boolean }> } | null>;+ editQueuedRun(+ runId: string,+ text: string,+ expectedText: string,+ viewer?: string,+ ): Promise<{ edited: boolean; reason?: string }>;withdrawRun(runId: string, viewer?: string): Promise<{ withdrawn: boolean; reason?: string }>;signalRun(runId: string,diff --git a/src/api/routes/run-events.ts b/src/api/routes/run-events.tsindex 779c99f19..f420ccf34 100644--- a/src/api/routes/run-events.ts+++ b/src/api/routes/run-events.ts@@ -67,6 +67,7 @@ async function streamRun(ctx: ApiCtx): Promise<void> {res.destroy();} finally {refreshing = false;+ sync();}};const unsubscribe = app.subscribeRun(@@ -77,7 +78,7 @@ async function streamRun(ctx: ApiCtx): Promise<void> {void refresh();return;}- if (event.kind !== "delta") return;+ if (event.kind !== "delta" || refreshing) return;if (event.offset > offset) {sync();return;diff --git a/src/api/routes/turns.ts b/src/api/routes/turns.tsindex 541db9f31..f677e91e3 100644--- a/src/api/routes/turns.ts+++ b/src/api/routes/turns.ts@@ -146,6 +146,16 @@ async function getActiveRunForThread(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { runId: active?.runId ?? null, ...(active?.queued ? { queued: active.queued } : {}) });}+async function patchQueuedRun(ctx: ApiCtx): Promise<void> {+ const { res, app, actor, body } = ctx;+ if (!isObj(body) || typeof body.text !== "string" || typeof body.expectedText !== "string")+ return sendJson(res, 400, { error: "bad_request", message: "text and expectedText required" });+ const outcome = await app.editQueuedRun(ctx.params.id!, body.text, body.expectedText, actor?.p);+ if (outcome.edited) return sendJson(res, 200, outcome);+ if (outcome.reason === "not_found") return sendJson(res, 404, { error: "not_found" });+ return sendJson(res, outcome.reason === "empty_text" ? 400 : 409, outcome);+}+async function postRunWithdraw(ctx: ApiCtx): Promise<void> {const { res, app, actor } = ctx;const outcome = await app.withdrawRun(ctx.params.id!, actor?.p);@@ -210,6 +220,7 @@ export const turnRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/approvals/:id", auth: "source", handle: getApproval },{ method: "POST", path: "/v1/runs/:id/delivery-state", auth: "source", handle: postRunDeliveryState },{ method: "POST", path: "/v1/runs/:id/signal", auth: "source", handle: postRunSignal },+ { method: "PATCH", path: "/v1/runs/:id/input", auth: "source", handle: patchQueuedRun },{ method: "POST", path: "/v1/runs/:id/withdraw", auth: "source", handle: postRunWithdraw },{ method: "GET", path: "/v1/runs/:id", auth: "source", handle: getRun },{ method: "GET", path: "/v1/runs", auth: "source", handle: getActiveRunForThread },diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex dc7413988..a0bf6030c 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -78,7 +78,13 @@ import {isValidCapabilityTimezone,type CapabilityClaims,} from "../auth/capability-token.ts";-import type { GapWork, HarnessLlmRequestRecord, HarnessTurnResult, RuntimeChoice } from "../harness/harness.ts";+import type {+ GapWork,+ HarnessLlmRequestRecord,+ HarnessTurnInput,+ HarnessTurnResult,+ RuntimeChoice,+} from "../harness/harness.ts";import { forModelContext, forSearchView } from "../harness/context-compaction.ts";import {renderSecurityPolicyPrompt,@@ -208,7 +214,14 @@ export type { Orchestrator, OrchestratorDeps, OrchestratorInput, SurfaceContextPclass ProjectRosterChanged extends Error {}-const ACTIVITY_ENTRY_TYPES = new Set<EntryType>(["tool_call", "tool_result", "approval_request", "approval_resolved"]);+const ACTIVITY_ENTRY_TYPES = new Set<EntryType>([+ "text_start",+ "text",+ "tool_call",+ "tool_result",+ "approval_request",+ "approval_resolved",+]);function knownBrowseModel(id: string | null | undefined): { id: string; provider: string } | undefined {const provider = id ? resolveModel(id)?.provider : undefined;@@ -586,6 +599,32 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (result === undefined) throw new ProjectRosterChanged();return result;};+ const mirrorRunActivity = async (appended: SessionEntry): Promise<void> => {+ if (input.runId && deps.runActivity && ACTIVITY_ENTRY_TYPES.has(appended.type)) {+ await deps.runActivity+ .append(input.runId, {+ seq: appended.seq,+ parentSeq: appended.parentSeq,+ type: appended.type,+ payload: appended.payload,+ createdAt: appended.createdAt,+ })+ .catch(swallowAs("orchestrator: run-activity append", undefined));+ } else if (input.runId && deps.runActivity && appended.type === "thinking") {+ const block = appended.payload as { thinking?: string; redacted?: boolean };+ if (!block.redacted && block.thinking?.trim()) {+ await deps.runActivity+ .append(input.runId, {+ seq: appended.seq,+ parentSeq: appended.parentSeq,+ type: appended.type,+ payload: { thinking: block.thinking },+ createdAt: appended.createdAt,+ })+ .catch(swallowAs("orchestrator: run-activity append", undefined));+ }+ }+ };if (!(await managedRosterIsCurrent())) {return { status: "refused", reason: "project membership changed; retry from the current project" };}@@ -1757,6 +1796,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const messagePrefix = "security-screen-release:session_message_";if (p.approvalKey?.startsWith(messagePrefix))await deps.sessionSyscalls?.rejectMessage?.(session.id, p.approvalKey.slice(messagePrefix.length));+ const decisionEntry = await withManagedRosterVersion(() =>+ deps.sessions.append(lease, {+ type: "approval_resolved",+ payload: { requestId: input.approval!.requestId, command: p.command, approved: false },+ scopeLabel: scopeId as ScopeId,+ }),+ );+ await mirrorRunActivity(decisionEntry);await pending.delete(input.approval.requestId);deps.auditLog.record({at: Date.now(),@@ -1811,6 +1858,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {],};}+ const decisionEntry = await withManagedRosterVersion(() =>+ deps.sessions.append(lease, {+ type: "approval_resolved",+ payload: { requestId: input.approval!.requestId, command: p.command, approved: true, scope },+ scopeLabel: scopeId as ScopeId,+ }),+ );+ await mirrorRunActivity(decisionEntry);await pending.delete(input.approval.requestId);if (p.kind === "input") {await deps.sessions@@ -2888,6 +2943,83 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {...(tapeRows.fold ? { fold: tapeRows.fold } : {}),};}+ const emit: HarnessTurnInput["emit"] = async (entry) => {+ turnProgress++;+ const persistStart = Date.now();+ try {+ const stored = (() => {+ const tainted = entry;+ if (+ tainted.type === "assistant" ||+ tainted.type === "approval_request" ||+ ((tainted.type === "tool_result" || tainted.type === "tool_call") &&+ isObj(tainted.payload) &&+ tainted.payload.blocked === "needs_approval")+ ) {+ const payload = isObj(tainted.payload) ? { ...tainted.payload } : {};+ if (typeof payload.workStartedAt !== "number")+ payload.workStartedAt = input.runStartedAt ?? coreReceivedAt;+ if (typeof payload.workFinishedAt !== "number") payload.workFinishedAt = Date.now();+ return { ...tainted, payload };+ }+ if (tainted.type !== "user") return tainted;+ const payload = isObj(tainted.payload) ? { ...tainted.payload } : {};+ Object.assign(payload, swarmEntryProvenance);+ if (input.runId) payload.runId = input.runId;+ if (actor.displayName?.trim() && typeof payload.name !== "string")+ payload.name = actor.displayName.trim();+ if (input.displayText?.trim() && payload.text === input.text && typeof payload.display !== "string")+ payload.display = input.displayText;+ if (syntheticPrompt || continuation) payload.hidden = true;+ return { ...tainted, payload };+ })();+ const appended = await withManagedRosterVersion(() => deps.sessions.append(lease, stored));+ emittedEntries.push(appended);+ if (input.runId && deps.turnStream) {+ const goalView = goalViewFromEntry(appended.type, appended.payload);+ if (goalView) deps.turnStream.noteGoal(input.runId, goalView);+ }+ if (appended.type === "user" && spine.turnUserEntrySeq === undefined) {+ spine.turnUserEntrySeq = appended.seq;+ if (input.runId && deps.runs)+ await deps.runs+ .noteTurnUserSeq(input.runId, appended.seq)+ .catch(swallowAs("orchestrator: record turn boundary", false));+ }+ if (appended.type === "user") failureUserPayload = undefined;+ if (appended.type === "tool_call") {+ toolCalls += 1;+ if (toolCalls === 1 && input.runId) {+ if (!input.surfaceTools) {+ deps.turnStream?.noteToolCall(input.runId);+ } else if (input.addressed && !isPollFire && spineFirstBlockOpen && !resume && !approvalReplay) {+ spineFirstBlockOpen = false;+ const payload = appended.payload as { tool?: unknown; action?: unknown };+ const deliberatePost = payload?.tool === surfaceName && payload?.action === "post";+ const ack = spineFirstBlock.trim();+ if (!deliberatePost && ack && defaultDestination && deps.deliveries) {+ spineAckText = ack;+ const runId = input.runId;+ const ackKey = `ack:${turnKey}`;+ void reachEnqueue({+ deliveries: deps.deliveries,+ destination: defaultDestination,+ text: ack,+ idempotencyKey: ackKey,+ provenance: postProvenance(ackKey),+ })+ .then(() => deps.turnStream?.markSurfacePosted(runId))+ .catch(swallowAs("orchestrator: first-block ack", undefined));+ }+ }+ }+ }+ await mirrorRunActivity(appended);+ return appended;+ } finally {+ emitGapWork("persist", persistStart, Date.now());+ }+ };return deps.harness.turns.runTurn({session,...(userProviderKeys ? { providerKeys: userProviderKeys } : {}),@@ -3064,99 +3196,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {};return withManagedRosterVersion(() => deps.sessions.appendTape(lease, { ...rec, meta }));},- emit: async (entry) => {- turnProgress++;- const persistStart = Date.now();- try {- const stored = (() => {- const tainted = entry;- if (tainted.type === "assistant") {- const payload = isObj(tainted.payload) ? { ...tainted.payload } : {};- if (typeof payload.workStartedAt !== "number")- payload.workStartedAt = input.runStartedAt ?? coreReceivedAt;- if (typeof payload.workFinishedAt !== "number") payload.workFinishedAt = Date.now();- return { ...tainted, payload };- }- if (tainted.type !== "user") return tainted;- const payload = isObj(tainted.payload) ? { ...tainted.payload } : {};- Object.assign(payload, swarmEntryProvenance);- if (actor.displayName?.trim() && typeof payload.name !== "string")- payload.name = actor.displayName.trim();- if (input.displayText?.trim() && payload.text === input.text && typeof payload.display !== "string")- payload.display = input.displayText;- if (syntheticPrompt || continuation) payload.hidden = true;- return { ...tainted, payload };- })();- const appended = await withManagedRosterVersion(() => deps.sessions.append(lease, stored));- emittedEntries.push(appended);- if (input.runId && deps.turnStream) {- const goalView = goalViewFromEntry(appended.type, appended.payload);- if (goalView) deps.turnStream.noteGoal(input.runId, goalView);- }- if (appended.type === "user" && spine.turnUserEntrySeq === undefined) {- spine.turnUserEntrySeq = appended.seq;- if (input.runId && deps.runs)- await deps.runs- .noteTurnUserSeq(input.runId, appended.seq)- .catch(swallowAs("orchestrator: record turn boundary", false));- }- if (appended.type === "user") failureUserPayload = undefined;- if (appended.type === "tool_call") {- toolCalls += 1;- if (toolCalls === 1 && input.runId) {- if (!input.surfaceTools) {- deps.turnStream?.noteToolCall(input.runId);- } else if (input.addressed && !isPollFire && spineFirstBlockOpen && !resume && !approvalReplay) {- spineFirstBlockOpen = false;- const payload = appended.payload as { tool?: unknown; action?: unknown };- const deliberatePost = payload?.tool === surfaceName && payload?.action === "post";- const ack = spineFirstBlock.trim();- if (!deliberatePost && ack && defaultDestination && deps.deliveries) {- spineAckText = ack;- const runId = input.runId;- const ackKey = `ack:${turnKey}`;- void reachEnqueue({- deliveries: deps.deliveries,- destination: defaultDestination,- text: ack,- idempotencyKey: ackKey,- provenance: postProvenance(ackKey),- })- .then(() => deps.turnStream?.markSurfacePosted(runId))- .catch(swallowAs("orchestrator: first-block ack", undefined));- }- }- }- }- if (input.runId && deps.runActivity && ACTIVITY_ENTRY_TYPES.has(appended.type)) {- await deps.runActivity- .append(input.runId, {- seq: appended.seq,- parentSeq: appended.parentSeq,- type: appended.type,- payload: appended.payload,- createdAt: appended.createdAt,- })- .catch(swallowAs("orchestrator: run-activity append", undefined));- } else if (input.runId && deps.runActivity && appended.type === "thinking") {- const block = appended.payload as { thinking?: string; redacted?: boolean };- if (!block.redacted && block.thinking?.trim()) {- await deps.runActivity- .append(input.runId, {- seq: appended.seq,- parentSeq: appended.parentSeq,- type: appended.type,- payload: { thinking: block.thinking },- createdAt: appended.createdAt,- })- .catch(swallowAs("orchestrator: run-activity append", undefined));- }- }- return appended;- } finally {- emitGapWork("persist", persistStart, Date.now());- }- },+ emit,scopeLabel: scopeId,orgScopeId: resolution.orgScopeId,onDelta: (chunk: string) => {@@ -3167,9 +3207,18 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (input.surfaceTools && spineFirstBlockOpen && spineFirstBlock.length < FIRST_BLOCK_CAPTURE_MAX_CHARS)spineFirstBlock += chunk;},- onTextBlockStart: () => {+ onTextBlockStart: async (phase) => {if (input.runId && deps.turnStream && !input.surfaceTools) deps.turnStream.publishBlockStart(input.runId);if (input.surfaceTools && spineFirstBlock) spineFirstBlockOpen = false;+ if (phase && !input.surfaceTools) {+ const streamOffset =+ input.runId && deps.turnStream ? (deps.turnStream.snapshot(input.runId) ?? "").length : undefined;+ await emit({+ type: "text_start",+ payload: { phase, ...(streamOffset !== undefined ? { streamOffset } : {}) },+ scopeLabel: scopeId,+ });+ }},onGapWork: (cb) => {harnessOnGapWork = cb;diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.tsindex 8a8e033ee..56d3af16a 100644--- a/src/harness/claude-harness.ts+++ b/src/harness/claude-harness.ts@@ -353,6 +353,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {const initial = userMessage(text, turn.images);let pendingPrompts = 1;let stopped = false;+ let interrupted = false;let result: SDKResultMessage | null = null;const thinking: string[] = [];const flushThinking = async () => {@@ -446,6 +447,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {active.add(sdkQuery);const interrupt = async (fromUser: boolean) => {stopped ||= fromUser;+ interrupted = true;queue.close();await sdkQuery.interrupt().catch(() => undefined);controller.abort();@@ -542,7 +544,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {queue.push(initial);const consume = (async () => {for await (const message of sdkQuery) {- if (settled) break;+ if (settled || interrupted) break;if (message.type === "assistant") {const usage = message.message.usage;const seen = {@@ -645,6 +647,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {result = message;await recordStep(message);await flushThinking();+ if (interrupted) break;const terminal = ref.runtimeHandoff || ref.silentRequested || ref.pausedOnApproval;const text = message.subtype === "success" && !terminal ? message.result.trim() : "";if (text) {@@ -678,26 +681,7 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {]): consume);} catch (error) {- if (!controller.signal.aborted || error instanceof NonRetryableTurnError) throw error;- const reply = streamedText.trim();- await flushThinking();- if (reply && !ref.runtimeHandoff && !ref.silentRequested && !ref.pausedOnApproval) {- const finalEntry = await turn.emit({- type: "assistant",- payload: { text: reply, stopped: true },- scopeLabel: turn.scopeLabel,- });- await tapeReplyCheckpoint(turn, finalEntry);- }- return {- reply: ref.runtimeHandoff || ref.silentRequested || ref.pausedOnApproval ? "" : reply,- ...(!ref.runtimeHandoff || stopped ? { stopped: true as const } : {}),- ...(ref.runtimeHandoff ? { runtimeHandoff: ref.runtimeHandoff } : {}),- ...(ref.silentRequested ? { silent: true } : {}),- ...(ref.pendingApprovals?.length ? { pendingApprovals: ref.pendingApprovals } : {}),- ...(ref.pausedOnApproval ? { pausedOnApproval: true } : {}),- modelCalls: Math.max(1, callUsage.size),- };+ if ((!interrupted && !controller.signal.aborted) || error instanceof NonRetryableTurnError) throw error;}const finalResult = result as SDKResultMessage | null;const stoppedPartial = async (): Promise<HarnessTurnResult> => {@@ -719,8 +703,10 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {...(ref.silentRequested ? { silent: true } : {}),...(ref.pendingApprovals?.length ? { pendingApprovals: ref.pendingApprovals } : {}),...(ref.pausedOnApproval ? { pausedOnApproval: true } : {}),+ modelCalls: Math.max(1, callUsage.size),};};+ if (interrupted && (pendingPrompts > 0 || finalResult?.subtype !== "success")) return stoppedPartial();if (!finalResult) {if (controller.signal.aborted) return stoppedPartial();throw new Error("Claude Agent SDK ended without a result");diff --git a/src/harness/codex-app-server.ts b/src/harness/codex-app-server.tsindex 174dab5c8..b02d17a01 100644--- a/src/harness/codex-app-server.ts+++ b/src/harness/codex-app-server.ts@@ -152,12 +152,7 @@ export class CodexAppServer {});let pendingOutput = "";const receiveLine = (line: string) => {- this.eventTail = this.eventTail- .then(() => this.receive(line))- .catch((error) => {- this.failAll(error instanceof Error ? error : new Error(String(error)));- this.process.kill("SIGTERM");- });+ this.eventTail = this.eventTail.then(() => this.receive(line)).catch((error) => this.failTransport(error));};this.process.stdout!.setEncoding("utf8");this.process.stdout!.on("data", (chunk: string) => {@@ -306,19 +301,24 @@ export class CodexAppServer {await this.options.onNotification(message.method, message.params);return;}- void this.respond(message.id, message.method, message.params).catch((error) => {- this.failAll(error instanceof Error ? error : new Error(String(error)));- this.process.kill("SIGTERM");- });+ void this.respond(message.id, message.method, message.params).catch((error) => this.failTransport(error));}private async respond(id: JsonRpcId, method: string, params: unknown): Promise<void> {+ let response: JsonRpcMessage;try {const result = await this.options.onRequest(method, params);- await this.send({ id, result });+ response = { id, result };} catch (error) {- await this.send({ id, error: { code: -32000, message: errMessage(error) } });+ response = { id, error: { code: -32000, message: errMessage(error) } };}+ if (!this.closed) await this.send(response);+ }++ private failTransport(error: unknown): void {+ if (this.closed) return;+ this.failAll(error instanceof Error ? error : new Error(String(error)));+ this.process.kill("SIGTERM");}private send(message: JsonRpcMessage): Promise<void> {diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.tsindex 09dd6ade1..c81be103d 100644--- a/src/harness/codex-harness.ts+++ b/src/harness/codex-harness.ts@@ -126,6 +126,8 @@ type ActiveTurn = {reject(error: Error): void;responseItems: CodexItem[];completedItems: CodexItem[];+ publicMessages: Map<string, CodexItem & { complete?: boolean }>;+ stoppedReply?: string;taskIds: Map<string, string>;taskStatuses: Map<string, TaskStatus>;taskResults: Set<string>;@@ -497,11 +499,41 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {});}if (method === "item/agentMessage/delta" && threadId === state.threadId && typeof p.delta === "string") {+ if (state.stopped) return;+ const id = typeof p.itemId === "string" ? p.itemId : "";+ const item = state.publicMessages.get(id) ?? { type: "agentMessage" };+ item.text = (typeof item.text === "string" ? item.text : "") + p.delta;+ state.publicMessages.set(id, item);state.firstOutputAt ??= Date.now();state.turn.onDelta?.(p.delta);}if ((method === "item/started" || method === "item/completed") && p.item && typeof p.item === "object") {const item = p.item as CodexItem;+ if (threadId === state.threadId && item.type === "agentMessage") {+ if (state.stopped) return;+ const id = typeof item.id === "string" ? item.id : "";+ state.publicMessages.set(id, {+ ...item,+ text: typeof item.text === "string" ? item.text : "",+ complete: method === "item/completed",+ });+ if (method === "item/started")+ await state.turn.onTextBlockStart?.(+ item.phase === "commentary" || item.phase === "final_answer" ? item.phase : undefined,+ );+ if (+ method === "item/completed" &&+ item.phase === "commentary" &&+ typeof item.text === "string" &&+ item.text.trim()+ ) {+ await state.turn.emit({+ type: "text",+ payload: { text: item.text, phase: "commentary" },+ scopeLabel: state.turn.scopeLabel,+ });+ }+ }if (method === "item/completed") {state.completedItems.push(item);if (state.turn.tape && !state.tapeError) {@@ -996,6 +1028,7 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {reject: rejectCompleted,responseItems: [],completedItems: [],+ publicMessages: new Map(),taskIds: new Map(),taskStatuses: new Map(),taskResults: new Set(),@@ -1078,11 +1111,37 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {};let turnId = "";const interrupt = async (stopped: boolean) => {+ if (stopped && !state.stopped) {+ state.stoppedReply = textFromTurn({+ id: turnId,+ status: "interrupted",+ items: [...state.publicMessages.values()].filter((item) => item.phase !== "commentary"),+ });+ }state.stopped ||= stopped;toolAbort.abort();if (turnId) await rt.server.request("turn/interrupt", { threadId, turnId }).catch(() => undefined);};state.interrupt = () => interrupt(false);+ let stoppedReplySaved: Promise<void> | undefined;+ const saveStoppedReply = (): Promise<void> => {+ stoppedReplySaved ??= (async () => {+ for (const item of state.publicMessages.values()) {+ if (item.phase === "commentary" && !item.complete && typeof item.text === "string" && item.text.trim())+ await turn.emit({+ type: "text",+ payload: { text: item.text, phase: "commentary" },+ scopeLabel: turn.scopeLabel,+ });+ }+ await turn.emit({+ type: "assistant",+ payload: { text: state.stoppedReply ?? "", stopped: true },+ scopeLabel: turn.scopeLabel,+ });+ })();+ return stoppedReplySaved;+ };const onCancel = () => {runtimeCleanupRequested = true;void interrupt(true);@@ -1188,9 +1247,10 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {}if (result.status === "failed" && !state.stopped && !ref.runtimeHandoff)throw codexProviderFailure(result.error?.message ?? "Codex turn failed");- if (turn.cancel?.aborted) {- runtimeCleanupRequested = true;- turnResult = { reply: "", stopped: true };+ if (state.stopped || turn.cancel?.aborted) {+ if (turn.cancel?.aborted) runtimeCleanupRequested = true;+ await saveStoppedReply();+ turnResult = { reply: state.stoppedReply ?? "", stopped: true };} else {const terminal = ref.runtimeHandoff || ref.silentRequested || ref.pausedOnApproval;const reply = terminal ? "" : textFromTurn(result);@@ -1217,7 +1277,8 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {} catch (error) {if (turn.cancel?.aborted) {runtimeCleanupRequested = true;- turnResult = { reply: "", stopped: true };+ await saveStoppedReply();+ turnResult = { reply: state.stoppedReply ?? "", stopped: true };} else {throw error;}diff --git a/src/harness/harness.ts b/src/harness/harness.tsindex 42ad45e65..b352f2cf0 100644--- a/src/harness/harness.ts+++ b/src/harness/harness.ts@@ -112,7 +112,7 @@ export interface HarnessTurnInput {onProgress?(p: { toolCalls: number; tokens?: number }): void;onGapWork?(sink: (work: GapWork) => void): void;onDelta?(chunk: string): void;- onTextBlockStart?(): void;+ onTextBlockStart?(phase?: "commentary" | "final_answer"): void | Promise<void>;screenToolResult?(input: ToolResultScreenInput): Promise<ToolResultScreen>;}diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.tsindex d38e92840..1fe44f107 100644--- a/src/harness/mock-harness.ts+++ b/src/harness/mock-harness.ts@@ -259,6 +259,7 @@ export function createMockHarness(): Harness {cmd.slice(cmd.indexOf("!preamble-then-quiet") + "!preamble-then-quiet".length).trim() ||"Still queued — silent.";if (turn.onDelta) for (const chunk of streamChunks(preamble)) turn.onDelta(chunk);+ await turn.emit({ type: "text", payload: { text: preamble }, scopeLabel: turn.scopeLabel });await turn.emit({type: "tool_call",payload: { tool: "execute", command: "check" },@@ -272,6 +273,7 @@ export function createMockHarness(): Harness {const narration =cmd.slice(cmd.indexOf("!narrate-no-update") + "!narrate-no-update".length).trim() || "Nothing new.";if (turn.onDelta) for (const chunk of streamChunks(narration)) turn.onDelta(chunk);+ await turn.emit({ type: "text", payload: { text: narration }, scopeLabel: turn.scopeLabel });await turn.emit({type: "tool_call",payload: { tool: "execute", command: "check" },@@ -280,9 +282,20 @@ export function createMockHarness(): Harness {await turn.emit({ type: "tool_result", payload: { tool: "execute", ok: true }, scopeLabel: turn.scopeLabel });usedTool = true;reply = `${narration}\n\n[no-update]`;+ } else if (command0.startsWith("!phased-reply")) {+ await turn.onTextBlockStart?.("commentary");+ turn.onDelta?.("Checking.");+ await turn.emit({+ type: "text",+ payload: { text: "Checking.", phase: "commentary" },+ scopeLabel: turn.scopeLabel,+ });+ await turn.onTextBlockStart?.("final_answer");+ reply = "All clear.";} else if (command0.startsWith("!preamble")) {const preamble = cmd.slice(cmd.indexOf("!preamble") + "!preamble".length).trim() || "On it — checking.";if (turn.onDelta) for (const chunk of streamChunks(preamble)) turn.onDelta(chunk);+ await turn.emit({ type: "text", payload: { text: preamble }, scopeLabel: turn.scopeLabel });await turn.emit({type: "tool_call",payload: { tool: "execute", command: "check" },diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 595814547..4e90f73f5 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -2344,7 +2344,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {}const finalEntry = await turn.emit({type: "assistant",- payload: { text: reply },+ payload: { text: reply, stopped: true },scopeLabel: turn.scopeLabel,});const stoppedPartial = stoppedPartialTapeMessage(freshMessages, reply, finalEntry.createdAt);diff --git a/src/runs/memory-run-store.ts b/src/runs/memory-run-store.tsindex 29541dab3..a57723d0a 100644--- a/src/runs/memory-run-store.ts+++ b/src/runs/memory-run-store.ts@@ -211,6 +211,14 @@ export function createMemoryRunStore(opts?: { maxClaims?: number }): MemoryRunti.sort((a, b) => a.createdAt - b.createdAt);},+ async editPendingText(runId, text, expectedText) {+ const run = runs.get(runId);+ if (!run || run.status !== "pending" || run.attempts !== 0 || run.turnUserSeq !== null) return false;+ if ((run.request.displayText ?? run.request.text) !== expectedText) return false;+ run.request = { ...run.request, text, displayText: text };+ return true;+ },+async withdraw(runId) {const run = runs.get(runId);if (!run || run.status !== "pending") return false;diff --git a/src/runs/postgres-run-store.ts b/src/runs/postgres-run-store.tsindex ee9d05701..52192f9df 100644--- a/src/runs/postgres-run-store.ts+++ b/src/runs/postgres-run-store.ts@@ -404,6 +404,16 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxClareturn rows.map(rowToRun);},+ async editPendingText(runId: string, text: string, expectedText: string): Promise<boolean> {+ const { rowCount } = await q(+ `UPDATE runs SET request = (request::jsonb || jsonb_build_object('text', $2::text, 'displayText', $2::text))::text+ WHERE id = $1 AND status = 'pending' AND attempts = 0 AND turn_user_seq IS NULL+ AND COALESCE(request::jsonb ->> 'displayText', request::jsonb ->> 'text') = $3`,+ [runId, text, expectedText],+ );+ return (rowCount ?? 0) > 0;+ },+async withdraw(runId: string): Promise<boolean> {const { rowCount } = await q("DELETE FROM runs WHERE id = $1 AND status = 'pending'", [runId]);return (rowCount ?? 0) > 0;diff --git a/src/runs/run-store.ts b/src/runs/run-store.tsindex 00f6f0f18..dd02c4039 100644--- a/src/runs/run-store.ts+++ b/src/runs/run-store.ts@@ -94,6 +94,8 @@ export interface RunStore {withdraw(runId: string): Promise<boolean>;+ editPendingText(runId: string, text: string, expectedText: string): Promise<boolean>;+activeSessionIds(): Promise<string[]>;list(opts?: { limit?: number }): Promise<Run[]>;diff --git a/src/types.ts b/src/types.tsindex d18011c5f..08b977b13 100644--- a/src/types.ts+++ b/src/types.ts@@ -111,6 +111,7 @@ export type EntryType =| "user"| "assistant"| "thinking"+ | "text_start"| "text"| "tool_call"| "tool_result"diff --git a/test/claude-harness-turn.test.ts b/test/claude-harness-turn.test.tsindex c016120e9..76e605952 100644--- a/test/claude-harness-turn.test.ts+++ b/test/claude-harness-turn.test.ts@@ -167,6 +167,138 @@ test("a user stop that surfaces as a non-success SDK result is a clean stop, and);});+for (const late of [+ { type: "stream_event", event: { type: "content_block_delta", delta: { type: "text_delta", text: " late" } } },+ resultMessage("replacement after stop"),+]) {+ test(`Claude freezes partial output when cancellation races with ${late.type}`, async () => {+ const waiting = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const cancel = new AbortController();+ const deltas: string[] = [];+ currentScript = async function* (prompts) {+ await prompts[Symbol.asyncIterator]().next();+ yield {+ type: "stream_event",+ event: { type: "content_block_delta", delta: { type: "text_delta", text: "Visible partial" } },+ };+ waiting.resolve();+ await release.promise;+ yield late;+ };+ const harness = createClaudeHarness({});+ const { turn, entries } = harnessTurn({ cancel: cancel.signal, onDelta: (text) => deltas.push(text) });+ const running = harness.turns.runTurn(turn);+ await waiting.promise;+ cancel.abort();+ release.resolve();+ const result = await running;+ assert.equal(result.stopped, true);+ assert.equal(result.reply, "Visible partial");+ assert.deepEqual(deltas, ["Visible partial"]);+ assert.deepEqual(+ entries.filter((entry) => entry.type === "assistant").map((entry) => entry.payload),+ [{ text: "Visible partial", stopped: true }],+ );+ });+}++for (const bookkeeping of ["request recording", "thinking persistence"]) {+ test(`Claude preserves its partial reply when stopped during ${bookkeeping}`, async () => {+ const waiting = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const cancel = new AbortController();+ currentScript = async function* (prompts) {+ await prompts[Symbol.asyncIterator]().next();+ yield {+ type: "stream_event",+ event: { type: "content_block_delta", delta: { type: "text_delta", text: "Visible partial" } },+ };+ yield {+ type: "assistant",+ message: { id: "thinking", content: [{ type: "thinking", thinking: "Checking the answer." }] },+ };+ yield resultMessage("replacement after stop");+ };+ const harness = createClaudeHarness({});+ const { turn, entries } = harnessTurn({ cancel: cancel.signal });+ const pause = async () => {+ waiting.resolve();+ await release.promise;+ };+ if (bookkeeping === "request recording") turn.recordLlmRequest = pause;+ else {+ const emit = turn.emit;+ turn.emit = async (entry) => {+ if (entry.type === "thinking") await pause();+ return emit(entry);+ };+ }+ const running = harness.turns.runTurn(turn);+ await waiting.promise;+ cancel.abort();+ release.resolve();+ const result = await running;+ assert.equal(result.stopped, true);+ assert.equal(result.reply, "Visible partial");+ assert.deepEqual(+ entries.filter((entry) => entry.type === "assistant").map((entry) => entry.payload),+ [{ text: "Visible partial", stopped: true }],+ );+ });+}++for (const persistence of ["final entry", "reply checkpoint"]) {+ for (const ending of ["close", "throw"]) {+ test(`Claude completes a committed reply when cancelled during ${persistence} persistence and the SDK will ${ending}`, async () => {+ const waiting = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const cancel = new AbortController();+ currentScript = (prompts) => {+ const generator = (async function* () {+ await prompts[Symbol.asyncIterator]().next();+ yield {+ type: "stream_event",+ event: { type: "content_block_delta", delta: { type: "text_delta", text: "Visible partial" } },+ };+ yield resultMessage("Final full answer");+ if (ending === "throw") throw new Error("query interrupted");+ })();+ if (ending === "throw") generator.return = async () => ({ done: true, value: undefined });+ return generator;+ };+ const harness = createClaudeHarness({});+ const { turn, entries } = harnessTurn({ cancel: cancel.signal });+ const pause = async () => {+ waiting.resolve();+ await release.promise;+ };+ if (persistence === "final entry") {+ const emit = turn.emit;+ turn.emit = async (entry) => {+ if (entry.type === "assistant") await pause();+ return emit(entry);+ };+ } else {+ turn.tape = async (entry) => {+ if (entry.kind === "annotation") await pause();+ };+ }+ const running = harness.turns.runTurn(turn);+ await waiting.promise;+ cancel.abort();+ release.resolve();+ const result = await running;+ assert.equal(result.stopped, undefined);+ assert.equal(result.reply, "Final full answer");+ assert.deepEqual(+ entries.filter((entry) => entry.type === "assistant").map((entry) => entry.payload),+ [{ text: "Final full answer" }],+ );+ });+ }+}+test("model calls are counted per API response and charged their real input tokens", async () => {currentScript = async function* (prompts) {await prompts[Symbol.asyncIterator]().next();diff --git a/test/codex-app-server.test.ts b/test/codex-app-server.test.tsindex 4d117361a..f98afea97 100644--- a/test/codex-app-server.test.ts+++ b/test/codex-app-server.test.ts@@ -12,6 +12,119 @@ const cases = [{ name: "an unterminated final frame at EOF", text: "before\u2028after", ending: "", fragmented: true },];+test("Codex tool requests do not block other calls, notifications, or RPC responses", { timeout: 3000 }, async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-tool-concurrency-"));+ const binary = join(dir, "codex");+ writeFileSync(+ binary,+ `#!${process.execPath}+const readline = require("node:readline");+const send = message => process.stdout.write(JSON.stringify(message) + "\\n");+readline.createInterface({ input: process.stdin }).on("line", line => {+ const message = JSON.parse(line);+ if (message.method === "start") {+ send({ id: "first", method: "item/tool/call" });+ send({ id: "second", method: "item/tool/call" });+ send({ id: "third", method: "item/tool/call" });+ send({ method: "progress", params: 1 });+ send({ method: "progress", params: 2 });+ send({ id: message.id, result: "started" });+ } else if (message.method === "nested") send({ id: message.id, result: "nested reply" });+ else if (["first", "second", "third"].includes(message.id)) send({ method: "tool/replied", params: message });+});+`,+ );+ chmodSync(binary, 0o755);+ const release = Promise.withResolvers<void>();+ const firstDone = Promise.withResolvers<void>();+ const calls: number[] = [];+ const notifications: unknown[] = [];+ const replies: unknown[] = [];+ const server: CodexAppServer = new CodexAppServer({+ binaryPath: binary,+ cwd: dir,+ onNotification: async (method, params) => {+ if (method === "progress") {+ await Promise.resolve();+ notifications.push(params);+ } else {+ replies.push(params);+ if ((params as { id: string }).id === "first") firstDone.resolve();+ }+ },+ onRequest: async () => {+ const index = calls.length;+ calls.push(index);+ if (index === 0) {+ assert.equal(await server.request("nested"), "nested reply");+ await release.promise;+ }+ if (index === 2) throw new Error("tool failed");+ return index;+ },+ });+ t.after(async () => {+ release.resolve();+ await server.close();+ rmSync(dir, { recursive: true, force: true });+ });+ assert.equal(await server.request("start", {}, AbortSignal.timeout(1000)), "started");+ assert.deepEqual(calls, [0, 1, 2]);+ assert.deepEqual(notifications, [1, 2]);+ release.resolve();+ await firstDone.promise;+ assert.deepEqual(replies, [+ { id: "second", result: 1 },+ { id: "third", error: { code: -32000, message: "tool failed" } },+ { id: "first", result: 0 },+ ]);+ assert.equal(server.error(), null);+});++for (const fails of [false, true]) {+ test(`Codex tolerates an in-flight tool ${fails ? "failure" : "result"} after transport close`, async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-tool-close-"));+ const binary = join(dir, "codex");+ writeFileSync(+ binary,+ `#!${process.execPath}+const readline = require("node:readline");+readline.createInterface({ input: process.stdin }).on("line", line => {+ const request = JSON.parse(line);+ process.stdout.write(JSON.stringify({ id: "tool", method: "item/tool/call" }) + "\\n");+ process.stdout.write(JSON.stringify({ id: request.id, result: "started" }) + "\\n");+});+`,+ );+ chmodSync(binary, 0o755);+ const release = Promise.withResolvers<void>();+ const finished = Promise.withResolvers<void>();+ const server = new CodexAppServer({+ binaryPath: binary,+ cwd: dir,+ onNotification: () => {},+ onRequest: async () => {+ await release.promise;+ finished.resolve();+ if (fails) throw new Error("late failure");+ return "late result";+ },+ });+ t.after(async () => {+ release.resolve();+ await server.close();+ rmSync(dir, { recursive: true, force: true });+ });+ assert.equal(await server.request("start", {}, AbortSignal.timeout(1000)), "started");+ await server.close();+ const error = server.error();+ release.resolve();+ await finished.promise;+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(server.error(), error);+ });+}+for (const { name, text, ending, fragmented } of cases) {test(`Codex JSON-RPC preserves ${name}`, async (t) => {const dir = mkdtempSync(join(tmpdir(), "qm-codex-framing-"));diff --git a/test/codex-harness.test.ts b/test/codex-harness.test.tsindex ed7ebeb08..7db211963 100644--- a/test/codex-harness.test.ts+++ b/test/codex-harness.test.ts@@ -68,7 +68,7 @@ test("Codex replay keeps paired tool ids within the provider's 64-character limiassert.equal(codexReplayCallId("short-id"), "short-id");});-function fakeCodexBinary(dir: string): string {+function fakeCodexBinary(dir: string, commentary = false): string {const path = join(dir, "fake-codex");writeFileSync(path,@@ -93,6 +93,14 @@ rl.on("line", (line) => {if (msg.method === "thread/inject_items") return send({ id: msg.id, result: {} });if (msg.method === "turn/start") {send({ id: msg.id, result: { turn: { id: "turn-1", status: "inProgress", items: [] } } });+ if (${commentary}) {+ for (const id of ["ack-1", "ack-2"]) {+ send({ method: "item/started", params: { threadId: "thread-1", item: { type: "agentMessage", id, phase: "commentary" } } });+ send({ method: "item/agentMessage/delta", params: { threadId: "thread-1", itemId: id, delta: "Checking." } });+ send({ method: "item/completed", params: { threadId: "thread-1", item: { type: "agentMessage", id, text: "Checking.", phase: "commentary" } } });+ }+ send({ method: "item/started", params: { threadId: "thread-1", item: { type: "agentMessage", id: "item-1", phase: "final_answer" } } });+ }send({ method: "thread/tokenUsage/updated", params: { threadId: "thread-1", tokenUsage: { total: { inputTokens: 100 }, last: { inputTokens: 100 } } } });send({ method: "thread/tokenUsage/updated", params: { threadId: "thread-1", tokenUsage: { total: { inputTokens: 100 }, last: { inputTokens: 100 } } } });send({ method: "item/started", params: { threadId: "thread-1", turnId: "turn-1", item: { type: "collabAgentToolCall", id: "collab-1", tool: "spawnAgent", status: "inProgress", senderThreadId: "thread-1", receiverThreadIds: ["child-1"], prompt: "return ALPHA", agentsStates: { "child-1": { status: "running", message: null } } } } });@@ -1446,7 +1454,7 @@ for (const mode of ["turnFailed", "startRejected"] as const) {});}-function stopReportsFailedCodexBinary(dir: string): string {+function stopReportsFailedCodexBinary(dir: string, stream = false, final = true): string {const path = join(dir, "stop-failed-codex");writeFileSync(path,@@ -1462,10 +1470,23 @@ rl.on("line", (line) => {if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "thread-sf" } } });if (msg.method === "turn/start") {send({ id: msg.id, result: { turn: { id: "turn-sf", status: "inProgress", items: [] } } });+ if (${stream}) {+ send({ method: "item/started", params: { threadId: "thread-sf", item: { id: "ack", type: "agentMessage", phase: "commentary" } } });+ send({ method: "item/agentMessage/delta", params: { threadId: "thread-sf", itemId: "ack", delta: "Checking." } });+ if (${final}) {+ send({ method: "item/completed", params: { threadId: "thread-sf", item: { id: "ack", type: "agentMessage", phase: "commentary", text: "Checking." } } });+ send({ method: "item/started", params: { threadId: "thread-sf", item: { id: "answer", type: "agentMessage", phase: "final_answer" } } });+ send({ method: "item/agentMessage/delta", params: { threadId: "thread-sf", itemId: "answer", delta: "Partial answer" } });+ }+ }return writeFileSync(${JSON.stringify(join(dir, "started"))}, "1");}if (msg.method === "turn/interrupt") {send({ id: msg.id, result: {} });+ if (${stream}) {+ send({ method: "item/agentMessage/delta", params: { threadId: "thread-sf", itemId: "answer", delta: " LATE" } });+ send({ method: "item/completed", params: { threadId: "thread-sf", item: { id: "answer", type: "agentMessage", phase: "final_answer", text: "BAD LATE COMPLETION" } } });+ }return send({ method: "turn/completed", params: { threadId: "thread-sf", turn: { id: "turn-sf", status: "failed", error: { message: "turn interrupted" }, items: [] } } });}});@@ -1725,3 +1746,123 @@ test(assert.deepEqual(requests, []);},);++test("Codex persists repeated public commentary in order with distinct streaming blocks", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-commentary-"));+ const harness = createCodexHarness({ binaryPath: fakeCodexBinary(dir, true), env: testHarnessEnv(dir) });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const entries: SessionEntry[] = [];+ const streamed: string[] = [];+ const scope = "personal:test" as ScopeId;+ const result = await harness.turns.runTurn({+ session: { id: "commentary" } as Session,+ input: "check",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => {+ const saved = {+ ...entry,+ sessionId: "commentary",+ seq: entries.length + 1,+ createdAt: Date.now(),+ } as SessionEntry;+ entries.push(saved);+ return saved;+ },+ recordModelCall: () => {},+ onDelta: (delta) => {+ streamed.push(delta);+ },+ onTextBlockStart: async (phase) => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ streamed.push(`block:${phase}`);+ },+ });+ assert.equal(result.reply, "hello");+ assert.deepEqual(+ entries.filter((entry) => entry.type === "text").map((entry) => entry.payload),+ [+ { text: "Checking.", phase: "commentary" },+ { text: "Checking.", phase: "commentary" },+ ],+ );+ assert.deepEqual(streamed, [+ "block:commentary",+ "Checking.",+ "block:commentary",+ "Checking.",+ "block:final_answer",+ "hello",+ ]);+});++for (const final of [true, false]) {+ for (const mechanism of ["signal", "cancel"] as const) {+ test(`Codex saves only pre-stop ${final ? "final" : "commentary"} text via ${mechanism}`, async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-partial-stop-"));+ const signals = createMemoryRunSignalStore();+ const harness = createCodexHarness({+ binaryPath: stopReportsFailedCodexBinary(dir, true, final),+ env: testHarnessEnv(dir),+ signals,+ turnWallClockMs: 5_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const cancel = new AbortController();+ const received = Promise.withResolvers<void>();+ const entries: SessionEntry[] = [];+ const deltas: string[] = [];+ const scope = "personal:test" as ScopeId;+ const running = harness.turns.runTurn({+ session: { id: "partial-stop" } as Session,+ runId: "partial-stop-run",+ input: "check",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ cancel: cancel.signal,+ emit: async (entry) => {+ const saved = {+ ...entry,+ sessionId: "partial-stop",+ seq: entries.length + 1,+ createdAt: Date.now(),+ } as SessionEntry;+ entries.push(saved);+ return saved;+ },+ recordModelCall: () => {},+ onDelta: (text) => {+ deltas.push(text);+ if (text === (final ? "Partial answer" : "Checking.")) received.resolve();+ },+ });+ await received.promise;+ if (mechanism === "cancel") cancel.abort();+ else await signals.send("partial-stop-run", { kind: "abort" });+ const result = await running;+ assert.equal(result.stopped, true);+ assert.deepEqual(+ entries.filter((entry) => entry.type === "text").map((entry) => entry.payload),+ [{ text: "Checking.", phase: "commentary" }],+ );+ assert.equal(result.reply, final ? "Partial answer" : "");+ assert.deepEqual(deltas, final ? ["Checking.", "Partial answer"] : ["Checking."]);+ assert.deepEqual(+ entries.filter((entry) => entry.type === "assistant").map((entry) => entry.payload),+ [{ text: final ? "Partial answer" : "", stopped: true }],+ );+ });+ }+}diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.tsindex 043dec017..b01495e9a 100644--- a/test/orchestrator.test.ts+++ b/test/orchestrator.test.ts@@ -2074,6 +2074,23 @@ test("read/write round-trip through the workspace", async () => {assert.match(r.reply ?? "", /hello-workspace/);});+test("an approval pause persists timing on its boundary entry", async () => {+ const { app } = freshApp();+ const before = Date.now();+ const first = await app.turn(dm("!paused-approval git push --force origin main"));+ assert.equal(first.status, "ok");+ assert.ok(first.pendingApprovals?.length);+ const paused = await app.getSession(first.sessionId!);+ const boundary = paused!.entries.findLast(+ (entry) => (entry.payload as { blocked?: string })?.blocked === "needs_approval",+ );+ assert.ok(boundary);+ const timing = boundary.payload as { workStartedAt: number; workFinishedAt: number };+ assert.ok(timing.workStartedAt >= before);+ assert.ok(timing.workFinishedAt >= timing.workStartedAt);+ assert.ok(timing.workFinishedAt <= boundary.createdAt);+});+test("dangerous command pauses for HiLO approval, then proceeds when approved", async () => {const { app } = freshApp();const first = await app.turn(dm("!run git push --force origin main"));@@ -3265,6 +3282,27 @@ test("'allow for session' approves every same-command invocation in the same turassert.equal(second.pendingApprovals?.length ?? 0, 0);});+test("accepted approval decisions are durably recorded in the conversation", async () => {+ for (const approved of [false, true]) {+ const { app, sessions, runs } = freshApp();+ const command = "git push --force origin main";+ const first = await app.turn(dm(`!run ${command}`));+ const requestId = first.pendingApprovals![0]!.requestId;+ await app.turn(dm(`!run ${command}`, { approval: { requestId, approved } }));+ const decisions = (await sessions.getEntries(first.sessionId!)).filter(+ (entry) => entry.type === "approval_resolved",+ );+ assert.equal(decisions.length, 1);+ assert.deepEqual(decisions[0]!.payload, { requestId, command, approved, ...(approved ? { scope: "once" } : {}) });+ const replay = (await runs.list()).find((run) => run.request.approval?.requestId === requestId);+ assert.ok(replay);+ const live = await app.getRun(replay.id);+ const liveDecisions = live?.activity?.filter((entry) => entry.type === "approval_resolved");+ assert.equal(liveDecisions?.length, 1);+ assert.deepEqual(liveDecisions![0]!.payload, decisions[0]!.payload);+ }+});+test("'session busy' does not consume the one-shot approval (a retry click still works)", async () => {const { app, sessions } = freshApp();const command = "git push --force origin main";@@ -4018,3 +4056,42 @@ test("private session approval replay preserves restrictions even when the clickassert.equal(run?.request.readOnly, true);assert.equal(run?.request.origin.kind, "automation");});++test("narration reaches the live activity feed before its tool call", async () => {+ const { app, runs } = freshApp();+ const text = "!preamble I'll check the first item.";+ const result = await app.turn(dm(text));+ assert.equal(result.status, "ok");+ const run = (await runs.list()).find((entry) => entry.request.text === text);+ assert.ok(run);+ const view = await app.getRun(run.id);+ assert.deepEqual(+ view?.activity?.map((entry) => entry.type),+ ["text", "tool_call", "tool_result"],+ );+ assert.deepEqual(view?.activity?.[0]?.payload, { text: "I'll check the first item." });+});++test("public text phases persist with exact stream offsets in session history and run activity", async () => {+ const { app, runs } = freshApp();+ const result = await app.turn(dm("!phased-reply"));+ assert.equal(result.status, "ok");+ assert.equal(result.reply, "All clear.");+ const run = (await runs.list()).find((entry) => entry.request.text === "!phased-reply");+ assert.ok(run);+ const view = await app.getRun(run.id);+ const history = await app.getSession(result.sessionId!);+ const expected = [+ { phase: "commentary", streamOffset: 0 },+ { phase: "final_answer", streamOffset: "Checking.\n\n".length },+ ];+ assert.deepEqual(+ view?.activity?.filter((entry) => entry.type === "text_start").map((entry) => entry.payload),+ expected,+ );+ assert.deepEqual(+ history?.entries.filter((entry) => entry.type === "text_start").map((entry) => entry.payload),+ expected,+ );+ assert.equal(view?.partial, "Checking.\n\nAll clear.");+});diff --git a/test/pi-harness-cancel-exit.test.ts b/test/pi-harness-cancel-exit.test.tsindex e14aba557..fd18afb25 100644--- a/test/pi-harness-cancel-exit.test.ts+++ b/test/pi-harness-cancel-exit.test.ts@@ -62,6 +62,7 @@ test("a mid-prompt cancel takes the stopped exit: partial persisted replay-safe,const finalEntry = sink.entries.at(-1);assert.equal(finalEntry?.type, "assistant");assert.equal((finalEntry?.payload as { text?: unknown } | undefined)?.text, "(stopped)");+ assert.equal((finalEntry?.payload as { stopped?: boolean } | undefined)?.stopped, true);const cleanPartial = sink.tape.find((rec) =>rec.kind === "message" &&diff --git a/test/run-events.test.ts b/test/run-events.test.tsindex f93e367d2..3ad3657f6 100644--- a/test/run-events.test.ts+++ b/test/run-events.test.ts@@ -73,3 +73,76 @@ test("run events push deltas without snapshot polling and recover a separate worawait new Promise<void>((resolve) => server.close(() => resolve()));}});++test("run events deliver a pending activity snapshot before subsequent text and recover held deltas", async () => {+ const bus = createMemoryEventBus<RunStreamEvent>("ordered-test");+ let reads = 0;+ let workerText = "";+ let status: "running" | "done" = "running";+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const app = {+ async getRun() {+ reads++;+ if (reads === 3) {+ entered.resolve();+ await release.promise;+ }+ return {+ status,+ startedAt: 0,+ finishedAt: null,+ result: status === "done" ? { status: "ok", reply: workerText } : null,+ activity:+ reads >= 3 ? [{ seq: 1, parentSeq: null, type: "text", payload: { text: "working" }, createdAt: 0 }] : [],+ };+ },+ subscribeRun(_runId, listener, onResync) {+ return bus.subscribe(listener, { onResync });+ },+ syncRunStream(runId, offset) {+ emitRunText(bus, runId, workerText.slice(offset), offset);+ },+ } as Pick<App, "getRun" | "subscribeRun" | "syncRunStream">;+ const server = createServer((req, res) => {+ void runEventRoutes[0]!.handle({ app, req, res, params: { id: "run" } } as unknown as ApiCtx);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const controller = new AbortController();+ try {+ const response = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}`, {+ signal: controller.signal,+ });+ const reader = response.body!.getReader();+ let wire = "";+ const consume = (async () => {+ while (true) {+ const next = await reader.read();+ if (next.done) return;+ wire += new TextDecoder().decode(next.value);+ }+ })();+ await sleep(50);+ assert.equal(reads, 2);+ bus.emit({ runId: "run", kind: "refresh" });+ await entered.promise;+ workerText = "after-boundary";+ bus.emit({ runId: "run", kind: "delta", offset: 0, text: workerText });+ await sleep(30);+ assert.doesNotMatch(wire, /after-boundary/);+ release.resolve();+ await sleep(50);+ assert.ok(wire.indexOf("working") >= 0);+ assert.ok(wire.indexOf("after-boundary") > wire.indexOf("working"));+ assert.equal(wire.match(/after-boundary/g)?.length, 1);+ status = "done";+ bus.emit({ runId: "run", kind: "refresh" });+ await consume;+ assert.equal(bus.size(), 0);+ } finally {+ release.resolve();+ controller.abort();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});diff --git a/test/run-store.test.ts b/test/run-store.test.tsindex 3eaa57f5a..7ecb28044 100644--- a/test/run-store.test.ts+++ b/test/run-store.test.ts@@ -406,3 +406,29 @@ for (const backend of backends) {assert.equal(await runs.noteTurnUserSeq("missing-run", 1), false);});}++test("editing pending text preserves identity, order, attachments and rejects stale or started edits", async () => {+ const { runs } = createMemoryRunStore();+ const request = {+ ...turn("original"),+ attachments: [{ name: "notes.txt", mimetype: "text/plain", sizeBytes: 5, blobId: "notes-blob" }],+ };+ const first = (await runs.enqueue({ sessionId: "edits", request, dedupKey: "edit-key" })).run;+ const next = (await runs.enqueue({ sessionId: "edits", request: turn("next") })).run;+ assert.equal(await runs.editPendingText(first.id, "revised", "original"), true);+ assert.equal(await runs.editPendingText(first.id, "stale", "original"), false);+ const saved = await runs.get(first.id);+ assert.equal(saved?.request.text, "revised");+ assert.equal(saved?.request.displayText, "revised");+ assert.deepEqual(saved?.request.attachments, request.attachments);+ assert.equal(saved?.dedupKey, "edit-key");+ assert.deepEqual(+ (await runs.inFlightForThread("edits")).map((run) => run.id),+ [first.id, next.id],+ );+ const claimed = await runs.claimById(first.id, "worker", 1000);+ assert.equal(claimed?.request.text, "revised");+ assert.equal(await runs.editPendingText(first.id, "late", "revised"), false);+ await runs.fail(first.id, claimed!.leaseToken!, "retry", { retry: true });+ assert.equal(await runs.editPendingText(first.id, "retry edit", "revised"), false);+});diff --git a/test/session-sharing.test.ts b/test/session-sharing.test.tsindex 57e57d112..7389f512a 100644--- a/test/session-sharing.test.ts+++ b/test/session-sharing.test.ts@@ -56,6 +56,26 @@ test("shared transcript allowlists visible message fields and published replies");});+test("work phases and approval decisions remain outside the shared message snapshot", () => {+ assert.deepEqual(+ sharedMessages([+ entry("user", { text: "Run the check" }, 1),+ entry("text_start", { phase: "commentary", streamOffset: 0 }, 2),+ entry("text", { text: "PRIVATE_WORK_NARRATION" }, 3),+ entry("approval_request", { requestId: "r", command: "PRIVATE_COMMAND" }, 4),+ entry("approval_resolved", { requestId: "r", command: "PRIVATE_COMMAND", approved: false }, 5),+ entry("approval_request", { requestId: "r", command: "PRIVATE_COMMAND" }, 6),+ entry("approval_resolved", { requestId: "r", command: "PRIVATE_COMMAND", approved: true, scope: "once" }, 7),+ entry("text_start", { phase: "final_answer", streamOffset: 22 }, 8),+ entry("assistant", { text: "Check complete", stopped: true }, 9),+ ]),+ [+ { role: "user", text: "Run the check" },+ { role: "assistant", text: "Check complete" },+ ],+ );+});+test("fresh shares freeze messages and authorized attachments with separate audiences", async (t) => {const store = createMemoryMap<SessionShare>();const bytes = createMemoryDurableByteStore();diff --git a/test/wake-steering.test.ts b/test/wake-steering.test.tsindex a44d31782..f336aade5 100644--- a/test/wake-steering.test.ts+++ b/test/wake-steering.test.ts@@ -797,3 +797,71 @@ test("screening off delivers ambient updates to the existing run without a classassert.match(signals[0]!.text ?? "", /build finished/);assert.equal(built.modelGateway.audit().filter((rec) => rec.model === "mock-security").length, 0);});++test("queued web edits require the author and preserve queue identity", async () => {+ const built = freshApp();+ const threadRef = "web:U1:edit";+ const first = await built.app.turn(web("first", threadRef));+ await built.runs.claimById(first.runId!, "worker", 30000);+ const second = await built.app.turn(web("second", threadRef));+ const owner = (await built.runs.get(second.runId!))!.request.actor.id;+ assert.deepEqual(await built.app.editQueuedRun(second.runId!, "edited", "second", "internal:other"), {+ edited: false,+ reason: "not_found",+ });+ assert.deepEqual(await built.app.editQueuedRun(second.runId!, "", "second", owner), {+ edited: false,+ reason: "empty_text",+ });+ assert.deepEqual(await built.app.editQueuedRun(second.runId!, "edited", "second", owner), { edited: true });+ assert.deepEqual((await built.app.activeRunForThread(threadRef, owner))?.queued, [+ { runId: second.runId, text: "edited" },+ ]);+ assert.deepEqual(await built.app.editQueuedRun(second.runId!, "stale", "second", owner), {+ edited: false,+ reason: "changed_or_started",+ });+ assert.deepEqual(await built.app.editQueuedRun(first.runId!, "late", "first", owner), {+ edited: false,+ reason: "changed_or_started",+ });+});++test("run snapshots expose authorized durable web input with safe attachment metadata", async () => {+ const built = freshApp();+ const turn = await built.app.turn({+ ...web("pending input", "web:U1:pending-input"),+ attachments: [{ name: "notes.txt", mimetype: "text/plain", sizeBytes: 50, blobId: "private-blob" }],+ });+ const run = (await built.runs.get(turn.runId!))!;+ const snapshot = await built.app.getRun(run.id, run.request.actor.id);+ assert.deepEqual(snapshot?.input, {+ runId: run.id,+ seq: null,+ text: "pending input",+ createdAt: run.createdAt,+ attachments: [{ name: "notes.txt", mimetype: "text/plain", sizeBytes: 50 }],+ });+ assert.equal(await built.app.getRun(run.id, "internal:other"), null);+ await built.runs.noteTurnUserSeq(run.id, 0);+ assert.equal((await built.app.getRun(run.id, run.request.actor.id))?.input?.seq, 0);+ const slack = await built.app.turn(dm("slack input", "D-no-web-input"));+ assert.equal((await built.app.getRun(slack.runId!))?.input, undefined);+ const replay = await built.runs.enqueue({+ sessionId: run.sessionId,+ request: { ...run.request, approval: { requestId: "approval-replay", approved: true } },+ });+ assert.equal((await built.app.getRun(replay.run.id, run.request.actor.id))?.input, undefined);+ for (const text of ["", " "]) {+ const opener = await built.runs.enqueue({+ sessionId: run.sessionId,+ request: { ...run.request, text, proactiveOpener: true },+ });+ assert.equal((await built.app.getRun(opener.run.id, run.request.actor.id))?.input, undefined);+ }+ const explicit = await built.runs.enqueue({+ sessionId: run.sessionId,+ request: { ...run.request, proactiveOpener: true },+ });+ assert.equal((await built.app.getRun(explicit.run.id, run.request.actor.id))?.input?.text, "pending input");+});