xonecas.io
64875
Mc

mini-coder / commit 3484bf3

refactor: simplify cli startup and shell rendering

xonecas2026-03-15 3484bf341f87afaa7533ea7fec8b4932a5122d0e parent 950a980

5 files changed

src/cli/output.test.ts+11−1
@@ -1,5 +1,5 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2-import { CliReporter, renderUserMessage } from "./output.ts";
2+import { CliReporter, renderBanner, renderUserMessage } from "./output.ts";
33 import { terminal } from "./terminal-io.ts";
44
55 let stdout = "";
@@ -39,6 +39,16 @@ describe("renderUserMessage", () => {
3939 });
4040 });
4141
42+describe("renderBanner", () => {
43+ test("uses a tilde path in the header", () => {
44+ captureStdout();
45+
46+ renderBanner("zen/gpt-5.4", `${process.env.HOME}/src/mini-coder`);
47+
48+ expect(stripAnsi(stdout)).toContain("zen/gpt-5.4 · ~/src/mini-coder");
49+ });
50+});
51+
4252 describe("CliReporter live output", () => {
4353 test("groups streamed chunks into an indented output block", () => {
4454 captureStdout();
src/cli/output.ts+1−1
@@ -131,7 +131,7 @@ export function renderBanner(model: string, cwd: string): void {
131131 ? `mini-coder · v${PACKAGE_VERSION}`
132132 : "mini-coder";
133133 writeln(` ${c.cyan("mc")} ${c.dim(title)}`);
134- writeln(` ${c.dim(model)} ${c.dim("·")} ${c.dim(cwd)}`);
134+ writeln(` ${c.dim(model)} ${c.dim("·")} ${c.dim(tildePath(cwd))}`);
135135 writeln(
136136 ` ${c.dim("/help for commands · esc cancel · ctrl+c/ctrl+d exit")}`,
137137 );
src/cli/tool-render.test.ts+25−4
@@ -71,7 +71,7 @@ describe("renderToolResult", () => {
7171 );
7272
7373 const plain = stripAnsi(stdout);
74- expect(plain).toContain("error exit 1 · stdout 0L · stderr 1L · streamed");
74+ expect(plain).toContain("error exit 1 · stderr 1L");
7575 expect(plain).not.toContain("stderr (1 lines)");
7676 expect(plain).not.toContain("│ boom");
7777 });
@@ -93,12 +93,33 @@ describe("renderToolResult", () => {
9393 );
9494
9595 const plain = stripAnsi(stdout);
96- expect(plain).toContain(
97- "success exit 0 · stdout 1L · stderr 0L · streamed",
98- );
96+ expect(plain).toContain("done exit 0");
9997 expect(plain).not.toContain("out: done");
10098 });
10199
100+ test("shows stdout previews for non-streamed successful multi-line commands", () => {
101+ captureStdout();
102+
103+ renderToolResult(
104+ "shell",
105+ {
106+ stdout: "hello\nworld",
107+ stderr: "",
108+ exitCode: 0,
109+ success: true,
110+ timedOut: false,
111+ streamedOutput: false,
112+ },
113+ false,
114+ );
115+
116+ const plain = stripAnsi(stdout);
117+ expect(plain).toContain("done exit 0 · stdout 2L");
118+ expect(plain).toContain("stdout (2 lines)");
119+ expect(plain).toContain("│ hello");
120+ expect(plain).toContain("│ world");
121+ });
122+
102123 test("renders compact listSkills previews", () => {
103124 captureStdout();
104125
src/cli/tool-result-renderers.ts+94−44
@@ -2,7 +2,6 @@ import * as c from "yoctocolors";
22 import { G, writeln } from "./output.ts";
33
44 type ToolResultRenderer = (result: unknown, toolName?: string) => boolean;
5-
65 function writePreviewLines(opts: {
76 label: string;
87 value: string;
@@ -26,6 +25,72 @@ function truncateOneLine(value: string, max = 100): string {
2625 return value.length > max ? `${value.slice(0, max - 1)}…` : value;
2726 }
2827
28+function normalizeShellText(value: string): string {
29+ return value.replace(/[\r\n]+$/, "");
30+}
31+
32+function countShellLines(value: string): number {
33+ const normalized = normalizeShellText(value);
34+ return normalized ? normalized.split(/\r?\n/).length : 0;
35+}
36+
37+function getSingleShellLine(value: string): string | null {
38+ const normalized = normalizeShellText(value);
39+ if (!normalized) return null;
40+ const lines = normalized.split(/\r?\n/);
41+ return lines.length === 1 ? (lines[0] ?? "") : null;
42+}
43+
44+function buildShellSummaryParts(opts: {
45+ exitCode: number;
46+ stdoutLines: number;
47+ stderrLines: number;
48+ stdoutSingleLine: string | null;
49+ streamedOutput: boolean;
50+}): string[] {
51+ const parts = [`exit ${opts.exitCode}`];
52+ if (opts.streamedOutput) {
53+ if (opts.stdoutLines === 0 && opts.stderrLines === 0) {
54+ parts.push("no output");
55+ }
56+ if (opts.stderrLines > 0) {
57+ parts.push(`stderr ${opts.stderrLines}L`);
58+ }
59+ return parts;
60+ }
61+
62+ if (
63+ opts.stderrLines === 0 &&
64+ opts.stdoutSingleLine !== null &&
65+ opts.stdoutSingleLine.length > 0
66+ ) {
67+ parts.push(`out: ${truncateOneLine(opts.stdoutSingleLine)}`);
68+ return parts;
69+ }
70+
71+ if (opts.stdoutLines > 0) {
72+ parts.push(`stdout ${opts.stdoutLines}L`);
73+ }
74+ if (opts.stderrLines > 0) {
75+ parts.push(`stderr ${opts.stderrLines}L`);
76+ }
77+ if (opts.stdoutLines === 0 && opts.stderrLines === 0) {
78+ parts.push("no output");
79+ }
80+ return parts;
81+}
82+
83+function shouldPreviewShellStdout(opts: {
84+ success: boolean;
85+ stdoutLines: number;
86+ stderrLines: number;
87+ stdoutSingleLine: string | null;
88+}): boolean {
89+ if (opts.stdoutLines === 0) return false;
90+ if (!opts.success || opts.stderrLines > 0) return true;
91+ return opts.stdoutSingleLine === null;
92+}
93+
2994 function renderShellResult(result: unknown): boolean {
3095 const r = result as {
3196 stdout: string;
@@ -39,49 +104,26 @@ function renderShellResult(result: unknown): boolean {
39104 return false;
40105 }
41106
107+ const streamedOutput = r.streamedOutput === true;
108+ const stdoutLines = countShellLines(r.stdout);
109+ const stderrLines = countShellLines(r.stderr);
110+ const stdoutSingleLine = getSingleShellLine(r.stdout);
42111 const badge = r.timedOut
43112 ? c.yellow("timeout")
44113 : r.success
45- ? c.green("success")
114+ ? c.green("done")
46115 : c.red("error");
47-
48- const stdoutNormalized = r.stdout.replace(/[\r\n]+$/, "");
49- const stderrNormalized = r.stderr.replace(/[\r\n]+$/, "");
50- const stdoutLines = stdoutNormalized
51- ? stdoutNormalized.split(/\r?\n/).length
52- : 0;
53- const stderrLines = stderrNormalized
54- ? stderrNormalized.split(/\r?\n/).length
55- : 0;
56- const stdoutSingleLine =
57- stdoutLines === 1 ? (stdoutNormalized.split(/\r?\n/)[0] ?? "") : null;
58-
59- const parts = [
60- `exit ${r.exitCode}`,
61- `stdout ${stdoutLines}L`,
62- `stderr ${stderrLines}L`,
63- ];
64-
65- if (
66- r.success &&
67- !r.timedOut &&
68- !r.streamedOutput &&
69- stderrLines === 0 &&
70- stdoutSingleLine !== null &&
71- stdoutSingleLine.length > 0
72- ) {
73- parts.push(`out: ${truncateOneLine(stdoutSingleLine)}`);
74- }
75- if (r.streamedOutput) {
76- parts.push("streamed");
77- }
116+ const parts = buildShellSummaryParts({
117+ exitCode: r.exitCode,
118+ stdoutLines,
119+ stderrLines,
120+ stdoutSingleLine,
121+ streamedOutput,
122+ });
78123
79124 writeln(` ${badge} ${c.dim(parts.join(" · "))}`);
80125
81- if (r.success && !r.timedOut) {
82- return true;
83- }
84- if (r.streamedOutput) {
126+ if (streamedOutput) {
85127 return true;
86128 }
87129
@@ -91,16 +133,24 @@ function renderShellResult(result: unknown): boolean {
91133 lineColor: c.red,
92134 maxLines: 6,
93135 });
94- writePreviewLines({
95- label: "stdout",
96- value: r.stdout,
97- lineColor: c.dim,
98- maxLines: 4,
99- });
136+ if (
137+ shouldPreviewShellStdout({
138+ success: r.success && !r.timedOut,
139+ stdoutLines,
140+ stderrLines,
141+ stdoutSingleLine,
142+ })
143+ ) {
144+ writePreviewLines({
145+ label: "stdout",
146+ value: r.stdout,
147+ lineColor: c.dim,
148+ maxLines: 4,
149+ });
150+ }
100151
101152 return true;
102153 }
103-
104154 function renderSubagentResult(result: unknown): boolean {
105155 const r = result as {
106156 inputTokens?: number;
src/index.ts+50−39
@@ -52,6 +52,41 @@ initModelInfoCache();
5252 pruneOldData();
5353 void refreshModelInfoInBackground().catch(() => {});
5454
55+type AgentInitOptions = Parameters<typeof initAgent>[0];
56+
57+function buildAgentOptions(opts: {
58+ model: string;
59+ cwd: string;
60+ reporter: AgentInitOptions["reporter"];
61+ sessionId?: string | undefined;
62+ headless?: boolean;
63+ agentSystemPrompt?: string | undefined;
64+}): AgentInitOptions {
65+ return {
66+ model: opts.model,
67+ cwd: opts.cwd,
68+ initialThinkingEffort: getPreferredThinkingEffort(),
69+ initialShowReasoning: getPreferredShowReasoning(),
70+ initialPruningMode: getPreferredContextPruningMode(),
71+ initialToolResultPayloadCapBytes: getPreferredToolResultPayloadCapBytes(),
72+ initialPromptCachingEnabled: getPreferredPromptCachingEnabled(),
73+ initialOpenAIPromptCacheRetention: getPreferredOpenAIPromptCacheRetention(),
74+ initialGoogleCachedContent: getPreferredGoogleCachedContent(),
75+ reporter: opts.reporter,
76+ ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
77+ ...(opts.headless ? { headless: true } : {}),
78+ ...(opts.agentSystemPrompt
79+ ? { agentSystemPrompt: opts.agentSystemPrompt }
80+ : {}),
81+ };
82+}
83+
84+function writeStructuredResult(outputFd: number, payload: unknown): void {
85+ writeJsonLine((text) => {
86+ writeSync(outputFd, Buffer.from(text));
87+ }, payload);
88+}
89+
5590 // ─── Main ─────────────────────────────────────────────────────────────────────
5691
5792 async function main(): Promise<void> {
@@ -117,22 +152,15 @@ async function main(): Promise<void> {
117152 }
118153
119154 try {
120- const { runner } = await initAgent({
121- model: modelOverride,
122- cwd: parentCwd,
123- initialThinkingEffort: getPreferredThinkingEffort(),
124- initialShowReasoning: getPreferredShowReasoning(),
125- initialPruningMode: getPreferredContextPruningMode(),
126- initialToolResultPayloadCapBytes:
127- getPreferredToolResultPayloadCapBytes(),
128- initialPromptCachingEnabled: getPreferredPromptCachingEnabled(),
129- initialOpenAIPromptCacheRetention:
130- getPreferredOpenAIPromptCacheRetention(),
131- initialGoogleCachedContent: getPreferredGoogleCachedContent(),
132- reporter: new HeadlessReporter(),
133- headless: true,
134- ...(agentSystemPrompt ? { agentSystemPrompt } : {}),
135- });
155+ const { runner } = await initAgent(
156+ buildAgentOptions({
157+ model: modelOverride,
158+ cwd: parentCwd,
159+ reporter: new HeadlessReporter(),
160+ headless: true,
161+ agentSystemPrompt,
162+ }),
163+ );
136164
137165 const { text: resolvedText, images: refImages } = await resolveFileRefs(
138166 prompt ?? "",
@@ -146,21 +174,12 @@ async function main(): Promise<void> {
146174 outputTokens: status.totalOut,
147175 };
148176
149- if (args.outputFd !== null && summary) {
150- const outputFd = args.outputFd;
151- writeJsonLine((text) => {
152- writeSync(outputFd, Buffer.from(text));
153- }, summary);
177+ if (args.outputFd !== null) {
178+ writeStructuredResult(args.outputFd, summary);
154179 }
155180 } catch (err) {
156181 if (args.outputFd !== null) {
157- const outputFd = args.outputFd;
158- writeJsonLine(
159- (text) => {
160- writeSync(outputFd, Buffer.from(text));
161- },
162- { error: String(err) },
163- );
182+ writeStructuredResult(args.outputFd, { error: String(err) });
164183 }
165184 process.exit(1);
166185 }
@@ -173,20 +192,12 @@ async function main(): Promise<void> {
173192 }
174193
175194 try {
176- const agentOpts: Parameters<typeof initAgent>[0] = {
195+ const agentOpts = buildAgentOptions({
177196 model,
178197 cwd: args.cwd,
179- initialThinkingEffort: getPreferredThinkingEffort(),
180- initialShowReasoning: getPreferredShowReasoning(),
181- initialPruningMode: getPreferredContextPruningMode(),
182- initialToolResultPayloadCapBytes: getPreferredToolResultPayloadCapBytes(),
183- initialPromptCachingEnabled: getPreferredPromptCachingEnabled(),
184- initialOpenAIPromptCacheRetention:
185- getPreferredOpenAIPromptCacheRetention(),
186- initialGoogleCachedContent: getPreferredGoogleCachedContent(),
187198 reporter: new CliReporter(),
188- };
189- if (sessionId) agentOpts.sessionId = sessionId;
199+ sessionId,
200+ });
190201
191202 const { runner, cmdCtx } = await initAgent(agentOpts);