xonecas.io
64875
Mc

mini-coder / commit b68d5d7

fix: prevent hang on exit from closed stdin and dangling event loop

Two root causes for the 'ctrl+d hangs sometimes' bug:

1. readline() infinite spin: when stdin stream closes (emits 'end'),
   readKey() returns '' and 'if (!raw) continue' loops forever.
   Fix: treat empty readKey as EOF and return { type: 'eof' }.

2. No explicit process.exit(0) on success path: main() returned
   normally but background resources (HTTP fetches from
   refreshModelInfoInBackground, stdin listeners) kept the event
   loop alive. Fix: main().then(() => process.exit(0)).

Also adds AUDIT-REPORT.md from full codebase audit.

xonecas2026-03-21 b68d5d71644302d5fbc2c55015d2abc8256f4f41 parent d25a740

4 files changed

AUDIT-REPORT.md+106−0
@@ -0,0 +1,106 @@
1+# Audit Report — mini-coder v0.2.0
2+
3+**Date:** 2026-03-21
4+**Auditor:** Automated audit via mini-coder audit skill
5+**Scope:** Full code review + multi-provider interactive/one-shot testing
6+
7+---
8+
9+## Summary
10+
11+Reviewed all ~15K lines of TypeScript across 90 source files. Ran `bun run check` (303 tests pass, 0 lint/type/formatting issues). Tested 5 provider paths (zen/claude-haiku-4-5, zen/gemini-3-flash, zen/gpt-5.4-nano, zen/glm-5, anthropic/claude-haiku-4-5 via OAuth) in both one-shot and interactive tmux sessions. Exercised multi-turn tool use, model switching, ESC interrupt, `/new`, `/undo`, `/help`, `!` shell integration, and `listSkills`.
12+
13+**Overall assessment:** The codebase is well-structured, adheres closely to the core idea, and works correctly across all provider paths. The architecture is clean with good separation of concerns. The issues found are minor.
14+
15+---
16+
17+## Code & Architecture
18+
19+### Correctness Issues
20+
21+1. **`supportsThinking()` + haiku = 400 error** (KNOWN) — When `preferred_thinking_effort` is set in the DB, all models get thinking options sent, including haiku models that reject adaptive thinking. The user hits a 400 on first use with a stored thinking preference. Root cause: `supportsThinking()` trusts models.dev `reasoning` flag, which is `true` for haiku models even though Zen's haiku endpoint rejects the `thinking` parameter.
22+
23+2. **`autoTitleSession` overwrites title on every turn** — `setSessionTitle` is called on every `processUserInput`, not just the first. Looking at the DB layer, it likely uses `INSERT OR REPLACE` or always updates. This means the session title changes to match the latest user message instead of staying as the first message. Should check if already titled.
24+
25+3. **`maxOutputTokens` hardcoded to 16384** (KNOWN) — In `turn-request.ts` line `maxOutputTokens: 16384`. The model-info cache already has context window data; deriving max output from model info would be more accurate, especially for models with larger output limits.
26+
27+4. **DB lock during concurrent access** — The settings restore command failed with `database is locked` because the WAL wasn't fully checkpointed. The `busy_timeout=1000` is set, but external sqlite3 CLI access can still conflict. Not a bug per se, but the WAL file grows large (4MB observed).
28+
29+### Architecture Alignment with Core Idea
30+
31+- ✅ **Append-only scrolling log** — No redraws, strict hierarchy works correctly.
32+- ✅ **Shell-first tool surface** — `shell`, `listSkills`, `readSkill`, MCP, and optional web tools. Minimal and correct.
33+- ✅ **`mc-edit` exact-text edits** — Deterministic, well-tested (94 tests).
34+- ✅ **16 ANSI colors only** — Uses yoctocolors consistently, inherits terminal theme.
35+- ✅ **Status bar** — Shows model, session ID, git branch, thinking effort, token counts, context %.
36+- ✅ **Context pruning** — Rolling per-step pruning with Anthropic cache preservation. Well-designed.
37+- ✅ **Single system prompt** — No provider-specific branches. Works across all providers.
38+- ✅ **Community config standards** — AGENTS.md discovery, skills from `.agents/skills/` and `.claude/skills/`.
39+- ✅ **Session management** — SQLite-backed, with resume, list, new session.
40+- ✅ **MCP support** — StreamableHTTP with SSE fallback, stdio transport.
41+- ✅ **OAuth login** — Anthropic OAuth with PKCE flow.
42+- ✅ **ESC interrupt** — Works cleanly, preserves partial response in history.
43+
44+### KISS / DRY / YAGNI
45+
46+- **Good**: The codebase is lean. No unnecessary abstractions. Provider routing is simple prefix-based dispatch.
47+- **Good**: jscpd reports only 0.16% duplication (23 lines across 129 files).
48+- **Minor**: `turn-execution.ts` has substantial complexity in `StreamToolCallTracker` and `StreamTextPhaseTracker` for handling provider quirks (OpenAI commentary phases, synthetic tool call IDs). This is justified given the real provider differences, but the file is dense at ~300+ lines. Could benefit from a short doc comment explaining the overall stream normalization strategy.
49+- **Minor**: `cli/` module has 43 files — the largest module. Most are appropriately scoped, but the input handling is spread across 6 files (`input.ts`, `input-buffer.ts`, `input-completion.ts`, `input-control.ts`, `input-editing.ts`, `input-images.ts`, `input-loop.ts`). This is understandable for complexity management but makes the input pipeline harder to trace.
50+
51+### Things NOT in Known Issues Worth Noting
52+
53+- **No conversation summary on max context** — The pruning approach (`pruneMessages` from AI SDK) silently removes messages. When context is exhausted, the user gets a generic error. The known issues already track this.
54+- **`onError: () => {}`** in `turn-request.ts` — Correctly suppresses SDK's default `console.error()`. Errors still propagate through `fullStream` as `{ type: "error" }` chunks, which `mapStreamChunkToTurnEvent` handles by throwing. Not related to hangs.
55+
56+---
57+
58+## UI/UX Alignment
59+
60+### Provider Comparison
61+
62+| Feature | zen/claude-haiku-4-5 | zen/gemini-3-flash | zen/gpt-5.4-nano | zen/glm-5 | anthropic/claude-haiku-4-5 (OAuth) |
63+| ---------------------- | -------------------- | ------------------ | ---------------- | --------- | ---------------------------------- |
64+| One-shot simple | ✅ | ✅ | ✅ | ✅ | ✅ |
65+| One-shot with tools | ✅ | ✅ | ✅ | N/T | N/T |
66+| Interactive multi-turn | ✅ | ✅ | ✅ | ✅ | ✅ |
67+| Tool calls displayed | Clean | Clean | Clean | Clean | Clean |
68+| Token tracking | Accurate | Accurate | Accurate | Accurate | Accurate |
69+| Context % | 3% | 0-1% | 1% | 3% | 5% |
70+| ESC interrupt | ✅ | ✅ | N/T | N/T | N/T |
71+| Model switching | ✅ | ✅ | ✅ | ✅ | ✅ |
72+
73+N/T = Not specifically tested in interactive mode, but one-shot works.
74+
75+### UI Observations
76+
77+- **Banner**: Clean, shows version, model, cwd, AGENTS.md, skill count. Matches spec.
78+- **Status bar**: Updates correctly after each turn. Token counts accumulate properly. Context window percentage is color-coded (green/yellow/red). Model and session ID always visible.
79+- **Tool rendering**: Shell commands show the command, exit code, and line count. Output is properly boxed with `│` prefix. Short outputs show inline (`out: hello world`). Long outputs get line-counted display.
80+- **`/help` output**: Lists all commands and all 20 skills with descriptions and source (global/local). Includes keyboard shortcuts.
81+- **Spinner**: Shows during thinking/tool execution. Clears cleanly on interrupt.
82+- **`/new`**: Clears screen and reprints banner — feels like a fresh start.
83+
84+### One Surprising Behavior
85+
86+- **`!` shell output stays local** — The `!echo "test"` shell integration runs the command and adds the output to history for the LLM, but doesn't trigger a model response. This is by design (spec says "sends the output to the llm as user message") but users might expect the LLM to comment on it. The current behavior is arguably better — it's like pasting context.
87+
88+---
89+
90+## Recommendations
91+
92+### Code Changes
93+
94+1. **Guard `supportsThinking()` more conservatively** — The models.dev `reasoning: true` flag is too broad. Either maintain a local allowlist of models that accept adaptive thinking, or catch the 400 and retry without thinking options. This is the most impactful known issue — it breaks the first-run experience when a thinking preference is stored.
95+
96+2. **Derive `maxOutputTokens` from model info** — The model-info cache already stores capabilities. Use it instead of the 16384 hardcode.
97+
98+3. **Add a brief architecture comment at the top of `turn-execution.ts`** — The stream normalization logic is the most complex part of the codebase. A 5-line comment explaining why synthetic tool call IDs and phase tracking exist would help future contributors.
99+
100+### Polish
101+
102+4. **Status bar: merge model + thinking effort** (KNOWN) — The `showReasoning` field in the status bar signature contributes to unnecessary re-renders. The known issues already track this.
103+
104+5. **Shell tool truncation** — The `MAX_OUTPUT_BYTES = 10_000` truncation cuts mid-stream. The known issue about truncating at argument boundaries applies here too — truncated outputs can lose important trailing context.
105+
106+6. **WAL file growth** — The sessions.db WAL file was 4MB. The `PASSIVE` checkpoint at startup may not always succeed. Consider a more aggressive checkpoint strategy or periodic forced checkpoints.
docs/KNOWN_ISSUES.md+1−1
@@ -3,7 +3,7 @@
33 ## Bugs
44
55 - `/model` doesn't autocomplete models provider/name pattern.
6-- CTRL+d hangs sometimes and doesn't exit.
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.
src/cli/input.ts+5−1
@@ -273,7 +273,11 @@ export async function readline(opts: { cwd?: string }): Promise<InputResult> {
273273 try {
274274 while (true) {
275275 const raw = await readKey(reader);
276- if (!raw) continue;
276+ if (!raw) {
277+ // Stream closed (stdin "end") — treat as EOF to avoid infinite spin.
278+ process.stdout.write("\n");
279+ return { type: "eof" };
280+ }
277281
278282 // ── Search mode ────────────────────────────────────────────────────────
279283 if (searchMode) {
src/index.ts+9−6
@@ -148,9 +148,12 @@ async function main(): Promise<void> {
148148 }
149149 }
150150
151-main().catch((err) => {
152- if (!(err instanceof RenderedError)) {
153- renderError(err, "main");
154- }
155- process.exit(1);
156-});
151+main().then(
152+ () => process.exit(0),
153+ (err) => {
154+ if (!(err instanceof RenderedError)) {
155+ renderError(err, "main");
156+ }
157+ process.exit(1);
158+ },
159+);