Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(gui): frost follow-up bar, ACP ask, caret, and queue chrome

justrachdf9d17796783
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91415bf8..e5711241 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@ current is part of cutting a release.
## Unreleased
+- GUI follow-up bar is a pill over the transcript with CSS frost; working subagents sit on the dock.
+- `ask_user` round-trips over ACP so the desktop can show an ApprovalCard mid-turn.
+- `#1011`: live replies keep the typewriter and block caret; the caret hides when the turn is done, and the first chunk reveals instead of painting in as one blob.
+- `#1009`: queued follow-up row does not paint a surface bar while a turn is working.
+- Drawn HTML uses the live desktop palette unless the turn already names colors (ADR 0137).
- Accord Unix 0600 is a standing duplex per live session (`GRAFF_ACCORD=0` opts out); JSONL stays the durable room (ADR 0134). `/debug` reports Accord session count and RSS.
- Engine messaging (idle peer mail, #1007) is the same latch on line REPL, TUI, and `graff acp`.
- `#1001`: idle TUI and line REPL start a turn when the durable peer room has new unread mail (one auto-turn per batch; inbox consume resets).
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index b8bf9bcb..b24b45f0 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -324,6 +324,14 @@ export async function POST(req: NextRequest) {
await endTurn(slot);
return Response.json({ ok: true });
}
+ if (method === "session/answer") {
+ try {
+ slot.transport.notify("session/answer", { ...body.params, sessionId: slot.sessionId });
+ } catch {
+ // a dead transport means the turn is over regardless
+ }
+ return Response.json({ ok: true });
+ }
if (method === "session/idle") {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
diff --git a/apps/native/components/primitives/ApprovalCard.tsx b/apps/native/components/primitives/ApprovalCard.tsx
index 2d557085..70f9fe68 100644
--- a/apps/native/components/primitives/ApprovalCard.tsx
+++ b/apps/native/components/primitives/ApprovalCard.tsx
@@ -2,6 +2,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import { Button } from "@/components/atoms/Button";
+import GlideMenu from "@/components/primitives/GlideMenu";
/* ─────────────────────────────────────────────────────────
* APPROVAL CARD (human-in-the-loop)
@@ -124,10 +125,12 @@ export type ApprovalQuestion = {
export default function ApprovalCard({
onSubmitted,
+ onCancelled,
resettable = true,
questions,
}: {
onSubmitted?: (answers?: string[]) => void;
+ onCancelled?: () => void;
resettable?: boolean;
variant?: string;
questions?: ApprovalQuestion[];
@@ -258,7 +261,7 @@ export default function ApprovalCard({
<button
type="button"
aria-label="Dismiss"
- onClick={() => setOpen(false)}
+ onClick={() => { setOpen(false); onCancelled?.(); }}
className="primitive-icon-button absolute right-2.5 top-2.5 z-10 text-ink-3 transition-colors duration-100 hover:bg-hover hover:text-ink"
>
<Ico size={14} sw={2.2} path={<path d="M18 6L6 18M6 6l12 12" />} />
@@ -296,17 +299,18 @@ export default function ApprovalCard({
style={questionStyle}
>
<div className="pr-7 text-[14px] font-medium text-ink">{question.q}</div>
- <div className="mt-2 flex flex-col gap-0.5">
+ <GlideMenu className="mt-2.5 flex flex-col gap-1" highlightClassName="inset-x-0 rounded-control bg-hover">
{question.options.map((option, i) => {
const on = picked.includes(i);
return (
<button
key={option}
type="button"
+ data-menu-row
aria-pressed={on}
tabIndex={active ? 0 : -1}
onClick={() => { if (active) toggle(i); }}
- className="flex items-center gap-2 rounded-control px-1.5 py-1 text-left transition-colors duration-100 hover:bg-hover"
+ className="relative z-10 flex items-center gap-1.5 rounded-control pl-1 pr-2 py-1 text-left transition-colors duration-100"
>
<span
className={`flex size-4 shrink-0 items-center justify-center transition-colors duration-200
@@ -325,8 +329,7 @@ export default function ApprovalCard({
</button>
);
})}
- <label className="flex items-center gap-2 rounded-control px-1.5 py-1 transition-colors duration-100 focus-within:bg-hover hover:bg-hover">
- <span aria-hidden="true" className="size-4 shrink-0" />
+ <label data-menu-row className="relative z-10 flex items-center gap-1.5 rounded-control pl-1 pr-2 py-1 transition-colors duration-100">
<input
value={custom[qIdx] ?? ""}
tabIndex={active ? 0 : -1}
@@ -346,7 +349,7 @@ export default function ApprovalCard({
className="min-w-0 flex-1 bg-transparent text-[13px] text-ink outline-none placeholder:text-ink-3"
/>
</label>
- </div>
+ </GlideMenu>
</div>
);
})}
@@ -381,7 +384,7 @@ export default function ApprovalCard({
</div>
<div className="-mr-0.5 flex items-center gap-1.5">
- <Button variant="ghost" size="sm" onClick={() => setOpen(false)}>
+ <Button variant="ghost" size="sm" onClick={() => (last ? (setOpen(false), onCancelled?.()) : goTo(qi + 1))}>
Skip
</Button>
<Button variant="accent" size="sm" disabled={!hasAnswer} onClick={advance}>
diff --git a/apps/native/components/primitives/LoadingState.tsx b/apps/native/components/primitives/LoadingState.tsx
index 210b98f5..06b196c5 100644
--- a/apps/native/components/primitives/LoadingState.tsx
+++ b/apps/native/components/primitives/LoadingState.tsx
@@ -60,12 +60,13 @@ function LoaderGrid({
);
}
-function useElapsed() {
+function useElapsed(paused = false) {
const [ds, setDs] = useState(0);
useEffect(() => {
+ if (paused) return;
const t = setInterval(() => setDs((d) => d + 1), 100);
return () => clearInterval(t);
- }, []);
+ }, [paused]);
const total = ds / 10;
if (total < 60) return `${total.toFixed(1)}s`;
return `${Math.floor(total / 60)}m ${(total % 60).toFixed(1)}s`;
@@ -74,14 +75,18 @@ function useElapsed() {
export default function LoadingState({
label,
variant = "Drive",
+ /** When set, the live clock is skipped and this string is shown (turn activity). */
+ elapsed,
/** the meme feed for the Surfer variant; drop the file in /public to light it up */
videoSrc = "/subway-surfers.mp4",
}: {
label?: string;
variant?: string;
+ elapsed?: string;
videoSrc?: string;
}) {
- const elapsed = useElapsed();
+ const clock = useElapsed(elapsed !== undefined);
+ const timed = elapsed !== undefined ? elapsed : clock;
const surfer = variant === "Surfer";
const resolvedLabel = label ?? (surfer ? "Subway surfing" : "Churning");
const [videoOk, setVideoOk] = useState(true);
@@ -100,7 +105,7 @@ export default function LoadingState({
{resolvedLabel}
</span>
);
- const elapsedEl = <span className="font-mono text-[12px] text-ink-3 tabular-nums">{elapsed}</span>;
+ const elapsedEl = timed ? <span data-activity-detail className="font-mono text-[12px] text-ink-3 tabular-nums">{timed}</span> : null;
if (surfer) {
return (
diff --git a/apps/native/components/primitives/Markdown.tsx b/apps/native/components/primitives/Markdown.tsx
index 713af05c..a589685a 100644
--- a/apps/native/components/primitives/Markdown.tsx
+++ b/apps/native/components/primitives/Markdown.tsx
@@ -128,7 +128,9 @@ export default function Markdown({
onOpenPath,
}: {
text: string;
- /** A turn is still arriving: heal the open tail and show the caret. */
+ /** A turn is still arriving: heal the open tail and show the caret.
+ * Once it settles, omit the caret — the block glyph is the typing cursor,
+ * not a settled mark (#1011). */
streaming?: boolean;
/** The whole text is already here (a file in the files pane): one parse,
* no block splitting, no tail healing. */
@@ -149,7 +151,7 @@ export default function Markdown({
<Streamdown
mode={asDocument ? "static" : "streaming"}
isAnimating={streaming}
- caret="block"
+ caret={streaming ? "block" : undefined}
plugins={PLUGINS}
mermaid={mermaidOptions}
components={components}
diff --git a/apps/native/components/primitives/PromptBar.module.css b/apps/native/components/primitives/PromptBar.module.css
index d837c737..6798ebd0 100644
--- a/apps/native/components/primitives/PromptBar.module.css
+++ b/apps/native/components/primitives/PromptBar.module.css
@@ -3,6 +3,40 @@
min-width: 0;
}
+/* Liquid Glass-ish shell: a distinct control layer over the transcript.
+ * Samples the chat (ADR 0138), not the desktop. Heavy blur + fill so
+ * body text underneath is a wash, not a second sentence. */
+.glass {
+ background: color-mix(in oklab, var(--surface) 94%, transparent);
+ box-shadow:
+ inset 0 1px 0 oklch(1 0 0 / 0.22),
+ inset 0 -1px 0 oklch(0 0 0 / 0.12),
+ var(--shadow-overlay);
+ backdrop-filter: blur(110px) saturate(1.85);
+ -webkit-backdrop-filter: blur(110px) saturate(1.85);
+}
+/* Short scrim above the pill — Apple's scroll-edge idea: content under
+ * the bar recedes so the control stays readable. */
+.dock {
+ background: linear-gradient(
+ to top,
+ color-mix(in oklab, var(--page) 88%, transparent) 0%,
+ color-mix(in oklab, var(--page) 48%, transparent) 50%,
+ transparent 100%
+ );
+}
+@media (prefers-reduced-transparency: reduce) {
+ .glass {
+ background: var(--surface);
+ box-shadow: var(--shadow-overlay);
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+ }
+ .dock {
+ background: none;
+ }
+}
+
/* Split panes can be narrow even on a large display. Keep settings legible
on their own row and reserve separate space for attachment/send actions. */
@container (max-width: 420px) {
diff --git a/apps/native/components/primitives/PromptBar.tsx b/apps/native/components/primitives/PromptBar.tsx
index 6d82c869..1e88bbf4 100644
--- a/apps/native/components/primitives/PromptBar.tsx
+++ b/apps/native/components/primitives/PromptBar.tsx
@@ -386,7 +386,7 @@ export default function PromptBar({
setDragging(false);
void attachFiles(files);
}}
- className={`relative isolate flex flex-col overflow-hidden border bg-surface shadow-card transition-[border-color,border-radius] duration-150 focus-within:border-line-strong ${
+ className={`relative isolate flex flex-col overflow-hidden border ${layout.glass} transition-[border-color,border-radius] duration-150 focus-within:border-line-strong ${
dragging ? "border-accent-ink" : "border-line"
} ${
tall ? "gap-2.5 p-3.5" : "gap-1.5 p-1.5"
diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsx
index 151d55c7..9819d955 100644
--- a/apps/native/components/primitives/ToolChips.tsx
+++ b/apps/native/components/primitives/ToolChips.tsx
@@ -309,8 +309,10 @@ export default function ToolChips({
);
})}
</div>
+ </div>
+ </div>}
- {/* file-diff chips */}
+ {/* file-diff chips — sit outside the disclosure so a collapsed run still shows what changed */}
{(live ? diffs.length > 0 : step >= total) && (
<div className="mt-2.5 flex max-w-full flex-wrap gap-1.5 border-t border-line pt-2.5">
{diffs.map((d, i) => (
@@ -327,6 +329,7 @@ export default function ToolChips({
aria-label={`Show diff for ${d.file}`}
onFocus={openPreview(d.file)}
onBlur={closePreview(d.file)}
+ onClick={onOpenPath ? () => onOpenPath(d.file) : undefined}
className="inline-flex h-7 max-w-full items-center gap-1.5 rounded-chip
bg-surface px-2 font-mono text-[11.5px] text-ink shadow-btn
transition-colors duration-100 hover:bg-hover"
@@ -336,22 +339,10 @@ export default function ToolChips({
<span className="shrink-0 text-green tabular-nums">+{d.add}</span>
{d.del > 0 && <span className="shrink-0 text-red tabular-nums">−{d.del}</span>}
</button>
-
</span>
))}
- <button
- type="button"
- className="inline-flex h-7 items-center rounded-chip px-1.5 font-mono text-[11.5px] text-ink-3
- underline decoration-transparent underline-offset-2 transition-colors duration-100
- hover:text-ink-2 hover:decoration-current"
- style={{ animation: `fade-in 300ms ease-out ${DIFFS.length * 80}ms both` }}
- >
- {live ? `${diffs.length} files` : "+2 more"}
- </button>
</div>
)}
- </div>
- </div>}
{preview && typeof document !== "undefined" && createPortal(
<div
className="fixed z-50 w-72 overflow-hidden rounded-[10px] bg-surface shadow-overlay"
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index bb485deb..9592c191 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -4,6 +4,7 @@ import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefOb
import Markdown from "@/components/primitives/Markdown";
import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips, { type LiveDiff } from "@/components/primitives/ToolChips";
+import ApprovalCard from "@/components/primitives/ApprovalCard";
import TurnActivity from "./TurnActivity";
import HtmlArtifact from "./HtmlArtifact";
import McpAppResult from "./McpAppResult";
@@ -113,6 +114,7 @@ export const AssistantBody = memo(function AssistantBody({
turn,
onOpenPath,
onReview,
+ onAnswer,
scroller,
following,
reasoningLabel,
@@ -121,6 +123,7 @@ export const AssistantBody = memo(function AssistantBody({
turn: AssistantTurn;
onOpenPath?: (path: string) => void;
onReview?: () => void;
+ onAnswer?: (text: string, cancelled?: boolean) => void;
scroller?: RefObject<HTMLDivElement | null>;
following: boolean;
reasoningLabel?: string;
@@ -179,6 +182,16 @@ export const AssistantBody = memo(function AssistantBody({
</div>
),
)}
+ {turn.status === "ask" && turn.ask && (
+ <div data-ask-card className="mt-4">
+ <ApprovalCard
+ questions={[{ q: turn.ask.question, type: "radio", options: turn.ask.options }]}
+ resettable={false}
+ onSubmitted={(answers) => onAnswer?.(answers?.filter(Boolean).join(", ") ?? "", false)}
+ onCancelled={() => onAnswer?.("", true)}
+ />
+ </div>
+ )}
{!snapshot && <TurnActivity turn={turn} />}
{turn.error && (
<p role="alert" className="mt-4 max-w-[620px] text-[13.5px] leading-[1.65] text-red">{turn.error}</p>
diff --git a/apps/native/components/site/ChatColumn.tsx b/apps/native/components/site/ChatColumn.tsx
index b01e5d28..c88e4017 100644
--- a/apps/native/components/site/ChatColumn.tsx
+++ b/apps/native/components/site/ChatColumn.tsx
@@ -1,20 +1,23 @@
"use client";
import type { ComponentProps } from "react";
import PromptBar from "@/components/primitives/PromptBar";
+import composer from "@/components/primitives/PromptBar.module.css";
import type { Health } from "@/lib/acp-client";
import type { loadSession } from "@/lib/sessions";
import ChatTranscript from "./ChatTranscript";
import EmptyState from "./ChatEmpty";
import PromptQueue from "./PromptQueue";
+import ComposerAgents from "./ComposerAgents";
import SavedSnapshot from "./SavedSnapshot";
import type { Chat } from "./harness-types";
-export default function ChatColumn({ thread, compact, following, register, onOpenPath, onReview, onEditPrompt,
+export default function ChatColumn({ thread, compact, following, register, onOpenPath, onReview, onAnswer, onEditPrompt,
prompt, queue, pins, onShowPins, onClearPins, health, onOpenProject, onProjects, onConversations,
onRefresh, onContinue }: {
thread: Chat; compact: boolean; following: boolean;
register: (element: HTMLDivElement | null) => void;
- onOpenPath: (path: string) => void; onReview: () => void; onEditPrompt?: (n: number, text: string) => void;
+ onOpenPath: (path: string) => void; onReview: () => void;
+ onAnswer?: (text: string, cancelled?: boolean) => void; onEditPrompt?: (n: number, text: string) => void;
prompt: ComponentProps<typeof PromptBar> & Required<Pick<ComponentProps<typeof PromptBar>, "onSend" | "models" | "onModelChange">>;
queue: ComponentProps<typeof PromptQueue>;
pins: number; onShowPins: () => void; onClearPins: () => void;
@@ -29,13 +32,14 @@ export default function ChatColumn({ thread, compact, following, register, onOpe
health={health} history={prompt.history} cwd={prompt.root} models={prompt.models}
modelKey={prompt.modelKey} onModelChange={prompt.onModelChange} commands={prompt.commands} />
</div>;
- return <div className="flex min-h-0 flex-1 flex-col">
+ return <div className="relative flex min-h-0 flex-1 flex-col">
<ChatTranscript messages={thread.messages} register={register} following={following}
- onOpenPath={onOpenPath} onReview={onReview} snapshot={thread.snapshot} onEditPrompt={onEditPrompt} />
- <div data-chat-composer className={`shrink-0 bg-page px-4 ${compact ? "py-2" : "pt-3 pb-6 sm:px-8"}`}>
- <div className="mx-auto max-w-[720px]">
+ onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer} snapshot={thread.snapshot} onEditPrompt={onEditPrompt} />
+ <div data-chat-composer className={`pointer-events-none absolute inset-x-0 bottom-0 z-10 px-4 ${composer.dock} ${compact ? "py-2" : "pt-16 pb-6 sm:px-8"}`}>
+ <div className="pointer-events-auto mx-auto max-w-[720px]">
{thread.snapshot && thread.session ? <SavedSnapshot name={thread.session} cwd={thread.cwd} model={prompt.modelKey}
onRefresh={onRefresh} onContinue={onContinue} /> : <>
+ <ComposerAgents root={prompt.root} session={thread.session} />
{pins > 0 && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
<span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Pinned</span>
<span className="min-w-0 flex-1 truncate text-ink">{pins} element{pins === 1 ? "" : "s"} in the browser go with your next message</span>
@@ -45,7 +49,7 @@ export default function ChatColumn({ thread, compact, following, register, onOpe
</button>
</div>}
<PromptQueue {...queue} />
- <PromptBar {...prompt} contextMeter={contextMeter} tall={!compact} placeholder={prompt.busy ? "Queue a follow-up…" : "Follow up"} />
+ <PromptBar {...prompt} variant="Pill" contextMeter={contextMeter} placeholder={prompt.busy ? "Queue a follow-up…" : "Follow up"} />
</>}
</div>
</div>
diff --git a/apps/native/components/site/ChatEmpty.tsx b/apps/native/components/site/ChatEmpty.tsx
index 0a1f8667..ae431b1b 100644
--- a/apps/native/components/site/ChatEmpty.tsx
+++ b/apps/native/components/site/ChatEmpty.tsx
@@ -59,6 +59,7 @@ export default function EmptyState({
<div className={`relative ${compact ? "" : "home-reveal home-reveal-composer mt-7"}`}>
<PromptBar
demo={false}
+ variant="Pill"
tall={!compact}
placeholder={compact ? "Ask graff…" : "Ask graff to read, edit, or review this workspace…"}
models={models}
diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsx
index 8cb31f38..204317f9 100644
--- a/apps/native/components/site/ChatTranscript.tsx
+++ b/apps/native/components/site/ChatTranscript.tsx
@@ -6,9 +6,10 @@ import type { Msg } from "./harness-types";
import { pinScrollerTail } from "@/lib/follow-scroll";
import { transcriptPageStart } from "@/lib/transcript-window";
-export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview, snapshot, onEditPrompt }: {
+export default memo(function ChatTranscript({ messages, register, following, onOpenPath, onReview, onAnswer, snapshot, onEditPrompt }: {
messages: Msg[]; register: (element: HTMLDivElement | null) => void; following: boolean;
- onOpenPath: (path: string) => void; onReview: () => void; snapshot?: boolean;
+ onOpenPath: (path: string) => void; onReview: () => void;
+ onAnswer?: (text: string, cancelled?: boolean) => void; snapshot?: boolean;
onEditPrompt?: (n: number, text: string) => void; // n is 1-based user prompt index; text is the replacement
}) {
const scroller = useRef<HTMLDivElement>(null);
@@ -52,7 +53,7 @@ export default memo(function ChatTranscript({ messages, register, following, onO
}, []);
return <div ref={registerScroller} data-chat-transcript data-following={following}
className="min-h-0 min-w-0 max-w-full flex-1 overflow-x-hidden overflow-y-auto overscroll-contain" style={{ overflowAnchor: "none" }}>
- <div data-transcript-content className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 py-8 sm:px-8">
+ <div data-transcript-content className="mx-auto flex w-full max-w-[720px] flex-col gap-8 px-4 pt-8 pb-36 sm:px-8">
{start > 0 && <button type="button" className="self-center rounded-lg bg-field px-3 py-2 text-xs text-ink-2 hover:bg-hover" onClick={() => {
const el = scroller.current;
if (el) anchor.current = { height: el.scrollHeight, top: el.scrollTop };
@@ -66,7 +67,7 @@ export default memo(function ChatTranscript({ messages, register, following, onO
const n = messages.slice(0, start + index + 1).filter(m => m.role === "user" && m.origin !== "notification").length;
onEditPrompt(n, next);
}} />
- : <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview}
+ : <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer}
scroller={scroller} following={following && start + index === messages.length - 1} snapshot={snapshot} />)}
</div>
</div>;
diff --git a/apps/native/components/site/ComposerAgents.tsx b/apps/native/components/site/ComposerAgents.tsx
new file mode 100644
index 00000000..c1289af9
--- /dev/null
+++ b/apps/native/components/site/ComposerAgents.tsx
@@ -0,0 +1,86 @@
+"use client";
+import { useEffect, useState } from "react";
+import {
+ agentRequest,
+ childElapsed,
+ composerChildren,
+ type ChildAgent,
+ type LocalAgent,
+} from "@/lib/agents";
+import layout from "@/components/primitives/PromptBar.module.css";
+
+export default function ComposerAgents({ root, session }: { root?: string; session?: string }) {
+ const [children, setChildren] = useState<ChildAgent[]>([]);
+ const [parent, setParent] = useState<LocalAgent | null>(null);
+ const [now, setNow] = useState(Date.now);
+ const [stopping, setStopping] = useState<string | null>(null);
+ useEffect(() => {
+ if (!session) return;
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const controller = new AbortController();
+ const poll = async () => {
+ try {
+ if (document.visibilityState !== "hidden") {
+ const listed = await agentRequest(root, { action: "list", scope: "workspace" }, controller.signal);
+ const mine = (listed.agents as LocalAgent[] | undefined)?.find(agent => agent.session === session) ?? null;
+ if (disposed) return;
+ setParent(mine);
+ if (!mine) { setChildren([]); }
+ else {
+ const result = await agentRequest(root, {
+ action: "children", scope: "workspace", target: mine.session, startId: mine.startId,
+ }, controller.signal);
+ if (!disposed) setChildren(composerChildren(result.children));
+ }
+ }
+ } catch {
+ if (!disposed) setChildren([]);
+ } finally {
+ if (!disposed) timer = setTimeout(poll, 3000);
+ }
+ };
+ void poll();
+ return () => { disposed = true; controller.abort(); clearTimeout(timer); };
+ }, [root, session]);
+ const live = children.some(child => child.status === "working");
+ useEffect(() => {
+ if (!live) return;
+ const timer = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(timer);
+ }, [live]);
+ const stop = async (id: string) => {
+ if (!parent || stopping) return;
+ setStopping(id);
+ try {
+ await agentRequest(root, { action: "cancel", scope: "workspace", target: parent.session, startId: parent.startId, child: id });
+ setChildren(current => current.map(child => child.id === id ? { ...child, status: "failed" } : child));
+ } catch { /* keep the chip; next poll corrects it */ }
+ finally { setStopping(null); }
+ };
+ if (!children.length) return null;
+ return (
+ <ul aria-label="Sub-agents" className="mb-2 flex flex-col gap-1.5">
+ {children.map(child => (
+ <li key={child.id} data-composer-child={child.id}
+ className={`${layout.glass} flex min-w-0 items-center gap-2 rounded-full border border-line px-2.5 py-1.5 text-[12.5px]`}>
+ {child.status === "working"
+ ? <span aria-hidden className="size-3 shrink-0 rounded-full border-[1.5px] border-ink-3 border-t-ink animate-spin motion-reduce:animate-none" />
+ : <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-red" />}
+ <span className="shrink-0 font-medium text-ink">{child.status === "failed" ? "Failed" : child.label || "Sub-agent"}</span>
+ <span className="min-w-0 flex-1 truncate text-ink-3" title={child.task}>{child.task}</span>
+ <span className="shrink-0 font-mono text-[11.5px] text-ink-3 tabular-nums">{childElapsed(child.updatedAt, now)}</span>
+ {child.status === "working" && (
+ <button type="button" aria-label="Stop sub-agent" disabled={stopping === child.id}
+ onClick={() => void stop(child.id)}
+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-ink-3 hover:bg-hover hover:text-ink disabled:opacity-40">
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" aria-hidden>
+ <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
+ </svg>
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 6ef275f9..773d407f 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -39,7 +39,7 @@ import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-s
import { useDesktopShortcuts } from "./useDesktopShortcuts";
import { useDesktopWorkspace } from "./useDesktopWorkspace";
import {
- cancel,
+ answer, cancel,
chatHandle,
disposeSession,
type Health,
@@ -437,13 +437,13 @@ export default function GraffHarness() {
const steerQueued = (chat: number, item: number) => steerer.steer(chat, item, () => {
const session = sessionsRef.current.get(chat);
- if (!session) return Promise.reject(new Error("Session unavailable"));
- return cancel(handleOf(chat), session);
+ return session ? cancel(handleOf(chat), session) : Promise.reject(new Error("Session unavailable"));
});
const columnBody = (thread: Chat) => <ChatColumn key={thread.id} thread={thread}
compact={columnIds.length > 1 || navigation.focusedMode || filesOpen || browserOpen || agentsOpen || reviewsOpen || !!(fileRequest?.changes)} following={tailing[thread.id] ?? true} register={paneRef(thread.id)}
onOpenPath={openPath} onReview={openChanges}
+ onAnswer={(text, cancelled) => { const live = sessionsRef.current.get(thread.id); const ask = thread.messages.findLast(m => m.role === "assistant")?.turn.ask; if (live && ask) void answer(handleOf(thread.id), live, { callId: ask.callId, text, cancelled }); }}
onEditPrompt={(n, text) => {
const live = sessionsRef.current.get(thread.id);
if (live) void cancel(handleOf(thread.id), live).catch(() => undefined);
diff --git a/apps/native/components/site/PromptQueue.tsx b/apps/native/components/site/PromptQueue.tsx
index 99fd8f25..4d7c7731 100644
--- a/apps/native/components/site/PromptQueue.tsx
+++ b/apps/native/components/site/PromptQueue.tsx
@@ -60,7 +60,8 @@ export default function PromptQueue({ items, busy, status, error, onSteer, onRem
// The words without their markers; a marker never renders as a path.
const label = parts.filter((_, index) => index % 2 === 0).join("").replace(/\s+/g, " ").trim();
return (
- <li key={item.id} data-queued-prompt={item.id} className="flex flex-wrap items-center gap-2 rounded-[8px] bg-surface px-2.5 py-1.5 text-[12.5px] text-ink-2 shadow-hairline">
+ <li key={item.id} data-queued-prompt={item.id} data-queue-chrome={busy ? "working" : "idle"}
+ className={`flex flex-wrap items-center gap-2 rounded-[8px] px-2.5 py-1.5 text-[12.5px] text-ink-2 ${busy ? "" : "bg-surface shadow-hairline"}`}>
<span className="shrink-0 text-[11px] font-medium tracking-wide text-ink-3 uppercase">Queued</span>
{editing === item.id ? (
<>
@@ -91,7 +92,7 @@ export default function PromptQueue({ items, busy, status, error, onSteer, onRem
</>
) : (
<>
- <span className="min-w-0 flex-1 truncate text-ink" title={item.text}>{label || "Attachment only"}</span>
+ <span className={`min-w-0 flex-1 truncate ${busy ? "text-ink-3" : "text-ink"}`} title={item.text}>{label || "Attachment only"}</span>
{parts.map((part, index) => index % 2 === 1
? <QueuedImage key={`${index}-${part}`} name={markerName(part)} />
: null)}
diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsx
index 02c59196..bd7cfa31 100644
--- a/apps/native/components/site/TurnActivity.tsx
+++ b/apps/native/components/site/TurnActivity.tsx
@@ -1,5 +1,6 @@
"use client";
import { useEffect, useState } from "react";
+import LoadingState from "@/components/primitives/LoadingState";
import type { AssistantTurn } from "@/lib/acp";
import { turnActivity } from "@/lib/turn-activity";
export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn; snapshot?: boolean }) {
@@ -17,8 +18,13 @@ export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn;
}, [active]);
if (!turn.startedAt && !active && !turn.error && turn.status !== "snapshot") return null;
const activity = turnActivity(turn, now, snapshot ? { snapshot: true } : undefined);
- return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : activity.live ? "text-ink-2" : "text-ink-3"}`}>
- {activity.live ? <span aria-hidden="true" className="size-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-r-transparent motion-reduce:animate-none" /> : <span aria-hidden="true">{activity.state === "snapshot" ? "○" : activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span>}
+ if (activity.live) {
+ return <div data-turn-activity={activity.state} className="mt-4">
+ <LoadingState label={activity.label} elapsed={activity.detail ?? ""} variant="Drive" />
+ </div>;
+ }
+ return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : "text-ink-3"}`}>
+ <span aria-hidden="true">{activity.state === "snapshot" ? "○" : activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span>
<span role="status" aria-live="polite">{activity.label}</span>{activity.detail && <><span aria-hidden="true">·</span><span data-activity-detail className="tabular-nums">{activity.detail}</span></>}
</div>;
}
diff --git a/apps/native/components/site/useSmoothStream.ts b/apps/native/components/site/useSmoothStream.ts
index 38af0a4f..af923eb7 100644
--- a/apps/native/components/site/useSmoothStream.ts
+++ b/apps/native/components/site/useSmoothStream.ts
@@ -4,17 +4,19 @@ import { useEffect, useRef, useState } from "react";
import { createSmoothStream } from "@/lib/smooth-stream";
/** Reveal live text only while visible and motion is welcome. Switching either
- * condition off flushes the latest text and cancels the pending frame. */
+ * condition off flushes the latest text and cancels the pending frame.
+ * The controller starts empty so the first live chunk typewrites instead of
+ * painting in as one blob — same as `createSmoothStream("")` in the unit tests. */
export function useSmoothStream(target: string, live: boolean): string {
- const [shown, setShown] = useState(target);
+ const [shown, setShown] = useState(live ? "" : target);
const latest = useRef(target);
latest.current = target;
const animated = useRef(false);
const stream = useRef<ReturnType<typeof createSmoothStream> | null>(null);
useEffect(() => {
if (!live) return;
- const controller = createSmoothStream(latest.current, setShown);
- setShown(latest.current);
+ const controller = createSmoothStream("", setShown);
+ setShown("");
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
const syncMotion = () => {
animated.current = !document.hidden && !reduced.matches;
diff --git a/apps/native/e2e/queue.pw.ts b/apps/native/e2e/queue.pw.ts
index c9205e69..79c7c58c 100644
--- a/apps/native/e2e/queue.pw.ts
+++ b/apps/native/e2e/queue.pw.ts
@@ -11,6 +11,13 @@ test.beforeEach(async ({ page }) => {
await page.getByRole("button", { name: "Start fixture" }).click();
});
+test("a working queued row has no surface fill", async ({ page }) => {
+ const queued = page.locator('[data-queued-prompt="1"]');
+ await expect(queued).toHaveAttribute("data-queue-chrome", "working");
+ const bg = await queued.evaluate(el => getComputedStyle(el).backgroundColor);
+ expect(bg === "rgba(0, 0, 0, 0)" || bg === "transparent").toBeTruthy();
+});
+
test("editing a non-head message pauses completion and sends the saved multiline text", async ({ page }) => {
const queued = page.locator(row);
await expect(queued.locator("img")).toHaveJSProperty("naturalWidth", 1);
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index acf9794b..3030e8af 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -162,6 +162,24 @@ export async function cancel(chat: ChatHandle, sessionId: string): Promise<void>
if (!response.ok) throw new Error("Could not interrupt the current turn");
}
+/** Mid-turn reply to `ask_user`. Notification, like cancel — the prompt stream stays open. */
+export async function answer(
+ chat: ChatHandle,
+ sessionId: string,
+ opts: { callId: string; text?: string; cancelled?: boolean },
+): Promise<void> {
+ const response = await fetch(BASE, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ chat,
+ method: "session/answer",
+ params: { sessionId, callId: opts.callId, text: opts.text ?? "", cancelled: opts.cancelled === true },
+ }),
+ });
+ if (!response.ok) throw new Error("Could not send the answer");
+}
+
/** Kill a closed tab's agent. `keepalive` so a close-then-navigate still lands. */
export async function disposeSession(chat: ChatHandle): Promise<void> {
await fetch(BASE, {
diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.ts
index 98dfcfca..8c20d462 100644
--- a/apps/native/lib/acp.test.ts
+++ b/apps/native/lib/acp.test.ts
@@ -18,6 +18,18 @@ describe("parseRpcLine", () => {
});
describe("applyAcpUpdate", () => {
+ it("surfaces gui_ask_user as an ask with options", () => {
+ const turn = applyAcpUpdate(emptyTurn(), {
+ sessionUpdate: "gui_ask_user",
+ callId: "q1",
+ question: "Which mix?",
+ input: { options: ["Pistachio", "Mint"] },
+ });
+ assert.equal(turn.status, "ask");
+ assert.equal(turn.ask?.callId, "q1");
+ assert.equal(turn.ask?.question, "Which mix?");
+ assert.deepEqual(turn.ask?.options, ["Pistachio", "Mint"]);
+ });
it("keeps the file chip when a completion update omits its title and input", () => {
let turn = applyAcpUpdate(emptyTurn(), {sessionUpdate:'tool_call', toolCallId:'read-one', title:'read_file', kind:'read', rawInput:{path:'navigation.ts'}, status:'in_progress'});
turn = applyAcpUpdate(turn, {sessionUpdate:'tool_call_update', toolCallId:'read-one', status:'completed'});
diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index 483e2fd7..e5914f69 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -45,6 +45,7 @@ export type JsonRpcLine =
import {
emptyTurn,
+ parseAskOptions,
type AssistantTurn,
type ToolIcon,
type ToolRow,
@@ -223,7 +224,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
todos: todos.length ? todos : turn.todos,
// Text after a tool bracket is a new message segment, not a continuation.
pendingBreak: turn.text.length > 0 ? true : turn.pendingBreak,
- status: turn.status === "ask" ? "ask" : status === "running" || turn.status === "thinking" ? "streaming" : turn.status,
+ status: status === "running" || turn.status === "thinking" || turn.status === "ask" ? "streaming" : turn.status,
};
if ((merged.icon === "write" || kind === "edit") && (status === "ok" || status === "error")) {
return { ...next, diffs: mergeDiff(next, merged, contentText) };
@@ -278,7 +279,7 @@ export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): Assistan
return {
...turn,
reasoning: `${turn.reasoning}${text}`,
- status: turn.status === "ask" ? "ask" : turn.text ? "streaming" : "thinking",
+ status: turn.text ? "streaming" : "thinking",
};
}
case "agent_message_chunk": {
@@ -288,7 +289,19 @@ export function applyAcpUpdate(turn: AssistantTurn, update: AcpUpdate): Assistan
...turn,
text: `${turn.text}${needsBreak ? "\n\n" : ""}${text}`,
pendingBreak: false,
- status: turn.status === "ask" ? "ask" : "streaming",
+ status: "streaming",
+ };
+ }
+ case "gui_ask_user": {
+ const rec = update as { callId?: unknown; call_id?: unknown; question?: unknown; input?: unknown };
+ return {
+ ...turn,
+ ask: {
+ callId: String(rec.callId ?? rec.call_id ?? ""),
+ question: String(rec.question ?? "The agent needs a decision."),
+ options: parseAskOptions(rec.input),
+ },
+ status: "ask",
};
}
case "tool_call":
diff --git a/apps/native/lib/agents.test.ts b/apps/native/lib/agents.test.ts
index de994414..32b630e1 100644
--- a/apps/native/lib/agents.test.ts
+++ b/apps/native/lib/agents.test.ts
@@ -1,6 +1,6 @@
import { describe, it } from "node:test";
import assert from "node:assert/strict";
-import { workingAgentCount } from "./agents.ts";
+import { childElapsed, composerChildren, workingAgentCount } from "./agents.ts";
describe("working agent occupancy", () => {
it("counts working peers and ignores idle ones", () => {
@@ -9,3 +9,18 @@ describe("working agent occupancy", () => {
assert.equal(workingAgentCount([{ status: "waiting" }, { status: "working" }, { status: "working" }]), 2);
});
});
+
+describe("composer subagent chips", () => {
+ it("hides completed children and keeps failed ones", () => {
+ assert.deepEqual(composerChildren([
+ { id: "a", label: "Scout", task: "read", status: "working", updatedAt: 1, truncated: false },
+ { id: "b", label: "Done", task: "write", status: "completed", updatedAt: 1, truncated: false },
+ { id: "c", label: "Broke", task: "run", status: "failed", updatedAt: 1, truncated: false },
+ ]).map(child => child.id), ["a", "c"]);
+ });
+ it("formats elapsed the way the dock prints it", () => {
+ assert.equal(childElapsed(0, 45_000), "45s");
+ assert.equal(childElapsed(0, 90_000), "1m 30s");
+ assert.equal(childElapsed(0, 5_427_000), "1h 30m 27s");
+ });
+});
diff --git a/apps/native/lib/agents.ts b/apps/native/lib/agents.ts
index 470d14bc..d614c2ac 100644
--- a/apps/native/lib/agents.ts
+++ b/apps/native/lib/agents.ts
@@ -16,4 +16,17 @@ export async function agentRequest(root: string | undefined, params: Record<stri
}
export type ChildAgent = { id: string; label: string; task: string; status: 'working' | 'completed' | 'failed'; updatedAt: number; truncated: boolean };
+
+/** Working and failed children belong on the composer dock; completed ones do not. */
+export function composerChildren(children: ChildAgent[] | undefined): ChildAgent[] {
+ return (children ?? []).filter(child => child.status !== 'completed');
+}
+
+export function childElapsed(updatedAt: number, now = Date.now()): string {
+ const start = updatedAt > 0 && updatedAt < 1e12 ? updatedAt * 1000 : updatedAt;
+ const seconds = Math.max(0, Math.floor((now - start) / 1000));
+ if (seconds < 60) return `${seconds}s`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
+ return `${Math.floor(seconds / 3600)}h ${Math.floor(seconds % 3600 / 60)}m ${seconds % 60}s`;
+}
export type ChildActivity = { agent: ChildAgent; updates: import('./acp').JsonRpcLine[]; response: string };
diff --git a/apps/native/lib/appearance-note.ts b/apps/native/lib/appearance-note.ts
index 53320a9e..659f1a6c 100644
--- a/apps/native/lib/appearance-note.ts
+++ b/apps/native/lib/appearance-note.ts
@@ -18,7 +18,7 @@ export function appearanceNote(tokens: Record<string, string>): string {
.filter(token => tokens[token])
.map(token => `--${token}: ${tokens[token]}`)
.join("; ");
- return `[desktop appearance] A render_html view has no product chrome; the page bleeds into the transcript. If you draw, set the page background to --page and surfaces to --surface so it matches the desktop. CSS: ${css}`;
+ return `[desktop appearance] A render_html view has no product chrome; the page bleeds into the transcript. When you draw HTML, bake in this desktop palette (--page for the page background, --surface for cards, --ink for text) unless this turn already names colors or a palette. CSS: ${css}`;
}
export function withAppearanceNote<T extends { prompt?: unknown }>(params: T, tokens: Record<string, string>): T {
diff --git a/apps/native/lib/assistant-body.test.tsx b/apps/native/lib/assistant-body.test.tsx
index 04ec73ec..1cfb7d57 100644
--- a/apps/native/lib/assistant-body.test.tsx
+++ b/apps/native/lib/assistant-body.test.tsx
@@ -11,6 +11,18 @@ test("completed turns do not retain a synthetic waiting disclosure", () => {
expect(html).not.toContain("Thought for");
});
+test("ask_user renders the approval card instead of a spinner", () => {
+ const turn = {
+ ...emptyTurn(),
+ status: "ask" as const,
+ ask: { callId: "q1", question: "Which mix?", options: ["Pistachio", "Mint"] },
+ };
+ const html = renderToStaticMarkup(<AssistantBody turn={turn} following={false} />);
+ expect(html).toContain("Which mix?");
+ expect(html).toContain("Pistachio");
+ expect(html).toContain("data-ask-card");
+});
+
test("actual reasoning is retained when a turn completes", () => {
const turn = { ...emptyTurn(), status: "done" as const, reasoning: "Inspect the relevant file.", thoughtMs: 8000 };
const html = renderToStaticMarkup(<AssistantBody turn={turn} following={false} />);
diff --git a/apps/native/lib/graff-events.test.ts b/apps/native/lib/graff-events.test.ts
index 87a86296..3c64915e 100644
--- a/apps/native/lib/graff-events.test.ts
+++ b/apps/native/lib/graff-events.test.ts
@@ -52,10 +52,11 @@ describe("applyEvent", () => {
type: "ask_user",
call_id: "q1",
question: "Apply the edit?",
- input: {},
+ input: { options: ["Yes", "No"] },
});
assert.equal(turn.status, "ask");
assert.equal(turn.ask?.callId, "q1");
+ assert.deepEqual(turn.ask?.options, ["Yes", "No"]);
turn = applyEvent(turn, { type: "turn", text: "done", context_tokens: 1, cost_usd: 0.01 });
assert.equal(turn.status, "done");
assert.equal(turn.ask, undefined);
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index 86762810..71ac4cd9 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -80,8 +80,16 @@ export type TodoItem = {
export type AskPrompt = {
callId: string;
question: string;
+ options: string[];
};
+export function parseAskOptions(input: unknown): string[] {
+ if (!input || typeof input !== "object") return [];
+ const opts = (input as Record<string, unknown>).options;
+ if (!Array.isArray(opts)) return [];
+ return opts.flatMap((item) => (typeof item === "string" && item.trim() ? [item] : []));
+}
+
export type TurnStatus = "thinking" | "streaming" | "ask" | "done" | "error" | "snapshot";
export type AssistantTurn = {
@@ -163,7 +171,7 @@ function upsertTool(turn: AssistantTurn, name: string, input: Record<string, unk
path: typeof input.path === "string" ? input.path : undefined,
atChars: turn.text.length,
};
- return { ...turn, tools: [...turn.tools, row], status: turn.status === "ask" ? "ask" : "streaming" };
+ return { ...turn, tools: [...turn.tools, row], status: "streaming" };
}
export function summarizeInput(name: string, input: Record<string, unknown>): { text: string; tone?: "add" }[] {
@@ -284,19 +292,19 @@ export function applyEvent(turn: AssistantTurn, ev: GraffEvent): AssistantTurn {
...turn,
provider: typeof ev.provider === "string" ? ev.provider : turn.provider,
model: typeof ev.model === "string" ? ev.model : turn.model,
- status: turn.status === "ask" ? "ask" : "thinking",
+ status: "thinking",
};
case "reasoning":
return {
...turn,
reasoning: `${turn.reasoning}${typeof ev.text === "string" ? ev.text : ""}`,
- status: turn.status === "ask" ? "ask" : "thinking",
+ status: "thinking",
};
case "text":
return {
...turn,
text: `${turn.text}${typeof ev.text === "string" ? ev.text : ""}`,
- status: turn.status === "ask" ? "ask" : "streaming",
+ status: "streaming",
};
case "tool_call":
case "tool_call_started": {
@@ -336,6 +344,7 @@ export function applyEvent(turn: AssistantTurn, ev: GraffEvent): AssistantTurn {
ask: {
callId: String(ev.call_id ?? ""),
question: String(ev.question ?? "The agent needs a decision."),
+ options: parseAskOptions(ev.input),
},
status: "ask",
};
@@ -356,7 +365,7 @@ export function applyEvent(turn: AssistantTurn, ev: GraffEvent): AssistantTurn {
status: "error",
};
case "finalizing":
- return { ...turn, status: turn.status === "ask" ? "ask" : "streaming" };
+ return { ...turn, status: "streaming" };
default:
return turn;
}
diff --git a/apps/native/lib/gui-skill-context.ts b/apps/native/lib/gui-skill-context.ts
index 07984a75..102e4c45 100644
--- a/apps/native/lib/gui-skill-context.ts
+++ b/apps/native/lib/gui-skill-context.ts
@@ -31,7 +31,7 @@ export async function prepareGuiPrompt(params: Record<string, unknown> | undefin
const first = prompt.find(block => block.type === "text" && typeof block.text === "string");
if (!first || typeof first.text !== "string") {
if (!tokens) return params;
- const next = { ...params };
+ const next: Record<string, unknown> = { ...params };
delete next.appearance;
return next;
}
@@ -44,7 +44,7 @@ export async function prepareGuiPrompt(params: Record<string, unknown> | undefin
first.text = withGuiSkillContext(first.text, instructions.join("\n\n"));
}
if (tokens) first.text = `${first.text}\n\n${appearanceNote(tokens)}`;
- const next = { ...params, prompt };
+ const next: Record<string, unknown> = { ...params, prompt };
delete next.appearance;
return next;
}
diff --git a/apps/native/lib/gui-skills.test.ts b/apps/native/lib/gui-skills.test.ts
index de61df57..6e29902c 100644
--- a/apps/native/lib/gui-skills.test.ts
+++ b/apps/native/lib/gui-skills.test.ts
@@ -35,9 +35,18 @@ test("desktop appearance tokens ride the prompt and leave the catalog alone", as
expect(text).toContain("[desktop appearance]");
expect(text).toContain("--page: #faf8f5");
expect(text).toContain("--surface: #ffffff");
+ expect(text).toContain("unless this turn already names colors or a palette");
expect(prepared).not.toHaveProperty("appearance");
expect(original.prompt[0].text).toBe("Draw the burn-down");
});
+test("named colors still receive the live tokens so unspecified ones can match", async () => {
+ const original = { prompt: [{ type: "text", text: "Draw it with #ff4d4d bars on white" }], appearance: { page: "#0b0c09", surface: "#141712", ink: "#ececec" } };
+ const prepared = await prepareGuiPrompt(original);
+ const text = (prepared?.prompt as { text: string }[])[0].text;
+ expect(text.startsWith("Draw it with #ff4d4d bars on white")).toBe(true);
+ expect(text).toContain("--page: #0b0c09");
+ expect(text).toContain("unless this turn already names colors or a palette");
+});
test("MCP GUI skill injects config paths without the theme directory", async () => {
const original = { prompt: [{ type: "text", text: "$mcp add a filesystem server" }] };
const prepared = await prepareGuiPrompt(original);
diff --git a/apps/native/lib/markdown-caret.test.tsx b/apps/native/lib/markdown-caret.test.tsx
new file mode 100644
index 00000000..8cb9786d
--- /dev/null
+++ b/apps/native/lib/markdown-caret.test.tsx
@@ -0,0 +1,10 @@
+import { expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+import Markdown from "../components/primitives/Markdown";
+
+test("the block caret is only on a live reply", () => {
+ const live = renderToStaticMarkup(<Markdown text="Checking the motion lifecycle" streaming />);
+ const done = renderToStaticMarkup(<Markdown text="Checking the motion lifecycle" />);
+ expect(live).toContain("--streamdown-caret");
+ expect(done).not.toContain("--streamdown-caret");
+});
diff --git a/apps/native/lib/smooth-stream.test.ts b/apps/native/lib/smooth-stream.test.ts
index 9fc0dc6c..ed282291 100644
--- a/apps/native/lib/smooth-stream.test.ts
+++ b/apps/native/lib/smooth-stream.test.ts
@@ -10,6 +10,31 @@ function fixture() {
return { stream, frames, painted, tick(index: number) { now += 1000 / 120; frames[index](now); } };
}
+test("starting on the full string never typewrites — the live hook must start empty", () => {
+ const painted: string[] = [];
+ const frames: ((now: number) => void)[] = [];
+ let now = 0;
+ const blob = "The whole answer arrives in one chunk. ".repeat(20);
+ const stream = createSmoothStream(blob, text => painted.push(text), {
+ now: () => now, frame(callback) { frames.push(callback); return frames.length; }, cancel() {},
+ });
+ stream.update(blob, true);
+ expect(frames.length).toBe(0);
+ expect(painted).toEqual([]);
+ stream.dispose();
+});
+
+test("an empty start reveals the first live chunk instead of painting it in", () => {
+ const { stream, frames, painted, tick } = fixture();
+ const blob = "The whole answer arrives in one chunk. ".repeat(20);
+ stream.update(blob, true);
+ expect(frames.length).toBe(1);
+ tick(0);
+ expect(painted.at(-1)?.length).toBeGreaterThan(0);
+ expect(painted.at(-1)?.length).toBeLessThan(blob.length);
+ stream.dispose();
+});
+
test("120 Hz deliveries update the pending reveal instead of cancelling it", () => {
const { stream, frames, painted, tick } = fixture();
let target = "";
diff --git a/docs/adr/0137-desktop-appearance-is-a-turn-note.md b/docs/adr/0137-desktop-appearance-is-a-turn-note.md
index 9fb9d959..95a9d2b9 100644
--- a/docs/adr/0137-desktop-appearance-is-a-turn-note.md
+++ b/docs/adr/0137-desktop-appearance-is-a-turn-note.md
@@ -18,6 +18,7 @@ turn (#1006).
On the desktop, resolved appearance tokens (`page`, `surface`, `ink`, and the
rest of the existing token set) ride `session/prompt` as a small turn-local
note. They are not written into `prompt_text` and not into the tool catalog.
+Drawn HTML uses that palette unless the user already named colors this turn.
A model-drawn page has no product header and no 620px well. Close/open stays a
quiet control. MCP app results keep their own chrome.
@@ -25,5 +26,6 @@ quiet control. MCP app results keep their own chrome.
## Consequences
A theme switch does not bust the prefix cache. Existing snapshots still have
-whatever colors the model hardcoded; new pages can match `--page` / `--surface`.
-The opaque frame and CSP sandbox are unchanged.
+whatever colors the model hardcoded; new pages match `--page` / `--surface` /
+`--ink` unless the turn already names a palette. The opaque frame and CSP
+sandbox are unchanged.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 5727f46e..ef21c228 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -156,7 +156,7 @@ record only when you need the evidence or the edge cases.
| [0134](0134-accord-live-jsonl-durable.md) | JSONL is the durable peer room; Accord Unix 0600 is live by default (`GRAFF_ACCORD=0` opts out). |
| [0135](0135-one-shell-tool.md) | Advertise one `shell` tool (`run` / `output` / `kill`); bash names stay dispatch aliases. Not a PTY. |
| [0136](0136-follow-up-promotes-a-live-shell.md) | A queued follow-up or force-steer promotes a foreground shell; Esc still kills it. |
-| [0137](0137-desktop-appearance-is-a-turn-note.md) | Desktop appearance tokens for `render_html` ride the turn, never the prefix or tool catalog. |
+| [0137](0137-desktop-appearance-is-a-turn-note.md) | Desktop appearance tokens for `render_html` ride the turn, never the prefix or tool catalog; drawn HTML uses them unless the user named colors. |
| [0138](0138-unselected-splits-use-glass-overlay.md) | Unselected split panes keep their transcript under a light wash; the focused pane stays the working surface. |
## When to write one
diff --git a/docs/rendered-views.md b/docs/rendered-views.md
index 04efce00..f5eb6765 100644
--- a/docs/rendered-views.md
+++ b/docs/rendered-views.md
@@ -11,8 +11,8 @@ The view keeps its own inline `<style>` and `<script>`, so a page can be
animated or interactive. It sits in the transcript without a product header
or framed well; a quiet Close view / Open view control disposes and restores
the frame without touching the conversation. On the desktop, the live
-appearance tokens ride the turn as a note so a new page can match `--page`
-and `--surface` (ADR 0137).
+appearance tokens ride the turn as a note so a new page uses `--page`,
+`--surface`, and `--ink` unless the user already named colors (ADR 0137).
## Where the page lives
diff --git a/src/acp.zig b/src/acp.zig
index 6f2d595e..68de4c99 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -186,6 +186,8 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
var inbox: @import("acp_inbox.zig").Inbox = .{ .gpa = gpa, .io = io, .reader = in };
try inbox.start();
defer inbox.deinit();
+ @import("acp_ask.zig").attach(io, gpa);
+ defer @import("acp_ask.zig").detach();
var live: LiveTurn = .{ .root = root, .keys = keys, .out = out, .inbox = &inbox };
var d: Dispatch = .{
.turn = LiveTurn.run,
diff --git a/src/acp_ask.zig b/src/acp_ask.zig
new file mode 100644
index 00000000..39ef22b0
--- /dev/null
+++ b/src/acp_ask.zig
@@ -0,0 +1,116 @@
+//! Mid-turn mailbox for ACP `session/answer` while `ask_user` is blocked.
+//!
+//! ACP owns stdin, so json_inbox never starts. Cancel and answers have to
+//! land on this slot from `acp_inbox.accept` without waiting for handleLine.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+var mutex: Io.Mutex = .init;
+var ready: Io.Condition = .init;
+var io_slot: ?Io = null;
+var gpa_slot: ?Allocator = null;
+var text: ?[]u8 = null;
+var cancelled = false;
+var pending = false;
+var waiting = false;
+
+pub const Reply = struct {
+ text: []const u8,
+ cancelled: bool,
+};
+
+pub fn attach(io: Io, gpa: Allocator) void {
+ io_slot = io;
+ gpa_slot = gpa;
+ clearLocked();
+ pending = false;
+ cancelled = false;
+ waiting = false;
+}
+
+pub fn detach() void {
+ if (io_slot) |io| {
+ mutex.lockUncancelable(io);
+ clearLocked();
+ mutex.unlock(io);
+ }
+ io_slot = null;
+ gpa_slot = null;
+ pending = false;
+ cancelled = false;
+ waiting = false;
+}
+
+fn clearLocked() void {
+ if (text) |t| {
+ if (gpa_slot) |gpa| gpa.free(t);
+ text = null;
+ }
+}
+
+pub fn wait(arena: Allocator) !Reply {
+ const lock_io = io_slot orelse return .{ .text = "", .cancelled = true };
+ mutex.lockUncancelable(lock_io);
+ defer mutex.unlock(lock_io);
+ waiting = true;
+ defer waiting = false;
+ while (!pending) ready.waitUncancelable(lock_io, &mutex);
+ pending = false;
+ const was = cancelled;
+ cancelled = false;
+ const src = text;
+ text = null;
+ defer if (src) |t| if (gpa_slot) |gpa| gpa.free(t);
+ if (was) return .{ .text = "", .cancelled = true };
+ return .{ .text = try arena.dupe(u8, src orelse ""), .cancelled = false };
+}
+
+pub fn reply(answer: []const u8, cancel: bool) void {
+ const io = io_slot orelse return;
+ const gpa = gpa_slot orelse return;
+ mutex.lockUncancelable(io);
+ defer mutex.unlock(io);
+ clearLocked();
+ cancelled = cancel;
+ if (!cancel) text = gpa.dupe(u8, answer) catch null;
+ pending = true;
+ ready.broadcast(io);
+}
+
+/// session/cancel while ask_user is blocked: wake the waiter, ignore otherwise.
+pub fn cancelIfWaiting() void {
+ const io = io_slot orelse return;
+ mutex.lockUncancelable(io);
+ defer mutex.unlock(io);
+ if (!waiting) return;
+ clearLocked();
+ cancelled = true;
+ pending = true;
+ ready.broadcast(io);
+}
+
+const testing = std.testing;
+
+test "reply before wait is not lost" {
+ attach(testing.io, testing.allocator);
+ defer detach();
+ reply("yes", false);
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const got = try wait(arena_state.allocator());
+ try testing.expectEqualStrings("yes", got.text);
+ try testing.expect(!got.cancelled);
+}
+
+test "cancelIfWaiting is a no-op when nobody is blocked" {
+ attach(testing.io, testing.allocator);
+ defer detach();
+ cancelIfWaiting();
+ reply("later", false);
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const got = try wait(arena_state.allocator());
+ try testing.expectEqualStrings("later", got.text);
+}
diff --git a/src/acp_inbox.zig b/src/acp_inbox.zig
index 152f9ed1..af09b8ca 100644
--- a/src/acp_inbox.zig
+++ b/src/acp_inbox.zig
@@ -4,6 +4,7 @@ const Io = std.Io;
const Agent = @import("agent.zig").Agent;
const proto = @import("acp_protocol.zig");
const cancel_source = @import("cancel_source.zig");
+const acp_ask = @import("acp_ask.zig");
pub const Inbox = struct {
gpa: std.mem.Allocator,
@@ -105,10 +106,24 @@ pub const Inbox = struct {
if (sid == null or std.mem.eql(u8, sid.?, current)) {
self.cancelled = true;
if (self.active) cancel_source.cancel(.acp_cancel);
+ acp_ask.cancelIfWaiting();
}
}
return;
}
+ if (std.mem.eql(u8, r.method, "session/answer")) {
+ const obj: ?std.json.ObjectMap = if (r.params) |p| (if (p == .object) p.object else null) else null;
+ const cancelled_answer = if (obj) |o| switch (o.get("cancelled") orelse .null) {
+ .bool => |b| b,
+ else => false,
+ } else false;
+ const answer_text: []const u8 = if (obj) |o| blk: {
+ const v = o.get("text") orelse break :blk "";
+ break :blk if (v == .string) v.string else "";
+ } else "";
+ acp_ask.reply(answer_text, cancelled_answer);
+ return;
+ }
if (std.mem.eql(u8, r.method, "session/prompt") and self.session_id == null)
self.session_id = try self.gpa.dupe(u8, sid orelse "");
}
@@ -167,6 +182,20 @@ test "ACP cancel interrupts active turn and does not cancel its successor" {
try std.testing.expect(!Agent.esc_cancel.load(.acquire));
}
+test "session/answer fills the ask mailbox without queueing a line" {
+ acp_ask.attach(std.testing.io, std.testing.allocator);
+ defer acp_ask.detach();
+ var reader: Io.Reader = .fixed("");
+ var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
+ defer inbox.deinit();
+ try inbox.accept("{\"method\":\"session/answer\",\"params\":{\"text\":\"pill\",\"cancelled\":false}}");
+ try std.testing.expectEqual(@as(usize, 0), inbox.lines.items.len);
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = try acp_ask.wait(arena_state.allocator());
+ try std.testing.expectEqualStrings("pill", got.text);
+}
+
test "ACP cancellation before turn setup survives the reset" {
var reader: Io.Reader = .fixed("");
var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
diff --git a/src/acp_stream.zig b/src/acp_stream.zig
index 9a9a743c..e69403a0 100644
--- a/src/acp_stream.zig
+++ b/src/acp_stream.zig
@@ -189,6 +189,18 @@ pub fn translateEvent(
try writeToolDone(w, session_id, use_id, is_error, text);
return .tool;
}
+ if (std.mem.eql(u8, typ, "ask_user")) {
+ try proto.writeNotification(w, "session/update", .{
+ .sessionId = session_id,
+ .update = .{
+ .sessionUpdate = "gui_ask_user",
+ .callId = util.strFieldObj(ev.object, "call_id") orelse "",
+ .question = util.strFieldObj(ev.object, "question") orelse "",
+ .input = ev.object.get("input") orelse Value{ .object = .empty },
+ },
+ });
+ return .notice;
+ }
return .none;
}
@@ -331,6 +343,22 @@ test "translateEvent: an id-less tool_call_started updates the announced call" {
try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"content\"") == null);
}
+test "translateEvent: ask_user becomes a gui_ask_user update" {
+ var buf: [2048]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const ev = try std.json.parseFromSlice(Value, a, "{\"type\":\"ask_user\",\"call_id\":\"q1\",\"question\":\"Which one?\",\"input\":{\"options\":[\"A\",\"B\"]}}", .{});
+ defer ev.deinit();
+ var id_buf: [64]u8 = @splat(0);
+ var next: u32 = 0;
+ try testing.expectEqual(.notice, try translateEvent(&w, "s1", ev.value, &id_buf, &next));
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "gui_ask_user") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "Which one?") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"q1\"") != null);
+}
+
test "translateEvent: reasoning and text become chunks" {
var buf: [1024]u8 = undefined;
var w: Io.Writer = .fixed(&buf);
diff --git a/src/ask_user.zig b/src/ask_user.zig
index 51d52431..f003b799 100644
--- a/src/ask_user.zig
+++ b/src/ask_user.zig
@@ -21,14 +21,10 @@ const readline = @import("readline.zig");
const protocol_seq = @import("protocol_seq.zig");
const vision = @import("vision.zig");
const vision_queue = @import("vision_queue.zig");
+const acp_ask = @import("acp_ask.zig");
/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
- const in = self.in orelse return .{
- .text = "no human is attached — make a reasonable assumption and continue",
- .is_error = true,
- };
- const w = self.out.?;
const question = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "question") orelse "(no question)") else "(no question)";
if (main_mod.json_mode) {
const call_id = if (call.id.len > 0) call.id else blk: {
@@ -37,6 +33,13 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
break :blk id;
};
try emitAskUser(self, call_id, question, call.input);
+ // ACP owns stdin (`root.in` is null); answers arrive on session/answer.
+ if (self.in == null) {
+ const got = try acp_ask.wait(self.arena);
+ if (got.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };
+ return finishAnswer(self, std.mem.trim(u8, got.text, " \t\r"));
+ }
+ const in = self.in.?;
const raw = (try json_inbox.reply(self.arena, in)) orelse return .{
.text = "user ended input without answering",
.is_error = true,
@@ -52,6 +55,11 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };
return finishAnswer(self, answer.text);
}
+ const in = self.in orelse return .{
+ .text = "no human is attached — make a reasonable assumption and continue",
+ .is_error = true,
+ };
+ const w = self.out.?;
// Skip the re-print only when the question streamed live in full.
if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});
if (tools_mod.json_args.object(call.input)) |o| if (tools_mod.json_args.arrayOf(o, "options")) |opts| {
diff --git a/src/main.zig b/src/main.zig
index bb19db93..30b05441 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("subagent_recovery.zig");
_ = @import("acp_agent_activity.zig");
_ = @import("read_image.zig");
- _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig") };
+ _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig") };
}