Skip to content

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

Python

fix(acp): idle peer mail starts a turn; drop rendered-view chrome

justrachb315540163bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 94afb580..810a4244 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ current is part of cutting a release.
- Opt-in Accord Unix 0600 live path behind `presence_chan.postMessage` (`GRAFF_ACCORD=1`); JSONL stays the durable room (ADR 0134).
- `#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).
+- `#1007`: idle `graff acp` sessions start that same turn; `peer_message` no longer claims delivery waits for a step boundary.
+- `#1006`: rendered views sit in the transcript without product chrome; desktop appearance tokens ride the turn (ADR 0135).
+- `#1007`: idle `graff acp` sessions start that same turn; `peer_message` no longer claims delivery waits for a step boundary.
+- `#1006`: rendered views sit in the transcript without product chrome; desktop appearance tokens ride the turn (ADR 0135).
- Live 12-PR board on grok-4.6 SuperGrok (n=3, no SPEC.md): graff / Pi /
OpenCode 12/12, grok 11/12 (`#727`), exo 9/12 (gemini + two turbos —
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index 68b0c507..b8bf9bcb 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -324,6 +324,21 @@ export async function POST(req: NextRequest) {
await endTurn(slot);
return Response.json({ ok: true });
}
+ if (method === "session/idle") {
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ const send = (line: string) => {
+ if (slot.streaming) return;
+ try { controller.enqueue(encoder.encode(`${line}\n`)); } catch { /* closed */ }
+ };
+ const stop = slot.transport.subscribe(send);
+ const close = () => { stop(); try { controller.close(); } catch { /* already closed */ } };
+ req.signal.addEventListener("abort", close, { once: true });
+ },
+ });
+ return new Response(stream, { headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" } });
+ }
if (method === "session/prompt") {
if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });
const promptParams = await prepareGuiPrompt(body.params);
diff --git a/apps/native/components/site/SnapshotView.tsx b/apps/native/components/site/SnapshotView.tsx
index eced4b82..963dda1f 100644
--- a/apps/native/components/site/SnapshotView.tsx
+++ b/apps/native/components/site/SnapshotView.tsx
@@ -38,11 +38,23 @@ export default function SnapshotView({kind, id}: {kind: SnapshotKind; id: string
}, [kind]);
if (!validAppId(id)) return null;
const {label, title, src, sandbox, allow} = KINDS[kind];
+ const iframe = (kind !== "view" || nearby) && <iframe title={title} src={src(id)} sandbox={sandbox} allow={allow}
+ referrerPolicy="no-referrer"
+ className={kind === "view" ? "block h-full w-full border-0 bg-transparent" : "block h-[620px] w-full border-0"} />;
+ const toggle = <button type="button" className="text-[11px] text-ink-3" onClick={()=>setVisible(!visible)} aria-expanded={visible}>{visible ? "Close view" : "Open view"}</button>;
+ // #1006: a model-drawn page is a figure in the turn, not a labeled product card.
+ if (kind === "view") {
+ return <section ref={host} className="group relative my-3 w-full" aria-label={label}>
+ {visible
+ ? <div className="pointer-events-none absolute right-1 top-1 z-10 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"><span className="pointer-events-auto">{toggle}</span></div>
+ : toggle}
+ {visible && <div className="w-full bg-transparent" style={{height: "min(70vh, 32rem)"}}>{iframe}</div>}
+ </section>;
+ }
return <section ref={host} className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label={label}>
<div className="flex items-center justify-between px-3 py-2 text-xs text-ink-3">
- <span>{label}</span><button type="button" onClick={()=>setVisible(!visible)} aria-expanded={visible}>{visible ? "Close view" : "Open view"}</button>
+ <span>{label}</span>{toggle}
</div>
- {visible && <div className="h-[620px]">{(kind !== "view" || nearby) && <iframe title={title} src={src(id)} sandbox={sandbox} allow={allow}
- referrerPolicy="no-referrer" className="block h-[620px] w-full border-0" />}</div>}
+ {visible && <div className="h-[620px]">{iframe}</div>}
</section>;
}
diff --git a/apps/native/components/site/idle-peer-turns.ts b/apps/native/components/site/idle-peer-turns.ts
new file mode 100644
index 00000000..6e048890
--- /dev/null
+++ b/apps/native/components/site/idle-peer-turns.ts
@@ -0,0 +1,45 @@
+import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
+import { idleUpdates, type ChatHandle } from "@/lib/acp-client";
+import type { Chat } from "./harness-types";
+
+/** Paint unsolicited ACP session/update while a tab is idle (#1007). */
+export async function pumpIdlePeerTurns(opts: {
+ chatId: number;
+ handle: ChatHandle;
+ sessionId: string;
+ signal: AbortSignal;
+ running(): boolean;
+ setChats(update: (current: Chat[]) => Chat[]): void;
+}): Promise<void> {
+ let asstId: number | undefined;
+ try {
+ for await (const update of idleUpdates(opts.handle, opts.sessionId, opts.signal)) {
+ if (opts.running() || opts.signal.aborted) continue;
+ opts.setChats(current => current.map(chat => {
+ if (chat.id !== opts.chatId) return chat;
+ const existing = asstId != null
+ ? chat.messages.find(message => message.role === "assistant" && message.id === asstId)
+ : undefined;
+ let messages = chat.messages;
+ let id = asstId;
+ let turn: AssistantTurn = existing && existing.role === "assistant" ? existing.turn : emptyTurn();
+ if (!existing) {
+ id = Date.now();
+ asstId = id;
+ messages = [...chat.messages, { id, role: "assistant", turn }];
+ }
+ turn = applyAcpUpdate(turn, update);
+ if (update.sessionUpdate === "gui_turn_end") {
+ turn = finishAcpTurn(turn);
+ asstId = undefined;
+ }
+ return {
+ ...chat,
+ messages: messages.map(message => message.role === "assistant" && message.id === id ? { ...message, turn } : message),
+ };
+ }));
+ }
+ } catch {
+ if (opts.signal.aborted) return;
+ }
+}
diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.ts
index c6050c13..9fdad9b6 100644
--- a/apps/native/components/site/useHarnessSessions.ts
+++ b/apps/native/components/site/useHarnessSessions.ts
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState, type MutableRefObject, type Dispatch, type SetStateAction } from "react";
import { checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";
+import { pumpIdlePeerTurns } from "./idle-peer-turns";
import type { AcpCommand } from "@/lib/acp";
import type { PromptModel } from "@/components/primitives/PromptBar";
import { listSessionsPage, type StoredSession } from "@/lib/sessions";
@@ -22,6 +23,16 @@ type Props = {
const SIDEBAR_PAGE = 12;
export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal}: Props) {
const [projectsReady, setProjectsReady] = useState(false);
+ const idleCtl = useRef(new Map<number, AbortController>());
+ const watchIdle = (chatId: number, sessionId: string) => {
+ idleCtl.current.get(chatId)?.abort();
+ const ac = new AbortController();
+ idleCtl.current.set(chatId, ac);
+ void pumpIdlePeerTurns({
+ chatId, handle: handleOf(chatId), sessionId, signal: ac.signal,
+ running: () => runningRef.current.has(chatId), setChats,
+ });
+ };
const adoptCatalog = async (chatId: number) => {
// Use the provider and model actually resolved by graff.
try {
@@ -74,6 +85,7 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
});
sessionsRef.current.set(chatId, id);
setSessionIds((current) => ({ ...current, [chatId]: id }));
+ watchIdle(chatId, id);
// Populate the command menu from this agent's advertisement.
if (commands.length > 0) setCommands((current) => ({ ...current, [chatId]: commands }));
setHealth({ ok: true });
@@ -134,6 +146,8 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
return () => {
cancelled = true;
window.removeEventListener("pagehide", reap);
+ for (const ac of idleCtl.current.values()) ac.abort();
+ idleCtl.current.clear();
};
// The first tab's agent is spawned once per mount; later tabs spawn their
// own on creation, and a model change respawns only the active tab's.
diff --git a/apps/native/e2e/views.pw.ts b/apps/native/e2e/views.pw.ts
index 350f399f..34096750 100644
--- a/apps/native/e2e/views.pw.ts
+++ b/apps/native/e2e/views.pw.ts
@@ -31,6 +31,8 @@ test('a model-drawn page renders inline in a sandbox that cannot reach the app o
const id=await snapshot(drawn);
await page.goto(`/visual-tests/views?id=${id}`);
await expect(page.locator('section[aria-label="Rendered view"]')).toBeVisible();
+ await expect(page.locator('section[aria-label="Rendered view"]')).not.toHaveClass(/border/);
+ await expect(page.getByText('Rendered view',{exact:true})).toHaveCount(0);
const app=page.frameLocator('iframe');
// Rendered, with its own inline script and style — a page, not a screenshot.
await expect(app.locator('h1')).toHaveText('Revision burn-down');
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index 82901f99..acf9794b 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -1,4 +1,5 @@
import { parseRpcLine, type AcpCommand, type AcpUpdate, type JsonRpcLine } from "./acp";
+import { liveAppearanceTokens } from "./appearance-note";
const BASE = "/api/acp";
@@ -106,9 +107,11 @@ export async function* prompt(
sessionId: string,
text: string,
): AsyncGenerator<AcpUpdate> {
+ const appearance = liveAppearanceTokens();
const res = await rpc(chat, "session/prompt", {
sessionId,
prompt: [{ type: "text", text }],
+ ...(appearance ? { appearance } : {}),
}, true);
let terminal = false;
for await (const line of ndjson(res)) {
@@ -128,6 +131,28 @@ export async function* prompt(
if (!terminal) throw new Error("ACP stream ended before session/prompt returned");
}
+/** Unsolicited session/update while the tab is idle (#1007). Ends on abort. */
+export async function* idleUpdates(
+ chat: ChatHandle,
+ sessionId: string,
+ signal?: AbortSignal,
+): AsyncGenerator<AcpUpdate> {
+ const res = await fetch(BASE, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ chat, method: "session/idle", params: { sessionId }, stream: true }),
+ cache: "no-store",
+ signal,
+ });
+ if (!res.ok) {
+ const detail = await res.text().catch(() => "");
+ throw new Error(`ACP session/idle → ${res.status}: ${detail.slice(0, 240)}`);
+ }
+ for await (const line of ndjson(res)) {
+ if ("method" in line && line.method === "session/update") yield line.params.update;
+ }
+}
+
export async function cancel(chat: ChatHandle, sessionId: string): Promise<void> {
const response = await fetch(BASE, {
method: "POST",
diff --git a/apps/native/lib/acp-transport.ts b/apps/native/lib/acp-transport.ts
index a281ee51..deb333f2 100644
--- a/apps/native/lib/acp-transport.ts
+++ b/apps/native/lib/acp-transport.ts
@@ -51,6 +51,10 @@ export class AcpTransport {
}
abort(error: Error) { this.fail(error); }
get usable(): boolean { return this.failure === null; }
+ subscribe(fn: (line: string) => void): () => void {
+ this.listeners.add(fn);
+ return () => { this.listeners.delete(fn); };
+ }
notify(method: string, params?: unknown) {
if (this.failure) throw this.failure;
this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method, params }) + "\n");
diff --git a/apps/native/lib/appearance-note.ts b/apps/native/lib/appearance-note.ts
new file mode 100644
index 00000000..53320a9e
--- /dev/null
+++ b/apps/native/lib/appearance-note.ts
@@ -0,0 +1,42 @@
+import { colorTokens } from "./custom-themes";
+
+/** Turn-local desktop palette for `render_html` (#1006). Not the system prompt
+ * and not the tool catalog — those hashes must stay stable across appearance
+ * switches. The ACP client puts the live tokens on `session/prompt`. */
+export function parseAppearance(value: unknown): Record<string, string> | undefined {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const out: Record<string, string> = {};
+ for (const token of colorTokens) {
+ const raw = (value as Record<string, unknown>)[token];
+ if (typeof raw === "string" && raw.trim()) out[token] = raw.trim();
+ }
+ return Object.keys(out).length ? out : undefined;
+}
+
+export function appearanceNote(tokens: Record<string, string>): string {
+ const css = colorTokens
+ .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}`;
+}
+
+export function withAppearanceNote<T extends { prompt?: unknown }>(params: T, tokens: Record<string, string>): T {
+ if (!Array.isArray(params.prompt)) return params;
+ const prompt = params.prompt.map((block: { type?: string; text?: string }) => ({ ...block }));
+ const first = prompt.find(block => block.type === "text" && typeof block.text === "string");
+ if (!first || typeof first.text !== "string") return params;
+ first.text = `${first.text}\n\n${appearanceNote(tokens)}`;
+ return { ...params, prompt };
+}
+
+export function liveAppearanceTokens(): Record<string, string> | undefined {
+ if (typeof document === "undefined") return undefined;
+ const style = getComputedStyle(document.documentElement);
+ const out: Record<string, string> = {};
+ for (const token of colorTokens) {
+ const value = style.getPropertyValue(`--${token}`).trim();
+ if (value) out[token] = value;
+ }
+ return Object.keys(out).length ? out : undefined;
+}
diff --git a/apps/native/lib/gui-skill-context.ts b/apps/native/lib/gui-skill-context.ts
index 762615c0..07984a75 100644
--- a/apps/native/lib/gui-skill-context.ts
+++ b/apps/native/lib/gui-skill-context.ts
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { selectedGuiSkills, withGuiSkillContext } from "./gui-skills";
+import { appearanceNote, parseAppearance } from "./appearance-note";
import { themeDirectory } from "./theme-files";
function mcpConfigPaths() {
@@ -21,17 +22,29 @@ function extraFor(id: string): string {
export async function prepareGuiPrompt(params: Record<string, unknown> | undefined) {
if (!Array.isArray(params?.prompt)) return params;
+ const tokens = parseAppearance(params.appearance);
const selected = new Set<string>();
// Explicit mentions in user text only: attachments never activate a skill.
for (const block of params.prompt) if (block?.type === "text" && typeof block.text === "string") for (const skill of selectedGuiSkills(block.text)) selected.add(skill.id);
- if (!selected.size) return params;
- const instructions = await Promise.all([...selected].map(async id => {
- const text = await readFile(path.join(process.cwd(), "skills", id, "SKILL.md"), "utf8");
- const extra = extraFor(id);
- return `GUI skill: ${id}\n${text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")}${extra ? `\n${extra}` : ""}`;
- }));
+ if (!selected.size && !tokens) return params;
const prompt = params.prompt.map(block => ({ ...block }));
const first = prompt.find(block => block.type === "text" && typeof block.text === "string");
- first.text = withGuiSkillContext(first.text, instructions.join("\n\n"));
- return { ...params, prompt };
+ if (!first || typeof first.text !== "string") {
+ if (!tokens) return params;
+ const next = { ...params };
+ delete next.appearance;
+ return next;
+ }
+ if (selected.size) {
+ const instructions = await Promise.all([...selected].map(async id => {
+ const text = await readFile(path.join(process.cwd(), "skills", id, "SKILL.md"), "utf8");
+ const extra = extraFor(id);
+ return `GUI skill: ${id}\n${text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")}${extra ? `\n${extra}` : ""}`;
+ }));
+ first.text = withGuiSkillContext(first.text, instructions.join("\n\n"));
+ }
+ if (tokens) first.text = `${first.text}\n\n${appearanceNote(tokens)}`;
+ const next = { ...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 d9d5a342..de61df57 100644
--- a/apps/native/lib/gui-skills.test.ts
+++ b/apps/native/lib/gui-skills.test.ts
@@ -27,6 +27,17 @@ test("ordinary prompts and file attachments do not load GUI skills", async () =>
const original = { prompt: [{ type: "text", text: "Read the project" }, { type: "resource_link", name: "$theme", uri: "file:///fixture" }] };
expect(await prepareGuiPrompt(original)).toBe(original);
});
+test("desktop appearance tokens ride the prompt and leave the catalog alone", async () => {
+ const original = { prompt: [{ type: "text", text: "Draw the burn-down" }], appearance: { page: "#faf8f5", surface: "#ffffff", ink: "#1a1a1a" } };
+ const prepared = await prepareGuiPrompt(original);
+ const text = (prepared?.prompt as { text: string }[])[0].text;
+ expect(text.startsWith("Draw the burn-down")).toBe(true);
+ expect(text).toContain("[desktop appearance]");
+ expect(text).toContain("--page: #faf8f5");
+ expect(text).toContain("--surface: #ffffff");
+ expect(prepared).not.toHaveProperty("appearance");
+ expect(original.prompt[0].text).toBe("Draw the burn-down");
+});
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/docs/adr/0134-accord-live-jsonl-durable.md b/docs/adr/0134-accord-live-jsonl-durable.md
index 154fe584..866c1d67 100644
--- a/docs/adr/0134-accord-live-jsonl-durable.md
+++ b/docs/adr/0134-accord-live-jsonl-durable.md
@@ -17,6 +17,7 @@ Do not replace the room with Mailbox.
## Consequences
-Idle TUI and line-REPL sessions auto-start a turn on new parked peer mail (#1001), one
-batch at a time; `action=inbox` resets the latch. Flipping GRAFF_ACCORD
+Idle TUI, line-REPL, and `graff acp` sessions auto-start a turn on new parked
+peer mail (#1001, #1007), one batch at a time; `action=inbox` resets the latch.
+An in-flight prompt is not preempted (#430). Flipping GRAFF_ACCORD
does not change history pull (ADR 0004).
diff --git a/docs/adr/0135-desktop-appearance-is-a-turn-note.md b/docs/adr/0135-desktop-appearance-is-a-turn-note.md
new file mode 100644
index 00000000..f4e8692c
--- /dev/null
+++ b/docs/adr/0135-desktop-appearance-is-a-turn-note.md
@@ -0,0 +1,29 @@
+# 0135. Desktop appearance for drawn pages is a turn-local note
+
+Status: accepted 2026-09-17
+
+## Context
+
+`render_html` snapshots run in an opaque origin (ADR 0107), so they cannot read
+the desktop's CSS variables. Putting the live palette in `prompt_text` or the
+`render_html` tool schema would change the cached prefix / toolset hash on every
+appearance switch.
+
+A labeled "Rendered view" card also framed the page in a 620px product well,
+so a cream desktop got a dark slab (or the reverse) instead of a figure in the
+turn (#1006).
+
+## Decision
+
+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.
+
+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.
+
+## 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.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 0a6eb7d6..4e50b74b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -154,6 +154,7 @@ record only when you need the evidence or the edge cases.
| [0133](0133-publication-review-binds-committed-inputs.md) | Proposed: non-draft publication reviews immutable source and observed checks; changed inputs invalidate earlier assessments. |
| [0134](0134-accord-live-jsonl-durable.md) | JSONL is the durable peer room; Accord Unix 0600 is opt-in live behind postMessage. |
+| [0135](0135-desktop-appearance-is-a-turn-note.md) | Desktop appearance tokens for `render_html` ride the turn, never the prefix or tool catalog. |
## When to write one
diff --git a/docs/rendered-views.md b/docs/rendered-views.md
index f1d232c0..d4f1edbe 100644
--- a/docs/rendered-views.md
+++ b/docs/rendered-views.md
@@ -8,8 +8,11 @@ nothing opens automatically: the model chooses to draw, and the turn is still
the turn.
The view keeps its own inline `<style>` and `<script>`, so a page can be
-animated or interactive. Close view / Open view disposes and restores the
-frame without touching the conversation.
+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 0135).
## Where the page lives
diff --git a/src/acp.zig b/src/acp.zig
index 4476e622..6f2d595e 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -199,11 +199,16 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
.extra = liveModels,
};
while (true) {
- const line = (inbox.next(arena) catch break) orelse break;
- handleLine(&d, arena, out, line) catch |err| {
- std.debug.print("acp: dispatch failed: {t}\n", .{err});
- break;
- };
+ const event = (inbox.wait(arena) catch break) orelse break;
+ switch (event) {
+ .tick => @import("acp_idle.zig").maybeWake(&d, arena, out, io) catch |err| {
+ std.debug.print("acp: idle wake failed: {t}\n", .{err});
+ },
+ .line => |line| handleLine(&d, arena, out, line) catch |err| {
+ std.debug.print("acp: dispatch failed: {t}\n", .{err});
+ break;
+ },
+ }
out.flush() catch break;
}
session.saveSession(root, arena, root.session_name) catch {};
diff --git a/src/acp_idle.zig b/src/acp_idle.zig
new file mode 100644
index 00000000..d870562a
--- /dev/null
+++ b/src/acp_idle.zig
@@ -0,0 +1,86 @@
+//! #1007: idle ACP roots start a turn on parked peer mail, same latch as TUI/REPL.
+//! No `session/prompt` request id — the client did not send one. Mid-turn
+//! preemption stays out of scope (#430): this only runs between prompts.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const engine = @import("acp_engine.zig");
+const proto = @import("acp_protocol.zig");
+const peer_idle = @import("peer_idle.zig");
+const peer_inbox = @import("peer_inbox.zig");
+
+pub fn maybeWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, io: Io) !void {
+ const sid = d.session_id orelse return;
+ if (sid.len == 0) return;
+ var buf: [512]u8 = undefined;
+ const wake = peer_idle.takeIdleWake(io, &buf) orelse return;
+ try promptWake(d, arena, w, wake);
+}
+
+pub fn promptWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, wake: []const u8) !void {
+ const sid = d.session_id orelse return;
+ if (sid.len == 0 or wake.len == 0) return;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(.{
+ .jsonrpc = "2.0",
+ .method = "session/prompt",
+ .params = .{
+ .sessionId = sid,
+ .prompt = .{.{ .type = "text", .text = wake }},
+ },
+ });
+ try engine.handleLine(d, arena, w, aw.writer.buffered());
+ try proto.writeNotification(w, "session/update", .{
+ .sessionId = sid,
+ .update = .{
+ .sessionUpdate = "gui_turn_end",
+ .stopReason = "end_turn",
+ },
+ });
+}
+
+fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
+ return std.fmt.allocPrint(arena, "echo:{s}", .{text});
+}
+
+test "#1007 idle wake without a request id streams the turn and no RPC result" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var buf: [4096]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined, .session_id = "s1" };
+ try promptWake(&d, a, &w, "[peer] 1 unread");
+ const out = w.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, out, "echo:[peer] 1 unread") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "gui_turn_end") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "\"id\"") == null);
+}
+
+test "#1007 maybeWake is silent without a session or mail" {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ peer_idle.resetForTest();
+ }
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var buf: [256]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined };
+ try maybeWake(&d, arena.allocator(), &w, std.testing.io);
+ try std.testing.expectEqual(@as(usize, 0), w.buffered().len);
+ d.session_id = "s1";
+ try maybeWake(&d, arena.allocator(), &w, std.testing.io);
+ try std.testing.expectEqual(@as(usize, 0), w.buffered().len);
+}
diff --git a/src/acp_inbox.zig b/src/acp_inbox.zig
index 982d71d7..3a63fbc1 100644
--- a/src/acp_inbox.zig
+++ b/src/acp_inbox.zig
@@ -16,15 +16,24 @@ pub const Inbox = struct {
session_id: ?[]u8 = null,
cancelled: bool = false,
active: bool = false,
+ tick: bool = false,
future: ?Io.Future(void) = null,
+ tick_future: ?Io.Future(void) = null,
+
+ pub const Event = union(enum) {
+ line: []const u8,
+ tick,
+ };
pub fn start(self: *Inbox) !void {
// async may run the endless reader inline when its worker quota is
// busy, preventing the dispatcher from ever answering initialize.
self.future = try self.io.concurrent(pump, .{self});
+ self.tick_future = try self.io.concurrent(tickPump, .{self});
}
pub fn deinit(self: *Inbox) void {
+ if (self.tick_future) |*f| f.cancel(self.io);
if (self.future) |*f| f.cancel(self.io);
for (self.lines.items) |line| self.gpa.free(line);
self.lines.deinit(self.gpa);
@@ -42,6 +51,25 @@ pub const Inbox = struct {
return try arena.dupe(u8, line);
}
+ /// Idle loop: a stdin line, a 200ms poll tick, or EOF (`null`).
+ /// A queued line always wins over a tick so a prompt is never delayed.
+ pub fn wait(self: *Inbox, arena: std.mem.Allocator) !?Event {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ while (self.lines.items.len == 0 and !self.eof and !self.tick)
+ self.ready.waitUncancelable(self.io, &self.mutex);
+ if (self.lines.items.len > 0) {
+ const line = self.lines.orderedRemove(0);
+ defer self.gpa.free(line);
+ return .{ .line = try arena.dupe(u8, line) };
+ }
+ if (self.tick) {
+ self.tick = false;
+ return .tick;
+ }
+ return null;
+ }
+
/// Called after prepareRootTurn, under the same lock as incoming cancel.
pub fn begin(self: *Inbox) void {
self.mutex.lockUncancelable(self.io);
@@ -100,6 +128,18 @@ pub const Inbox = struct {
self.ready.broadcast(self.io);
self.mutex.unlock(self.io);
}
+
+ fn tickPump(self: *Inbox) void {
+ while (true) {
+ self.io.sleep(.fromMilliseconds(200), .awake) catch break;
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (self.eof) break;
+ if (self.active) continue;
+ self.tick = true;
+ self.ready.broadcast(self.io);
+ }
+ }
};
test "ACP cancel interrupts active turn and does not cancel its successor" {
@@ -132,3 +172,26 @@ test "ACP cancellation before turn setup survives the reset" {
inbox.begin();
try std.testing.expect(Agent.esc_cancel.load(.acquire));
}
+
+test "#1007 wait prefers a queued line over a poll tick" {
+ var reader: Io.Reader = .fixed("");
+ var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
+ defer inbox.deinit();
+ inbox.tick = true;
+ try inbox.accept("{\"method\":\"session/prompt\"}");
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const ev = (try inbox.wait(arena.allocator())) orelse return error.ExpectedLine;
+ try std.testing.expect(ev == .line);
+}
+
+test "#1007 wait returns a tick when idle" {
+ var reader: Io.Reader = .fixed("");
+ var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
+ defer inbox.deinit();
+ inbox.tick = true;
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const ev = (try inbox.wait(arena.allocator())) orelse return error.ExpectedTick;
+ try std.testing.expect(ev == .tick);
+}
diff --git a/src/main.zig b/src/main.zig
index fddfcf22..2a2f30d4 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -590,7 +590,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("goal_flow.zig");
_ = @import("goal_todo.zig");
_ = @import("goal_pacing.zig");
- _ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };
+ _ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };
_ = @import("acp_agents.zig");
_ = @import("subagent_activity.zig");
_ = @import("subagent_recovery.zig");
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index b0fa4d79..67926528 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -130,12 +130,12 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {
.is_error = true,
};
if (to.len == 0) return .{
- .text = "posted to this folder's room — every live session here hears it at their next step boundary. Set session to DM one peer instead.",
+ .text = "posted to this folder's room — every live idle session here starts a turn. A busy one reads it when that turn ends. Set session to DM one peer instead.",
.is_error = false,
};
const via: []const u8 = if (cross_folder) "device room" else "this folder";
return .{
- .text = try std.fmt.allocPrint(self.arena, "DM to \"{s}\" via the {s} — only they hear it, at their next step boundary. Re-ping with session=\"{s}\".", .{ to, via, to }),
+ .text = try std.fmt.allocPrint(self.arena, "DM to \"{s}\" via the {s} — only they hear it. An idle root starts a turn; a busy one waits until that turn ends. Re-ping with session=\"{s}\".", .{ to, via, to }),
.is_error = false,
};
}