xonecas.io
64875
Mc

mini-coder / commit 1a7c2aa

fix: nicer headless output and todoWrite preview in TUI

xonecas2026-04-16 1a7c2aa161d48d4711b9e1cb04e9ce368f64fa81 parent 08b1a98

7 files changed

README.md+1−1
@@ -100,7 +100,7 @@ $ printf '%s\n' 'fix the failing tests' | mc
100100 - Starts when `-p/--prompt` is provided or when stdin or stdout is not a TTY.
101101 - If stdout is redirected but stdin is still interactive, pass `-p`; headless mode will not fall back to an interactive prompt.
102102 - Uses the same parser as the TUI for plain text, `/skill:name`, and standalone image paths.
103-- Writes raw NDJSON events to stdout for text deltas, tool activity, final messages, and `done` / `error` / `aborted` outcomes.
103+- With `--json`, writes NDJSON events for completed assistant/tool-result messages plus `done` / `error` / `aborted` outcomes; streaming deltas are omitted.
104104 - Headless runs still persist like normal sessions and show up in `/session` history for that working directory.
105105 - Interactive slash commands such as `/model`, `/session`, and `/help` are not available in headless mode.
106106
TODO.md+0−4
@@ -5,10 +5,6 @@ Don't keep completed items bloating the file, remove them before committing.
55 Keep the file structured and minimal.
66 The spec.md and code are the sources of truth, not this file, don't assume anything because it's documented here.
77
8-## Open items
9-
10-- [ ] headless mode with --json should only output completed messages and not delta messages.
11-
128 ## Forge comparison follow-ups (high-value gaps, highest priority first)
139
1410 - [x] Add first-class todo tools plus prompt/UI integration so the agent can track and complete work explicitly instead of relying only on a `/tmp` file (`src/tools.ts`, `src/agent.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
spec.md+3−9
@@ -798,24 +798,18 @@ In headless mode without `--json`, stdout contains only the final persisted assi
798798
799799 With `--json`, stdout is a newline-delimited JSON stream (NDJSON). Each line is one JSON object with a `type` field.
800800
801-This stream is intentionally raw and close to the internal agent event protocol rather than a flattened summary format. It carries the streaming event payloads needed to observe the full run, including text deltas, thinking deltas, tool-call progress, tool execution progress, persisted assistant/tool-result messages, and terminal events.
801+This stream is intentionally close to the persisted agent event protocol rather than a flattened summary format, but it only includes completed events. Streaming text/thinking deltas, tool-call assembly events, and tool progress updates are omitted so scripts do not receive duplicate partial content.
802802
803803 At minimum, the streamed event types are:
804804
805-- `text_delta`
806-- `thinking_delta`
807-- `toolcall_start`
808-- `toolcall_delta`
809-- `toolcall_end`
810805 - `assistant_message`
811-- `tool_start`
812-- `tool_delta`
813-- `tool_end`
814806 - `tool_result`
815807 - `done`
816808 - `error`
817809 - `aborted`
818810
811+Queued/persisted `user_message` events may also appear when the loop injects an additional user message before the next model boundary.
812+
819813 Event payload fields use the same JSON-serializable shapes as the in-process agent stream and persisted pi-ai message content where applicable. No terminal-only formatting, status bar text, markdown rendering, or other TUI presentation output is written to stdout in this mode.
820814
821815 A successful one-shot run continues through any assistant/tool loops and ends only when the agent loop emits `done` (with `stopReason: "stop"` or `"length"`). Errors and user interrupts terminate the stream with `error` or `aborted` respectively.
src/headless.test.ts+18−14
@@ -71,7 +71,7 @@ function parseEventLines(lines: string[]): Array<Record<string, unknown>> {
7171 }
7272
7373 describe("headless", () => {
74- test("runHeadlessPrompt streams NDJSON events and persists the completed turn", async () => {
74+ test("runHeadlessPrompt streams only completed NDJSON events and persists the completed turn", async () => {
7575 faux.setResponses([
7676 fauxAssistantMessage([
7777 fauxThinking("Need to inspect the failing test."),
@@ -89,11 +89,10 @@ describe("headless", () => {
8989
9090 const events = parseEventLines(lines);
9191 expect(stopReason).toBe("stop");
92- expect(events.some((event) => event.type === "thinking_delta")).toBe(true);
93- expect(events.some((event) => event.type === "assistant_message")).toBe(
94- true,
95- );
96- expect(events.at(-1)?.type).toBe("done");
92+ expect(events.map((event) => event.type)).toEqual([
93+ "assistant_message",
94+ "done",
95+ ]);
9796
9897 const sessionId = state.session?.id;
9998 if (!sessionId) {
@@ -174,7 +173,7 @@ describe("headless", () => {
174173 expect(listPromptHistory(state.db, 1)).toEqual([]);
175174 });
176175
177- test("runHeadlessPrompt streams tool execution events for tool-use turns", async () => {
176+ test("runHeadlessPrompt streams only completed events for tool-use turns", async () => {
178177 faux.setResponses([
179178 fauxAssistantMessage(
180179 [fauxToolCall("shell", { command: "printf tool-output" })],
@@ -193,10 +192,12 @@ describe("headless", () => {
193192
194193 const events = parseEventLines(lines);
195194 expect(stopReason).toBe("stop");
196- expect(events.some((event) => event.type === "tool_start")).toBe(true);
197- expect(events.some((event) => event.type === "tool_delta")).toBe(true);
198- expect(events.some((event) => event.type === "tool_end")).toBe(true);
199- expect(events.some((event) => event.type === "tool_result")).toBe(true);
195+ expect(events.map((event) => event.type)).toEqual([
196+ "assistant_message",
197+ "tool_result",
198+ "assistant_message",
199+ "done",
200+ ]);
200201
201202 const sessionId = state.session?.id;
202203 if (!sessionId) {
@@ -221,7 +222,7 @@ describe("headless", () => {
221222 writeLine: (line) => {
222223 lines.push(line);
223224 const event = JSON.parse(line) as { type?: string };
224- if (event.type === "tool_start") {
225+ if (event.type === "assistant_message") {
225226 state.abortController?.abort();
226227 }
227228 },
@@ -229,8 +230,11 @@ describe("headless", () => {
229230
230231 const events = parseEventLines(lines);
231232 expect(stopReason).toBe("aborted");
232- expect(events.some((event) => event.type === "tool_result")).toBe(true);
233- expect(events.at(-1)?.type).toBe("aborted");
233+ expect(events.map((event) => event.type)).toEqual([
234+ "assistant_message",
235+ "tool_result",
236+ "aborted",
237+ ]);
234238
235239 const abortedEvent = events.at(-1);
236240 const message = abortedEvent?.message;
src/headless.ts+23−4
@@ -5,6 +5,7 @@
55 */
66
77 import type { AssistantMessage, UserMessage } from "@mariozechner/pi-ai";
8+import type { AgentEvent } from "./agent.ts";
89 import type { AppState } from "./index.ts";
910 import {
1011 resolveRawInput,
@@ -20,7 +21,7 @@ type HeadlessStopReason = "stop" | "length" | "error" | "aborted";
2021
2122 /** Options for a headless NDJSON run. */
2223 export interface HeadlessRunOptions {
23- /** Optional line writer for NDJSON event output. */
24+ /** Optional line writer for completed NDJSON event output. */
2425 writeLine?: (line: string) => void;
2526 }
2627
@@ -109,6 +110,20 @@ function extractAssistantText(message: AssistantMessage | null): string {
109110 .join("");
110111 }
111112
113+function shouldWriteHeadlessJsonEvent(event: AgentEvent): boolean {
114+ switch (event.type) {
115+ case "user_message":
116+ case "assistant_message":
117+ case "tool_result":
118+ case "done":
119+ case "error":
120+ case "aborted":
121+ return true;
122+ default:
123+ return false;
124+ }
125+}
126+
112127 function createHeadlessOutputController(
113128 state: AppState,
114129 writeImpl: (text: string) => void,
@@ -168,11 +183,12 @@ function createHeadlessOutputController(
168183 }
169184
170185 /**
171- * Run a single headless prompt to completion and stream NDJSON events.
186+ * Run a single headless prompt to completion and stream completed NDJSON events.
172187 *
173188 * The raw input is parsed with the same rules as interactive input. Slash
174- * commands are rejected in headless mode. Assistant/tool events are written as
175- * one JSON object per line.
189+ * commands are rejected in headless mode. Persisted messages and terminal
190+ * events are written as one JSON object per line; streaming delta/progress
191+ * events are omitted.
176192 *
177193 * @param state - Mutable application state for the run.
178194 * @param rawInput - Exact raw prompt text supplied by the user.
@@ -191,6 +207,9 @@ export async function runHeadlessPrompt(
191207 );
192208 const hooks: SubmitTurnHooks = {
193209 onEvent: (event) => {
210+ if (!shouldWriteHeadlessJsonEvent(event)) {
211+ return;
212+ }
194213 output.write(JSON.stringify(event));
195214 },
196215 };
src/ui/conversation.test.ts+27−0
@@ -1057,6 +1057,33 @@ describe("ui/conversation", () => {
10571057 expect(text).not.toContain("{");
10581058 });
10591059
1060+ test("renderAssistantMessage for a todoWrite tool call shows a todo-count summary instead of raw JSON", () => {
1061+ // Arrange
1062+ const assistant = {
1063+ content: [
1064+ fauxToolCall(
1065+ "todoWrite",
1066+ {
1067+ todos: [
1068+ { content: "Inspect headless JSON output", status: "completed" },
1069+ { content: "Update the TUI preview", status: "in_progress" },
1070+ ],
1071+ },
1072+ { id: "tool-1" },
1073+ ),
1074+ ],
1075+ };
1076+
1077+ // Act
1078+ const text = collectText(renderAssistantMessage(assistant, RENDER_OPTS));
1079+
1080+ // Assert
1081+ expect(text).toContain("todo write ->");
1082+ expect(text).toContain("Updating todos... 2 todos updated");
1083+ expect(text).not.toContain("{");
1084+ expect(text).not.toContain('"todos"');
1085+ });
1086+
10601087 test("renderAssistantMessage for an edit tool call shows both old and new content without diff prefixes", () => {
10611088 // Arrange
10621089 const assistant = {
src/ui/conversation.ts+20−0
@@ -415,6 +415,12 @@ function getToolArgString(args: Record<string, unknown>, key: string): string {
415415 return typeof value === "string" ? value : "";
416416 }
417417
418+function formatTodoWriteCallSummary(args: Record<string, unknown>): string {
419+ const todoCount = Array.isArray(args.todos) ? args.todos.length : 0;
420+ const todoLabel = todoCount === 1 ? "todo" : "todos";
421+ return `Updating todos... ${todoCount} ${todoLabel} updated`;
422+}
423+
418424 /** Strip shell execution labels and normalize the exit line for the UI. */
419425 function normalizeShellOutput(output: string): string {
420426 return output
@@ -918,6 +924,17 @@ function buildEditToolCallSpec(args: Record<string, unknown>): ToolBlockSpec {
918924 };
919925 }
920926
927+function buildTodoWriteToolCallSpec(
928+ args: Record<string, unknown>,
929+): ToolBlockSpec {
930+ return {
931+ toolName: "todoWrite",
932+ direction: "->",
933+ bodyLines: [{ kind: "text", text: formatTodoWriteCallSummary(args) }],
934+ previewBody: false,
935+ };
936+}
937+
921938 function buildReadImageToolCallSpec(
922939 args: Record<string, unknown>,
923940 ): ToolBlockSpec {
@@ -953,6 +970,9 @@ function buildToolCallSpec(
953970 if (toolName === "edit") {
954971 return buildEditToolCallSpec(args);
955972 }
973+ if (toolName === "todoWrite") {
974+ return buildTodoWriteToolCallSpec(args);
975+ }
956976 if (toolName === "readImage") {
957977 return buildReadImageToolCallSpec(args);
958978 }