xonecas.io
79113
Ma

mini-coding-agent / commit 90f9ac3

fix: crash on tui access to messages

Also fixes a regression around styles in the banner

xonecas2026-10-07 90f9ac392d64f53c3740df79e5739bf670966e1d parent 2382098

5 files changed

src/agent.zig+19−3
@@ -1,6 +1,7 @@
11 const std = @import("std");
22 const types = @import("types.zig");
33 const api = @import("api.zig");
4+const platform = @import("platform.zig");
45 const tools = @import("tools/index.zig");
56 const common = @import("tools/common.zig");
67 const session = @import("session.zig");
@@ -60,8 +61,17 @@ pub const Options = struct {
6061 session: *session.Session,
6162 cancel: *const std.atomic.Value(bool),
6263 config: *const config.Config,
64+ messages_mutex: ?*std.Io.Mutex = null,
6365 };
6466
67+fn lockMessages(opts: Options) void {
68+ if (opts.messages_mutex) |m| m.lockUncancelable(platform.io);
69+}
70+
71+fn unlockMessages(opts: Options) void {
72+ if (opts.messages_mutex) |m| m.unlock(platform.io);
73+}
74+
6575 const StreamCtx = struct { listener: Listener, started: bool = false };
6676
6777 fn onApiEvent(ctx: *anyopaque, event: api.Event) void {
@@ -84,10 +94,16 @@ fn onToolOutput(ctx: *anyopaque, chunk: []const u8) void {
8494 listener.emit(.{ .tool_output = chunk });
8595 }
8696
97+fn pushMessage(opts: Options, messages: *std.ArrayList(types.Message), message: types.Message) !void {
98+ lockMessages(opts);
99+ defer unlockMessages(opts);
100+ try messages.append(opts.a, message);
101+}
102+
87103 fn steer(opts: Options, messages: *std.ArrayList(types.Message), content: []const u8) !void {
88104 if (content.len == 0) return;
89105 const message = types.Message{ .user = .{ .content = content, .timestamp = util.nowMs() } };
90- try messages.append(opts.a, message);
106+ try pushMessage(opts, messages, message);
91107 try opts.session.appendMessage(opts.a, message);
92108 }
93109
@@ -177,7 +193,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(types.Message), interacti
177193 };
178194
179195 if (cancelled(opts, listener)) return;
180- messages.append(opts.a, .{ .assistant = assistant }) catch {
196+ pushMessage(opts, messages, .{ .assistant = assistant }) catch {
181197 listener.emit(.{ .err = "out of memory" });
182198 return;
183199 };
@@ -245,7 +261,7 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(types.Message), interacti
245261 .is_error = if (result) |r| r.is_error else true,
246262 .timestamp = util.nowMs(),
247263 } };
248- messages.append(opts.a, tool_message) catch {
264+ pushMessage(opts, messages, tool_message) catch {
249265 listener.emit(.{ .err = "out of memory" });
250266 return;
251267 };
src/api/google_generative_ai.zig+8−5
@@ -5,7 +5,8 @@ const types = @import("../types.zig");
55 const Part = struct {
66 text: ?[]const u8 = null,
77 inlineData: ?struct { mimeType: []const u8, data: []const u8 } = null,
8- functionCall: ?struct { name: []const u8, args: api.Raw, thoughtSignature: ?[]const u8 = null } = null,
8+ functionCall: ?struct { name: []const u8, args: api.Raw } = null,
9+ thoughtSignature: ?[]const u8 = null,
910 functionResponse: ?struct {
1011 name: []const u8,
1112 response: Response,
@@ -47,11 +48,13 @@ fn contentParts(a: std.mem.Allocator, msg: types.Message) ![]const Part {
4748 var parts: std.ArrayList(Part) = .empty;
4849 for (am.content.items) |block| switch (block) {
4950 .text => |t| try parts.append(a, textPart(t)),
50- .tool_call => |c| try parts.append(a, .{ .functionCall = .{
51- .name = c.name,
52- .args = .{ .bytes = api.argumentsOrObject(c.arguments) },
51+ .tool_call => |c| try parts.append(a, .{
52+ .functionCall = .{
53+ .name = c.name,
54+ .args = .{ .bytes = api.argumentsOrObject(c.arguments) },
55+ },
5356 .thoughtSignature = c.thought_signature,
54- } }),
57+ }),
5558 .thinking => {},
5659 };
5760 return parts.items;
src/tui/tui.zig+15−3
@@ -34,6 +34,10 @@ const PendingCall = struct { name: []const u8, summary: []const u8 };
3434 const STATE_WIDTH = "running".len;
3535 const STATE_PAD = std.fmt.comptimePrint("{{s: <{d}}}", .{STATE_WIDTH});
3636
37+fn paintRow(a: std.mem.Allocator, line: []const u8) []const u8 {
38+ return std.fmt.allocPrint(a, "{s}{s}\x1b[K", .{ theme.SGR_PLAIN, line }) catch line;
39+}
40+
3741 fn styleLine(a: std.mem.Allocator, line: stream.BodyLine) []const u8 {
3842 const safe = render.sanitize(a, line.text);
3943 const expanded = render.expandTabs(a, safe, 4);
@@ -456,6 +460,7 @@ const Tui = struct {
456460 stdin_closed: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
457461 eof_sent: bool = false,
458462 key_mutex: std.Io.Mutex = .init,
463+ messages_mutex: std.Io.Mutex = .init,
459464 events: std.ArrayList(agent.Event) = .empty,
460465 batch: std.ArrayList(agent.Event) = .empty,
461466 event_mutex: std.Io.Mutex = .init,
@@ -540,13 +545,12 @@ const Tui = struct {
540545 const blank = clean.len == 0 or (self.separator and self.wrote);
541546 self.separator = false;
542547 if (blank and self.wrote and !self.last_blank) {
543- self.scroll.appendSlice(self.a, theme.SGR_PLAIN) catch {};
548+ self.scroll.appendSlice(self.a, paintRow(self.sa, "")) catch {};
544549 self.scroll.appendSlice(self.a, "\r\n") catch {};
545550 self.last_blank = true;
546551 }
547552 if (clean.len != 0) {
548- self.scroll.appendSlice(self.a, clean) catch {};
549- self.scroll.appendSlice(self.a, theme.SGR_PLAIN) catch {};
553+ self.scroll.appendSlice(self.a, paintRow(self.sa, clean)) catch {};
550554 self.scroll.appendSlice(self.a, "\r\n") catch {};
551555 self.wrote = true;
552556 self.last_blank = false;
@@ -596,7 +600,9 @@ const Tui = struct {
596600
597601 fn statusLine(self: *Tui) []const u8 {
598602 const model = self.opts.model orelse return styles.dim(self.s, "no model configured");
603+ self.messages_mutex.lockUncancelable(platform.io);
599604 const used = estimateContextTokens(self.messages.items, self.opts.system_prompt, self.opts.tools_json);
605+ self.messages_mutex.unlock(platform.io);
600606 const usage = contextUsageLine(self.s, used, model);
601607 if (self.paused or self.phase == .pausing) {
602608 return std.fmt.allocPrint(self.s, "{s} · {s}", .{ styles.dim(self.s, "paused - type steering, Enter to submit"), usage }) catch usage;
@@ -864,10 +870,13 @@ const Tui = struct {
864870 }
865871 self.editor.clear();
866872 const message = types.Message{ .user = .{ .content = self.a.dupe(u8, text) catch text, .timestamp = util.nowMs() } };
873+ self.messages_mutex.lockUncancelable(platform.io);
867874 self.messages.append(platform.gpa, message) catch {
875+ self.messages_mutex.unlock(platform.io);
868876 self.fail("! out of memory", .{});
869877 return;
870878 };
879+ self.messages_mutex.unlock(platform.io);
871880 self.opts.session.appendMessage(platform.gpa, message) catch |e| {
872881 self.fail("! {s}", .{@errorName(e)});
873882 return;
@@ -938,7 +947,9 @@ const Tui = struct {
938947 self.opts.session.close();
939948 const cwd = std.process.currentPathAlloc(platform.io, self.a) catch ".";
940949 self.opts.session.* = session_mod.Session.init(self.a, self.cfg.sessions_dir, cwd);
950+ self.messages_mutex.lockUncancelable(platform.io);
941951 self.messages.clearRetainingCapacity();
952+ self.messages_mutex.unlock(platform.io);
942953 self.dirty = true;
943954 }
944955
@@ -1161,6 +1172,7 @@ fn inputThread(self: *Tui) void {
11611172 fn turnThread(self: *Tui) void {
11621173 var o = self.opts.*;
11631174 o.cancel = &self.abort;
1175+ o.messages_mutex = &self.messages_mutex;
11641176 agent.runTurn(o, &self.messages, .{
11651177 .ctx = self,
11661178 .is_pause_requested = Tui.isPauseRequested,
tools/qa-matrix.sh+94−0
@@ -0,0 +1,94 @@
1+#!/usr/bin/env bash
2+#
3+# qa-matrix.sh - run the QA scenarios from tools/qa.sh against every provider
4+# listed in AGENTS.md and print a pass/fail summary per scenario.
5+#
6+# tools/qa-matrix.sh [-o root] [-C cwd] [-d max-seconds] [-p provider]...
7+#
8+# Each provider needs a scratch XDG_CONFIG_HOME at <root>/configs/<provider>
9+# holding mini-coding-agent/config.json, and each scenario gets <root>/runs/
10+# <provider>/<scenario>. Only the providers named with -p are run; with none,
11+# all four from AGENTS.md are.
12+
13+set -euo pipefail
14+
15+here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
16+root=/tmp/mini-qa
17+cwd=$PWD
18+maxd=90
19+providers=()
20+
21+usage() {
22+ cat <<'EOF'
23+usage: qa-matrix.sh [options]
24+ -o root where configs and runs live (default /tmp/mini-qa)
25+ -C cwd working directory mini runs in (default $PWD)
26+ -d seconds capture cap per scenario (default 90)
27+ -p name provider to run (repeatable); default all of AGENTS.md
28+EOF
29+}
30+
31+while getopts 'o:C:d:p:h' opt; do
32+ case $opt in
33+ o) root=$OPTARG ;;
34+ C) cwd=$OPTARG ;;
35+ d) maxd=$OPTARG ;;
36+ p) providers+=("$OPTARG") ;;
37+ h) usage; exit 0 ;;
38+ *) usage; exit 2 ;;
39+ esac
40+done
41+if (( ${#providers[@]} == 0 )); then
42+ providers=(completions responses anthropic google)
43+fi
44+root=$(readlink -f -- "$root")
45+cwd=$(cd -- "$cwd" && pwd)
46+
47+run() {
48+ local provider=$1 scenario=$2 duration=$3 spec=$4
49+ local out=$root/runs/$provider/$scenario
50+ rm -rf -- "$out"
51+ mkdir -p -- "$out"
52+ echo "== $provider / $scenario =="
53+ "$here/qa.sh" -C "$cwd" -o "$out" -e "$root/configs/$provider" \
54+ -n "qa-$provider-$scenario" -d "$duration" -s "$spec" > "$out/run.log" 2>&1 || true
55+ tail -n 3 "$out/run.log" | sed 's/^/ /'
56+}
57+
58+# A flag is "the app died" when the pane reports MINI-EXIT with a nonzero code,
59+# or the app never reached an idle prompt after the scenario's final step.
60+check() {
61+ local provider=$1 scenario=$2 expect=$3
62+ local out=$root/runs/$provider/$scenario
63+ local final=$out/final.txt
64+ local verdict="ok"
65+ if grep -q 'MINI-EXIT' "$final" && ! grep -q 'MINI-EXIT 0' "$final"; then
66+ verdict="CRASH"
67+ elif ! grep -q '\[complete' "$final"; then
68+ verdict="NO-TURN"
69+ elif ! grep -qiE "$expect" "$final"; then
70+ verdict="MISSING:$expect"
71+ fi
72+ printf '%-11s %-10s %s\n' "$provider" "$scenario" "$verdict"
73+}
74+
75+dur() {
76+ local want=$1
77+ if (( want > maxd )); then echo "$maxd"; else echo "$want"; fi
78+}
79+
80+for p in "${providers[@]}"; do
81+ run "$p" single "$(dur 40)" 'text=Read a.txt and tell me its contents in one short sentence;;key=enter;;wait=30;;shot=done'
82+ run "$p" multi "$(dur 55)" 'text=Read a.txt and b.txt, then tell me both contents;;key=enter;;wait=45;;shot=done'
83+ run "$p" cancel "$(dur 45)" 'text=Run this exact bash command: sleep 30; echo done;;key=enter;;wait=6;;shot=running;;key=ctrl+c;;wait=5;;shot=cancelled;;text=Say hi in one word;;key=enter;;wait=20;;shot=recovered'
84+ run "$p" pause "$(dur 55)" 'text=Run this exact bash command: sleep 12; echo HELLO. Then run: sleep 12; echo WORLD. Then say ALL DONE;;key=enter;;wait=4;;shot=running;;key=esc;;wait=13;;shot=paused;;text=Stop, just say STEERED;;key=enter;;wait=25;;shot=steered'
85+done
86+
87+echo
88+echo "summary (expect = text that must appear in final.txt, else MISSING):"
89+for p in "${providers[@]}"; do
90+ check "$p" single 'hello world'
91+ check "$p" multi 'foo bar'
92+ check "$p" cancel 'cancelled'
93+ check "$p" pause 'STEERED'
94+done
tools/qa.sh+225−0
@@ -0,0 +1,225 @@
1+#!/usr/bin/env bash
2+#
3+# qa.sh - drive the real TUI in a real kitty window through a timed script of
4+# keystrokes and prompts, screenshotting throughout. stress.sh types one prompt
5+# and watches; this fires submissions, cancellations and pauses at chosen times
6+# so turn control paths can be exercised on a repeatable run.
7+#
8+# tools/qa.sh -C <cwd> -o <outdir> -e <xdg config home> -s <spec> [-s <spec>...]
9+#
10+# A spec is a sequence of steps separated by ``;;``:
11+#
12+# wait=<seconds> pause before the next step
13+# text=<string> type the string into the editor (may contain commas)
14+# key=<name> press a key: enter, shift+enter, ctrl+c, esc, tab, ctrl+d
15+# shot=<label> write the pane text to <outdir>/mark-<n>-<label>.txt
16+#
17+# The first step runs once the banner is up. Every action is logged to
18+# <outdir>/steps.txt with its wall time. Frames land in <outdir>/frame-NNNNN.png
19+# and the final pane in final.txt / final-screen.txt.
20+
21+set -euo pipefail
22+
23+fps=15
24+seconds=180
25+name="qa-$$"
26+here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
27+bin=$here/../zig-out/bin/mini
28+cwd=$PWD
29+out=
30+xdg=
31+specs=()
32+
33+usage() {
34+ cat <<'EOF'
35+usage: qa.sh [options]
36+ -d seconds how long to capture at most (default 180)
37+ -r fps capture rate (default 15)
38+ -o outdir where frames go (required)
39+ -C cwd working directory mini runs in (default $PWD)
40+ -e path XDG_CONFIG_HOME holding mini-coding-agent/config.json
41+ -b path mini binary (default ../zig-out/bin/mini)
42+ -n name kitty session name (default qa-$$)
43+ -s spec a step list (repeatable), see the header comment
44+EOF
45+}
46+
47+while getopts 'd:r:o:C:e:b:n:s:h' opt; do
48+ case $opt in
49+ d) seconds=$OPTARG ;;
50+ r) fps=$OPTARG ;;
51+ o) out=$OPTARG ;;
52+ C) cwd=$OPTARG ;;
53+ e) xdg=$OPTARG ;;
54+ b) bin=$OPTARG ;;
55+ n) name=$OPTARG ;;
56+ s) specs+=("$OPTARG") ;;
57+ h) usage; exit 0 ;;
58+ *) usage; exit 2 ;;
59+ esac
60+done
61+
62+if (( fps <= 0 || seconds <= 0 )); then
63+ echo "qa: fps and seconds must be positive" >&2
64+ exit 2
65+fi
66+if [[ -z $out || ${#specs[@]} -eq 0 ]]; then
67+ usage >&2
68+ exit 2
69+fi
70+if [[ ! -x $bin ]]; then
71+ echo "qa: no executable at $bin (run zig build first)" >&2
72+ exit 2
73+fi
74+bin=$(readlink -f -- "$bin")
75+cwd=$(cd -- "$cwd" && pwd)
76+mkdir -p -- "$out"
77+out=$(readlink -f -- "$out")
78+socket=/tmp/mini-$name.sock
79+
80+now_ms() {
81+ local t=${EPOCHREALTIME/,/.}
82+ echo $(( ${t%.*} * 1000 + 10#${t#*.} / 1000 ))
83+}
84+
85+kt() { kitty @ --to "unix:$socket" "$@"; }
86+pane() { kt get-text -m "id:$wid" --extent="$1" --ansi 2>/dev/null; }
87+
88+wid=
89+cleanup() {
90+ if [[ -n $wid ]]; then
91+ kt close-window -m "id:$wid" >/dev/null 2>&1 || true
92+ fi
93+ rm -f -- "$socket"
94+}
95+trap cleanup EXIT
96+trap 'exit 1' INT TERM
97+
98+printf -v launch 'cd %q; %q; printf "\nMINI-EXIT %%d\n" $?; exec sleep 86400' "$cwd" "$bin"
99+
100+rm -f -- "$socket"
101+env_args=()
102+if [[ -n $xdg ]]; then
103+ env_args=(env "XDG_CONFIG_HOME=$xdg")
104+fi
105+kitty --detach --listen-on "unix:$socket" \
106+ -o allow_remote_control=yes -o remember_window_size=no \
107+ -o initial_window_width=110c -o initial_window_height=34c \
108+ --title "mini-$name" \
109+ "${env_args[@]}" bash --norc --noprofile -c "$launch"
110+
111+for _ in $(seq 100); do
112+ wid=$(kt ls 2>/dev/null | grep -o '"id": [0-9]*' | tail -n1 | tr -dc '0-9' || true)
113+ [[ -n $wid ]] && break
114+ sleep 0.1
115+done
116+if [[ -z $wid ]]; then
117+ echo "qa: kitty never reported a window on $socket" >&2
118+ exit 1
119+fi
120+
121+for _ in $(seq 300); do
122+ pane all | grep -q 'mini ·' && break
123+ sleep 0.1
124+done
125+if ! pane all | grep -q 'mini ·'; then
126+ echo "qa: mini did not start; pane says:" >&2
127+ pane all >&2
128+ exit 1
129+fi
130+
131+log=$out/steps.txt
132+: > "$log"
133+echo "qa: $out"
134+shot=0
135+
136+send_text() {
137+ kt send-text -m "id:$wid" "$1"
138+}
139+
140+send_key() {
141+ case $1 in
142+ enter) kt send-key -m "id:$wid" enter ;;
143+ shift+enter) kt send-key -m "id:$wid" shift+enter ;;
144+ ctrl+c) kt send-key -m "id:$wid" ctrl+c ;;
145+ esc) kt send-key -m "id:$wid" escape ;;
146+ tab) kt send-key -m "id:$wid" tab ;;
147+ ctrl+d) kt send-key -m "id:$wid" ctrl+d ;;
148+ *) echo "qa: unknown key $1" >&2; exit 2 ;;
149+ esac
150+}
151+
152+# Expand every -s spec into a flat list of "at_ms<TAB>verb<TAB>arg" lines.
153+steps=()
154+t=0
155+for spec in "${specs[@]}"; do
156+ spec=${spec//;;/$'\n'}
157+ while IFS= read -r part; do
158+ part=${part#"${part%%[![:space:]]*}"}
159+ [[ -z $part ]] && continue
160+ verb=${part%%=*}
161+ arg=${part#*=}
162+ if [[ $verb == wait ]]; then
163+ t=$(awk "BEGIN { printf \"%d\", $t + $arg * 1000 }")
164+ continue
165+ fi
166+ steps+=("$t $verb $arg")
167+ done < <(printf '%s\n' "$spec")
168+done
169+
170+exec_steps() {
171+ local now=$1
172+ while (( ${#steps[@]} > 0 )); do
173+ local line=${steps[0]}
174+ local at=${line%% *}
175+ if (( at > now - start )); then break; fi
176+ steps=("${steps[@]:1}")
177+ local rest=${line#* }
178+ local verb=${rest%% *}
179+ local arg=${rest#* }
180+ case $verb in
181+ text) send_text "$arg"; printf '%s text %s\n' "$(( now - start ))" "$arg" >> "$log" ;;
182+ key) send_key "$arg"; printf '%s key %s\n' "$(( now - start ))" "$arg" >> "$log" ;;
183+ shot)
184+ shot=$(( shot + 1 ))
185+ pane all > "$out/mark-$(printf '%02d' "$shot")-$arg.txt" || true
186+ printf '%s shot %s\n' "$(( now - start ))" "$arg" >> "$log"
187+ ;;
188+ *) echo "qa: unknown step $verb" >&2; exit 2 ;;
189+ esac
190+ done
191+}
192+
193+end_reason=
194+start=$(now_ms)
195+next=$start
196+frames=0
197+while :; do
198+ now=$(now_ms)
199+ (( now - start >= seconds * 1000 )) && break
200+ exec_steps $now
201+
202+ if ! kt screenshot -m "id:$wid" "$out/frame-$(printf '%05d' "$frames").png" >/dev/null 2>&1; then
203+ end_reason="window vanished after $frames frames"
204+ break
205+ fi
206+ frames=$(( frames + 1 ))
207+
208+ if pane screen | grep -q 'MINI-EXIT'; then
209+ end_reason=$(pane screen | grep -o 'MINI-EXIT -\?[0-9]*' | tail -n1)
210+ break
211+ fi
212+
213+ next=$(( next + 1000 / fps ))
214+ sleep "$(awk "BEGIN { printf \"%.3f\", 1 / $fps }")"
215+done
216+
217+exec_steps 999999999
218+elapsed=$(( $(now_ms) - start ))
219+pane all > "$out/final.txt" || true
220+pane screen > "$out/final-screen.txt" || true
221+
222+echo "qa: $frames frames in $(( elapsed / 1000 ))s"
223+if [[ -n $end_reason ]]; then
224+ echo "qa: ended early: $end_reason"
225+fi