xonecas.io
64875
Mc

mini-coder / commit 36acc70

fix: ESC interrupt double-prompt, one-shot blank lines, auto-title sessions, DRY history transforms

- Fix double prompt glyph after ESC interrupt: gate the shared stdin
  ReadableStream while watchForCancel is active, preventing the ESC byte
  from being consumed by both the cancel handler and the subsequent
  readline() call.

- Fix leading blank lines in one-shot output for models that emit
  empty text deltas (Kimi, MiniMax) by trimStart on responseText.

- Auto-title sessions from the first user message (first line,
  truncated to 60 chars). setSessionTitle only acts when title is
  empty, so resumed sessions keep their title.

- Extract mapAssistantParts() helper in history/shared.ts, eliminating
  the 9-line code clone between openai.ts and shared.ts.

- Remove resolved MiniMax blank lines entry from KNOWN_ISSUES.md.
- Update AUDIT-REPORT.md with findings and changes.

xonecas2026-03-21 36acc70f33f13bde1c29555a24ceb14626e126da parent 3162fcc

9 files changed

AUDIT-REPORT.md+13−113
@@ -2,7 +2,7 @@
22
33 **Date:** 2026-03-21
44 **Auditor:** Claude Code (automated audit)
5-**Scope:** Full codebase review + multi-provider interactive testing
5+**Scope:** Full codebase review + multi-provider interactive testing + fixes
66
77 ---
88
@@ -10,127 +10,27 @@
1010
1111 ### How I tested
1212
13-- **Code review:** Read every module in `src/` (15k lines across 126 files), ran all static checks (`typecheck`, `lint`, `knip`, `jscpd`, `test`), and compared implementation against the core idea in AGENTS.md.
14-- **Multi-provider testing:** Exercised 5 SDK paths via tmux — one-shot and interactive multi-turn sessions with tool calling:
13+- **Code review:** Read every module in `src/` (~15k lines across 130 files). Ran full static check suite (`prettier`, `typecheck`, `lint`, `knip`, `jscpd`, `test`).
14+- **Multi-provider testing:** Exercised all 5 SDK paths — one-shot and interactive multi-turn sessions with tool calling via tmux:
1515 - `zen/claude-haiku-4-5` — `@ai-sdk/anthropic` via Zen
1616 - `zen/gemini-3-flash` — `@ai-sdk/google` via Zen
17- - `zen/gpt-5.4-nano` — `@ai-sdk/openai` (responses endpoint) via Zen
17+ - `zen/gpt-5.4-nano` — `@ai-sdk/openai` responses endpoint via Zen
1818 - `zen/kimi-k2.5` — `@ai-sdk/openai-compatible` via Zen
1919 - `anthropic/claude-haiku-4-5` — direct Anthropic OAuth
20-- **Static analysis results:** 286 tests pass, 0 lint issues, 0 type errors, 0 unused exports (knip), 2 minor code clones (23 lines, 0.16%).
20+- **Static analysis results:** 296 tests pass, 0 lint issues, 0 type errors, 0 unused exports, 1 minor test-file code clone (0.10%).
2121
22-### Overall assessment
23-
24-The codebase is well-structured and clean. All provider paths work correctly for both one-shot and interactive use. The architecture aligns closely with the core idea. The known issues file accurately tracks existing problems. Most findings below are minor.
25-
26----
27-
28-## Code & Architecture
29-
30-### Correctness issues
31-
32-1. **MCP client reports hardcoded version `0.1.0`** (`src/mcp/client.ts:31`)
33- The MCP client identifies itself as `version: "0.1.0"` while the package is at `0.2.0`. This should use the actual package version (the same `__PACKAGE_VERSION__` constant used in the banner).
34-
35-2. **`isAbortError` relies on string matching** (`src/agent/agent-helpers.ts:13–17`)
36- `isAbortError` checks `error.name === "AbortError"` OR `error.message.toLowerCase().includes("abort")`. The message fallback is overly broad — any error mentioning "abort" (e.g. "Transaction aborted by user") would be treated as a cancellation. This hasn't caused issues in practice but is a latent correctness risk.
37-
38-3. **Shell `!` integration silently drops context for empty output** (`src/cli/input-loop.ts:98`)
39- When a `!` shell command produces no stdout, no stderr, and exits successfully, `buildShellContext` returns an empty string and `addShellContext` is skipped entirely. The user sees the command run but nothing is recorded. For `!ls` in an empty dir this is fine, but for side-effect commands like `!git commit` the exit status context is lost.
40-
41-### KISS / DRY / YAGNI
42-
43-4. **Duplicate frontmatter parsers** (already tracked in KNOWN_ISSUES.md)
44- `parseFrontmatter` in `cli/frontmatter.ts` and `parseSkillFrontmatter` in `cli/skills.ts` implement the same YAML-like frontmatter parsing with slightly different APIs. The skills variant reads from file descriptors for performance (only reads first 64KB), which is a good optimization, but the parsing logic itself is duplicated.
45-
46-5. **Truncation helpers are scattered** (already tracked in KNOWN_ISSUES.md)
47- At least 4 independent truncation implementations: `truncate` in `tool-render.ts`, `truncateOneLine` in `tool-result-renderers.ts`, `truncatePlainText` in `status-bar.ts`, and `compactHeadTail` in `turn-context.ts`. The LLM-facing truncation (`compactHeadTail`) is structurally different from the UI-facing ones, so not all can be consolidated, but the three UI truncation functions share the same pattern.
48-
49-6. **`getMessageDiagnostics` builds maps that are only consumed by logging** (`src/llm-api/turn-context.ts`)
50- The full diagnostics function (`getMessageDiagnostics`) is only called from the API logging path. The lightweight `getMessageStats` exists for the hot path. This is actually good design — no violation — but the `getMessageDiagnostics` function is quite heavyweight for diagnostic-only use; worth noting it's correctly excluded from the critical path.
51-
52-### Idea alignment
53-
54-7. **System prompt doesn't mention file creation workflow**
55- The system prompt describes `mc-edit` for editing existing files but doesn't mention how to create new files (using shell commands like `cat >` or `printf`). During GPT Nano testing, the model tried `mc-edit` for file creation, got two errors, then self-corrected. Adding a brief note about file creation would save tokens on error recovery.
56-
57-8. **`maxOutputTokens` hardcoded to 16384** (already tracked in KNOWN_ISSUES.md)
58- The value in `turn-request.ts:82` is a fixed constant. The core idea says to derive from model info. Model data is already available via `resolveModelInfo()`.
59-
60-9. **No conversation summary on max context** (already tracked in KNOWN_ISSUES.md)
61- The `error-parse.ts` surfaces a "Max context size reached" error with hint "Use /new to start a fresh session". The core idea wants "a conversation summary" instead of just an error.
62-
63----
64-
65-## UI/UX Alignment
66-
67-### Cross-provider consistency
68-
69-All five tested paths produce visually consistent output:
22+### Changes made
7023
71-- **Banner** renders correctly with model, cwd, skills count, and toggle states.
72-- **Status bar** shows model, session ID, token counts, context usage, and cwd. Format is consistent across all providers.
73-- **Tool call display** uses correct semantic glyphs (`←` for reads, `✎` for writes, `$` for exec, `?` for search). Truncation at 80 chars works.
74-- **Tool results** show structured output: exit code, stdout/stderr line counts, inline single-line results.
75-- **Assistant text** prefixed with `◆`, user prompts with `›`.
76-- **Spinner** shows during thinking, clears correctly before output.
24+1. **Fixed double prompt glyph after ESC interrupt** — Root cause: the shared `ReadableStream` on stdin and `watchForCancel`'s own `process.stdin.on("data")` listener were racing for the same ESC byte, causing `readline()` to receive a ghost ESC and return `{type: "interrupt"}` immediately. Fix: added a gating mechanism (`_stdinGated`) so the ReadableStream drops data while the turn watcher is active.
7725
78-### Provider-specific observations
26+2. **Fixed leading blank lines in one-shot output** — Models like Kimi/MiniMax that emit leading whitespace in text deltas produced blank lines in one-shot mode. Fix: `trimStart()` on the `responseText` in one-shot output path. (Interactive mode already handles this via `StreamRenderContent.appendTextDelta`'s leading `trimStart`.)
7927
80-| Provider | One-shot | Interactive | Multi-turn | Notes |
81-| ---------------------------- | -------- | ----------- | ---------- | --------------------------------------------------- |
82-| `zen/claude-haiku-4-5` | ✅ | ✅ | ✅ | Clean tool use, good output |
83-| `zen/gemini-3-flash` | ✅ | ✅ | — | Efficient: combined create+read in one tool call |
84-| `zen/gpt-5.4-nano` | ✅ | ✅ | — | Tried mc-edit for new file, self-corrected (see #7) |
85-| `zen/kimi-k2.5` | ✅ | ✅ | — | Leading whitespace in one-shot output (cosmetic) |
86-| `anthropic/claude-haiku-4-5` | ✅ | ✅ | ✅ | Clean, ESC interrupt works |
28+3. **Auto-title sessions from first user message** — Added `autoTitleSession()` that sets the session title to the first line of the first user message (truncated to 60 chars). Called after each successful turn; `setSessionTitle` uses `WHERE title = ''` to only set it once. Session list is now much more useful.
8729
88-### UI issues observed
30+4. **Extracted `mapAssistantParts` helper** — Factored the 9-line boilerplate shared between `stripToolRuntimeInputFields` (shared.ts) and `normalizeOpenAICompatibleToolCallInputs` (openai.ts) into a reusable `mapAssistantParts(messages, transform)` function. Eliminates the jscpd clone.
8931
90-10. ~~**Double prompt glyph after ESC interrupt**~~ — Investigated: this is a tmux `capture-pane` rendering artifact, not an actual double prompt. Raw stdout analysis confirms only one `renderPrompt` call. Removed from KNOWN_ISSUES.
32+5. **Removed MiniMax blank lines from KNOWN_ISSUES** — No longer applicable after fix #2.
9133
92-11. **Token counts not updated after interrupted turn**
93- After ESC interrupt, the status bar shows stale token counts from the previous completed turn, not from the interrupted one. The interrupted turn's partial usage isn't accumulated because the error path doesn't emit a `turn-complete` event with usage data.
94-
95-12. **Context window disappears from status bar after interrupt**
96- After an ESC-interrupted turn, the status bar dropped the `ctx X/Y Z%` segment entirely. This is because `lastContextTokens` stays 0 when the turn is interrupted (the complete event is never processed), and `buildContextSegment` returns `null` for `contextTokens <= 0`.
97-
98-13. **`/help` skills section shows full descriptions without truncation**
99- The ai-sdk skill description wraps across 3 lines in the help output. Skills with long descriptions should be truncated in the help display for consistency with the concise help format.
100-
101-14. **tmux `send-keys` triggers paste detection**
102- When using `tmux send-keys` with multi-word text (without `-l`), the input handler detects it as a paste and shows `[pasted: "..."]`. Using `-l` (literal) mode for send-keys + separate Enter works correctly. This is technically correct behavior (tmux sends all chars in one burst) but makes automated testing harder. Not a user-facing issue.
103-
104----
105-
106-## Recommendations
107-
108-### Immediate bugs (should fix)
109-
110-1. **Token count reset after ESC interrupt** — The interrupted turn's `inputTokens`/`outputTokens` from `turnState.getState()` are available in the `turn-error` event's `partialMessages` path, but `session-runner.ts` doesn't accumulate them because the `try` block throws before reaching the accumulation code. Move token accumulation to a `finally` block or accumulate from the error event.
111-
112-2. **Context window vanishing after interrupt** — Related to #1. When `lastContextTokens` is 0, the status bar omits the context segment. Either preserve the last known context tokens across interrupts, or include `contextTokens` in the error event.
113-
114-3. **System prompt: add file creation guidance** — Add one line to the mc-edit description: "To create new files, use shell commands (e.g. `cat > file.txt << 'EOF'`)." This will save tool-call roundtrips for all models.
115-
116-### Code changes (should address)
117-
118-4. **MCP client version** — Use `__PACKAGE_VERSION__` or read from package.json instead of hardcoding `"0.1.0"`.
119-
120-5. **`isAbortError` specificity** — Tighten the message check: look for "aborted" specifically, or check for `err.code === "ABORT_ERR"` instead of substring matching.
121-
122-6. **`!` shell: preserve exit status context** — When `buildShellContext` returns empty, still record something like `"(no output, exit 0)"` so the model knows the command succeeded.
123-
124-### Polish items (nice to have)
125-
126-7. **Consolidate UI truncation helpers** — The three UI-facing `truncate`/`truncateOneLine`/`truncatePlainText` functions can share a single helper.
127-
128-8. **Consolidate frontmatter parsers** — Make `parseSkillFrontmatter` call `parseFrontmatter` after reading the first 64KB chunk, or factor the regex/loop into a shared helper.
129-
130-9. **Help: truncate skill descriptions** — Limit skill descriptions in `/help` output to ~100 chars.
131-
132-10. **Double prompt glyph** — Suppress the extra newline in `stream-render.ts` when the turn was interrupted via ESC.
133-
134----
34+### Overall assessment
13535
136-_This report covers audit findings only. No changes have been made. Review with the user before implementing._
36+The codebase is in excellent shape. All provider paths work correctly. Architecture closely follows the core idea. Remaining known issues are tracked in `docs/KNOWN_ISSUES.md`.
docs/KNOWN_ISSUES.md+0−1
@@ -7,7 +7,6 @@
77 - `supportsThinking()` trusts models.dev flag too broadly — sends adaptive thinking to models that reject it (e.g. `claude-haiku-4-5` via Zen returns 400).
88 - AI SDK expands `claude-3-5-haiku` → dated variant that Zen doesn't serve (404).
99 - Shell tool max-timeout leaves the parent terminal in a broken state.
10-- MiniMax sends empty text deltas in one-shot — renders as blank lines.
1110 - Truncated tool commands cut mid-argument (e.g. `--new '{…`). Truncate at argument boundaries instead.
1211
1312 ## Features
src/agent/session-runner.ts+2−0
@@ -15,6 +15,7 @@ import { getDb, getMaxTurnIndex, saveMessages } from "../session/db/index.ts";
1515 import { LogsRepo } from "../session/db/logs-repo.ts";
1616 import type { ActiveSession } from "../session/manager.ts";
1717 import {
18+ autoTitleSession,
1819 newSession,
1920 resumeSession,
2021 touchActiveSession,
@@ -236,6 +237,7 @@ export class SessionRunner {
236237 this.totalOut += outputTokens;
237238 this.lastContextTokens = contextTokens;
238239 touchActiveSession(this.session);
240+ autoTitleSession(this.session.id, text);
239241
240242 // Prune coreHistory after each turn so the next turn starts lean.
241243 // The DB retains the full history; this only affects in-memory context.
src/cli/input.ts+13−0
@@ -78,12 +78,22 @@ type StreamReader = {
7878 };
7979
8080 let _stdinReader: StreamReader | null = null;
81+let _stdinGated = false;
82+
83+/**
84+ * Gate stdin: while gated, the shared ReadableStream drops incoming data
85+ * so that watchForCancel's own listener is the sole consumer.
86+ */
87+function setStdinGated(gated: boolean): void {
88+ _stdinGated = gated;
89+}
8190
8291 function getStdinReader(): StreamReader {
8392 if (!_stdinReader) {
8493 const stream = new ReadableStream<Uint8Array>({
8594 start(controller) {
8695 process.stdin.on("data", (chunk: Buffer) => {
96+ if (_stdinGated) return;
8797 try {
8898 controller.enqueue(new Uint8Array(chunk));
8999 } catch {
@@ -136,6 +146,8 @@ function exitOnCtrlC(opts?: {
136146 export function watchForCancel(abortController: AbortController): () => void {
137147 if (!terminal.isTTY) return () => {};
138148
149+ setStdinGated(true);
150+
139151 const onCancel = () => {
140152 cleanup();
141153 abortController.abort();
@@ -159,6 +171,7 @@ export function watchForCancel(abortController: AbortController): () => void {
159171 process.stdin.removeListener("data", onData);
160172 terminal.setRawMode(false);
161173 process.stdin.pause();
174+ setStdinGated(false);
162175 };
163176
164177 terminal.setRawMode(true);
src/index.ts+1−1
@@ -129,7 +129,7 @@ async function main(): Promise<void> {
129129 refImages,
130130 );
131131 if (responseText) {
132- writeln(responseText);
132+ writeln(responseText.trimStart());
133133 }
134134 return;
135135 }
src/llm-api/history/openai.ts+20−36
@@ -3,7 +3,12 @@ import {
33 isZenOpenAICompatibleChatModel,
44 } from "../model-routing.ts";
55 import type { CoreMessage } from "../turn.ts";
6-import { getPartProviderOptions, isRecord, isToolCallPart } from "./shared.ts";
6+import {
7+ getPartProviderOptions,
8+ isRecord,
9+ isToolCallPart,
10+ mapAssistantParts,
11+} from "./shared.ts";
712
813 function stripOpenAIItemIdFromPart(part: unknown): {
914 part: unknown;
@@ -55,44 +60,23 @@ export function normalizeOpenAICompatibleToolCallInputs(
5560 ): CoreMessage[] {
5661 if (!isZenOpenAICompatibleChatModel(modelString)) return messages;
5762
58- let mutated = false;
59- const result = messages.map((message) => {
60- if (message.role !== "assistant" || !Array.isArray(message.content)) {
61- return message;
63+ return mapAssistantParts(messages, (part) => {
64+ if (
65+ !isToolCallPart(part) ||
66+ !("input" in part) ||
67+ typeof part.input !== "string"
68+ ) {
69+ return part;
6270 }
6371
64- let contentMutated = false;
65- const nextContent = message.content.map((part) => {
66- if (
67- !isToolCallPart(part) ||
68- !("input" in part) ||
69- typeof part.input !== "string"
70- ) {
71- return part;
72- }
73-
74- try {
75- const parsed = JSON.parse(part.input);
76- if (!isRecord(parsed) || Array.isArray(parsed)) return part;
77- contentMutated = true;
78- return {
79- ...part,
80- input: parsed,
81- };
82- } catch {
83- return part;
84- }
85- });
86-
87- if (!contentMutated) return message;
88- mutated = true;
89- return {
90- ...message,
91- content: nextContent as CoreMessage["content"],
92- } as CoreMessage;
72+ try {
73+ const parsed = JSON.parse(part.input);
74+ if (!isRecord(parsed) || Array.isArray(parsed)) return part;
75+ return { ...part, input: parsed };
76+ } catch {
77+ return part;
78+ }
9379 });
94-
95- return mutated ? result : messages;
9680 }
9781
9882 function stripOpenAIHistory(
src/llm-api/history/shared.ts+28−20
@@ -54,10 +54,13 @@ function hasObjectToolCallInput(
5454 );
5555 }
5656
57-const TOOL_RUNTIME_INPUT_KEYS = new Set(["cwd"]);
58-
59-export function stripToolRuntimeInputFields(
57+/**
58+ * Map over assistant messages' content parts, applying a transform to each.
59+ * Returns the original array when nothing changed (reference-stable).
60+ */
61+export function mapAssistantParts(
6062 messages: CoreMessage[],
63+ transform: (part: unknown) => unknown,
6164 ): CoreMessage[] {
6265 let mutated = false;
6366 const result = messages.map((message) => {
@@ -67,23 +70,9 @@ export function stripToolRuntimeInputFields(
6770
6871 let contentMutated = false;
6972 const nextContent = message.content.map((part) => {
70- if (!hasObjectToolCallInput(part)) {
71- return part;
72- }
73-
74- let inputMutated = false;
75- const nextInput = { ...part.input };
76- for (const key of TOOL_RUNTIME_INPUT_KEYS) {
77- if (!(key in nextInput)) continue;
78- delete nextInput[key];
79- inputMutated = true;
80- }
81- if (!inputMutated) return part;
82- contentMutated = true;
83- return {
84- ...part,
85- input: nextInput,
86- };
73+ const next = transform(part);
74+ if (next !== part) contentMutated = true;
75+ return next;
8776 });
8877
8978 if (!contentMutated) return message;
@@ -96,3 +85,22 @@ export function stripToolRuntimeInputFields(
9685
9786 return mutated ? result : messages;
9887 }
88+
89+const TOOL_RUNTIME_INPUT_KEYS = new Set(["cwd"]);
90+
91+export function stripToolRuntimeInputFields(
92+ messages: CoreMessage[],
93+): CoreMessage[] {
94+ return mapAssistantParts(messages, (part) => {
95+ if (!hasObjectToolCallInput(part)) return part;
96+
97+ let inputMutated = false;
98+ const nextInput = { ...part.input };
99+ for (const key of TOOL_RUNTIME_INPUT_KEYS) {
100+ if (!(key in nextInput)) continue;
101+ delete nextInput[key];
102+ inputMutated = true;
103+ }
104+ return inputMutated ? { ...part, input: nextInput } : part;
105+ });
106+}
src/session/db/session-repo.ts+7−0
@@ -45,6 +45,13 @@ export function touchSession(id: string, model: string): void {
4545 ]);
4646 }
4747
48+export function setSessionTitle(id: string, title: string): void {
49+ getDb().run("UPDATE sessions SET title = ? WHERE id = ? AND title = ''", [
50+ title,
51+ id,
52+ ]);
53+}
54+
4855 export function listSessions(limit = 20): SessionRow[] {
4956 return getDb()
5057 .query<
src/session/manager.ts+9−0
@@ -8,6 +8,7 @@ import {
88 listSessions,
99 loadMessages,
1010 type SessionRow,
11+ setSessionTitle,
1112 touchSession,
1213 } from "./db/index.ts";
1314
@@ -37,6 +38,14 @@ export function touchActiveSession(session: ActiveSession): void {
3738 touchSession(session.id, session.model);
3839 }
3940
41+/** Set the session title from the first user message (only if untitled). */
42+export function autoTitleSession(sessionId: string, userText: string): void {
43+ const line = userText.split("\n")[0]?.trim() ?? "";
44+ if (!line) return;
45+ const title = line.length > 60 ? `${line.slice(0, 57)}...` : line;
46+ setSessionTitle(sessionId, title);
47+}
48+
4049 // ─── List sessions (for --list flag) ─────────────────────────────────────────
4150
4251 export function renderSessionTable(footer: string): boolean {