Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix: show tool elapsed from start and drop first-turn delay

Cursor Agent28115af33fd9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6109f2a..e931563f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,10 @@ current is part of cutting a release.
steer or queue one prompt per line; Enter after the paste submits
exactly one (#643).
- Existing Tauri `gui/` is unchanged.
+- First-turn tool delay: live chips paint immediately (no 300–450ms
+ fade), ACP `tool_call` is `in_progress` and flushed, and the first
+ model call no longer waits for a deferred MCP handshake (ADR 0035).
+ Running tools show elapsed from the moment they start.
## v0.0.278 (2026-08-26)
diff --git a/TUI/app.zig b/TUI/app.zig
index 11e67a65..d62a5489 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -35,6 +35,8 @@ pub const ToolInfo = struct {
is_error: bool = false,
/// Refused by the harness before it ran.
denied: bool = false,
+ /// Engine-measured duration on a finished row. 0 while the call is live.
+ ms: u64 = 0,
};
pub const Entry = struct {
@@ -316,6 +318,7 @@ pub const Model = struct {
.done = info.done,
.is_error = info.is_error,
.denied = info.denied,
+ .ms = info.ms,
},
.at_ms = self.now_ms,
});
diff --git a/TUI/events.zig b/TUI/events.zig
index c8f1cc8e..912711e2 100644
--- a/TUI/events.zig
+++ b/TUI/events.zig
@@ -33,6 +33,8 @@ pub const Tool = struct {
is_error: bool = false,
/// The harness refused the call before it ran (tool_rejected).
denied: bool = false,
+ /// Wall-clock ms the engine measured (tool_finished). 0 while running.
+ ms: u64 = 0,
};
/// What the cost meter can say. Three of the four are STATES, not numbers, so
@@ -225,7 +227,7 @@ fn dupeTool(gpa: std.mem.Allocator, t: Tool) ?Tool {
gpa.free(name);
return null;
};
- return .{ .name = name, .detail = detail, .is_error = t.is_error, .denied = t.denied };
+ return .{ .name = name, .detail = detail, .is_error = t.is_error, .denied = t.denied, .ms = t.ms };
}
test "queue copies payloads, so an arena that dies with the turn cannot dangle" {
diff --git a/TUI/root.zig b/TUI/root.zig
index 68bdc96a..b23307e2 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -72,6 +72,7 @@ test {
_ = @import("glyphs.zig");
_ = @import("foldhdr.zig");
_ = @import("mdtable.zig");
+ _ = @import("tool_card.zig");
_ = @import("scrollback.zig");
_ = @import("layout_cache.zig");
_ = @import("selection.zig");
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 558ada71..19c9e581 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -9,6 +9,7 @@ const diff_mod = @import("diff.zig");
const foldhdr = @import("foldhdr.zig");
const glyphs = @import("glyphs.zig");
const theme_mod = @import("theme.zig");
+const tool_card = @import("tool_card.zig");
const Model = app.Model;
/// Soft pulse so a live turn reads as motion, not a lone spinner glyph.
@@ -231,7 +232,7 @@ pub fn row(self: *const Model, a: std.mem.Allocator, user_no: u32, e: app.Entry,
// pushes an empty row and gets the generic label.
(if (e.text.len > 0) e.text else thinkingLabel(now_ms))
else if (e.kind == .tool)
- try toolTitle(a, e, e)
+ try tool_card.toolTitle(a, e, e, now_ms)
else if (e.folded)
firstLine(e.text)
else
@@ -275,23 +276,7 @@ const isDoneTool = foldhdr.isDoneTool;
pub const nextTool = foldhdr.nextTool;
const displayName = foldhdr.displayName;
-/// The head of a tool row: `[status mark] name [argument preview]`, composed
-/// from FIELDS. On a paired card the name and its arguments come from the call
-/// (`named`) while the status mark comes from the outcome (`status`); on a lone
-/// row both are the same entry. A legacy row has only its stored line and is
-/// shown verbatim rather than taken apart — the old code split that line on
-/// " | ", which silently truncated any command containing one.
-fn toolTitle(a: std.mem.Allocator, named: app.Entry, status: app.Entry) ![]const u8 {
- const t = named.tool orelse return named.text;
- const mark: []const u8 = if (status.tool) |s|
- (if (s.denied) glyphs.denied ++ " " else if (s.is_error) glyphs.failed ++ " " else "")
- else
- "";
- const name = displayName(t.name);
- const args = if (t.done) "" else t.detail;
- if (args.len == 0) return if (mark.len == 0) name else std.fmt.allocPrint(a, "{s}{s}", .{ mark, name });
- return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, args });
-}
+const toolTitle = tool_card.toolTitle;
/// The one-line body under a tool card: the outcome's useful detail.
fn toolPreview(e: app.Entry) ?[]const u8 {
@@ -312,12 +297,12 @@ pub fn toolVisual(
const e = self.history.items[t];
const paired = t + 1 < end and isStartTool(e) and isDoneTool(self.history.items[t + 1]);
if (!paired) return row(self, a, 0, e, width, now_ms, selected); // a tool row is never numbered
- return toolCard(a, self.theme(), e, self.history.items[t + 1], selected, width);
+ return toolCard(a, self.theme(), e, self.history.items[t + 1], selected, width, now_ms);
}
-fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, call: app.Entry, outcome: app.Entry, selected: bool, width: usize) ![]const u8 {
+fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, call: app.Entry, outcome: app.Entry, selected: bool, width: usize, now_ms: u64) ![]const u8 {
const sel = glyphs.frame(&glyphs.row_mark, @intFromBool(!selected));
- const title = try toolTitle(a, call, outcome);
+ const title = try toolTitle(a, call, outcome, now_ms);
const preview = toolPreview(outcome);
const head = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}", .{ sel, if (selected) th.accent else th.muted, glyphs.tool, theme_mod.reset, th.text, title });
if (preview == null) return theme_mod.wrapToWidth(a, head, width);
diff --git a/TUI/tool_card.zig b/TUI/tool_card.zig
new file mode 100644
index 00000000..57d5a9aa
--- /dev/null
+++ b/TUI/tool_card.zig
@@ -0,0 +1,72 @@
+//! Tool-row title + live elapsed. Split from scrollback.zig so the 600-line
+//! ceiling has room for the duration suffix without a scrollback/card cycle.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const foldhdr = @import("foldhdr.zig");
+const glyphs = @import("glyphs.zig");
+
+const displayName = foldhdr.displayName;
+
+/// Elapsed for a running row (`now - at`) or a finished one (`recorded_ms`).
+/// Hidden under 100ms so a fast read does not flicker `0ms`.
+pub fn timingSuffix(buf: []u8, done: bool, recorded_ms: u64, now_ms: u64, at_ms: u64) []const u8 {
+ const ms: u64 = if (done) recorded_ms else now_ms -| at_ms;
+ if (ms < 100) return "";
+ return formatElapsed(buf, ms);
+}
+
+pub fn formatElapsed(buf: []u8, ms: u64) []const u8 {
+ if (ms < 1000) return std.fmt.bufPrint(buf, "{d}ms", .{ms}) catch "";
+ const s = ms / 1000;
+ if (s < 60) {
+ const tenths = (ms / 100) % 10;
+ if (tenths == 0) return std.fmt.bufPrint(buf, "{d}s", .{s}) catch "";
+ return std.fmt.bufPrint(buf, "{d}.{d}s", .{ s, tenths }) catch "";
+ }
+ return std.fmt.bufPrint(buf, "{d}m{d:0>2}s", .{ s / 60, s % 60 }) catch "";
+}
+
+/// The head of a tool row: `[status mark] name [argument preview] [elapsed]`.
+pub fn toolTitle(a: std.mem.Allocator, named: app.Entry, status: app.Entry, now_ms: u64) ![]const u8 {
+ const t = named.tool orelse return named.text;
+ const mark: []const u8 = if (status.tool) |s|
+ (if (s.denied) glyphs.denied ++ " " else if (s.is_error) glyphs.failed ++ " " else "")
+ else
+ "";
+ const name = displayName(t.name);
+ const args = if (t.done) "" else t.detail;
+ const recorded = if (status.tool) |s| s.ms else t.ms;
+ const done = t.done or if (status.tool) |s| s.done else false;
+ var tbuf: [16]u8 = undefined;
+ const timing = timingSuffix(&tbuf, done, recorded, now_ms, named.at_ms);
+ if (args.len == 0 and timing.len == 0)
+ return if (mark.len == 0) name else std.fmt.allocPrint(a, "{s}{s}", .{ mark, name });
+ if (args.len == 0)
+ return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, timing });
+ if (timing.len == 0)
+ return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, args });
+ return std.fmt.allocPrint(a, "{s}{s} {s} {s}", .{ mark, name, args, timing });
+}
+
+test "timingSuffix hides sub-100ms, then shows live and recorded" {
+ var buf: [16]u8 = undefined;
+ try std.testing.expectEqualStrings("", timingSuffix(&buf, false, 0, 50, 0));
+ try std.testing.expectEqualStrings("120ms", timingSuffix(&buf, false, 0, 120, 0));
+ try std.testing.expectEqualStrings("1.2s", timingSuffix(&buf, true, 1200, 0, 0));
+ try std.testing.expectEqualStrings("3s", timingSuffix(&buf, true, 3000, 0, 0));
+}
+
+test "toolTitle appends elapsed on a running row" {
+ const e: app.Entry = .{
+ .kind = .tool,
+ .text = "ls",
+ .at_ms = 0,
+ .tool = .{ .name = "bash", .detail = "ls -la", .done = false },
+ };
+ const title = try toolTitle(std.testing.allocator, e, e, 1500);
+ defer std.testing.allocator.free(title);
+ try std.testing.expect(std.mem.indexOf(u8, title, "bash") != null);
+ try std.testing.expect(std.mem.indexOf(u8, title, "1.5s") != null);
+}
diff --git a/TUI/turn.zig b/TUI/turn.zig
index bfd20453..ef68b224 100644
--- a/TUI/turn.zig
+++ b/TUI/turn.zig
@@ -224,6 +224,7 @@ fn applyEvent(self: *Model, ev: engine.Event) void {
.detail = t.detail,
.done = true,
.is_error = t.is_error,
+ .ms = t.ms,
}) catch {};
},
.tool_rejected => |t| {
diff --git a/apps/native/components/primitives/ThinkingState.tsx b/apps/native/components/primitives/ThinkingState.tsx
index 17b4ba4e..f4f4bc3b 100644
--- a/apps/native/components/primitives/ThinkingState.tsx
+++ b/apps/native/components/primitives/ThinkingState.tsx
@@ -251,7 +251,7 @@ export default function ThinkingState({
</>
);
const rowClass = "flex min-h-7 w-full items-center gap-2 rounded-[6px] px-1.5 py-0.5 text-left";
- const animation = { animation: `fade-up 320ms cubic-bezier(0.23,1,0.32,1) ${i * 120}ms both` };
+ const animation = live ? undefined : { animation: `fade-up 320ms cubic-bezier(0.23,1,0.32,1) ${i * 120}ms both` };
if (variant === "Search") {
return (
diff --git a/apps/native/components/primitives/ToolChips.tsx b/apps/native/components/primitives/ToolChips.tsx
index 4799e5a9..b1cec940 100644
--- a/apps/native/components/primitives/ToolChips.tsx
+++ b/apps/native/components/primitives/ToolChips.tsx
@@ -90,8 +90,28 @@ export type LiveToolRow = {
mono?: boolean;
detailMono?: boolean;
detail: { text: string; tone?: "add" }[];
+ status?: "running" | "ok" | "error";
+ startedAt?: number;
+ elapsedMs?: number;
};
+function formatElapsed(ms: number): string {
+ if (ms < 1000) return `${Math.round(ms)}ms`;
+ const s = ms / 1000;
+ if (s < 60) return s < 10 ? `${s.toFixed(1)}s` : `${Math.round(s)}s`;
+ return `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
+}
+
+function useNow(active: boolean): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!active) return;
+ const id = setInterval(() => setNow(Date.now()), 250);
+ return () => clearInterval(id);
+ }, [active]);
+ return now;
+}
+
export type LiveDiff = {
file: string;
add: number;
@@ -112,6 +132,8 @@ export default function ToolChips({
const diffLines: Record<string, { text: string; tone: "add" | "del" | "ctx" }[]> = live
? Object.fromEntries((liveDiffs ?? []).map((d) => [d.file, d.lines ?? []]))
: DIFF_LINES;
+ const liveRunning = live && rows.some((row) => row.status === "running");
+ const now = useNow(Boolean(liveRunning));
const [step, setStep] = useState(0);
const [open, setOpen] = useState(true);
const [openRows, setOpenRows] = useState<Set<string>>(new Set());
@@ -177,7 +199,7 @@ export default function ToolChips({
{(live ? rows : rows.slice(0, step)).map((row) => {
const rowOpen = openRows.has(row.label);
return (
- <div key={"id" in row && row.id ? row.id : row.label} style={{ animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>
+ <div key={"id" in row && row.id ? row.id : row.label} style={live ? undefined : { animation: "fade-up 300ms cubic-bezier(0.23,1,0.32,1) both" }}>
<button
type="button"
aria-expanded={rowOpen}
@@ -200,6 +222,14 @@ export default function ToolChips({
</svg>
</span>
<span className="shrink-0 text-[12.5px] font-medium text-ink">{row.label}</span>
+ {live && (() => {
+ const ms = row.status === "running" && row.startedAt
+ ? now - row.startedAt
+ : row.elapsedMs;
+ return ms !== undefined && ms >= 100 ? (
+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-ink-3">{formatElapsed(ms)}</span>
+ ) : null;
+ })()}
<span
className={`inline-flex h-5.5 min-w-0 flex-1 cursor-pointer items-center truncate rounded-chip bg-field px-1.5
text-[11.5px] text-ink-2 shadow-hairline transition-colors duration-100 hover:bg-hover-2
@@ -252,7 +282,7 @@ export default function ToolChips({
className="inline-flex h-7 max-w-full items-center gap-1.5 rounded-chip
bg-surface px-2 font-mono text-[11.5px] text-ink shadow-btn
transition-colors duration-100 hover:bg-hover"
- style={{ animation: `pop-in 250ms cubic-bezier(0.23,1,0.32,1) ${i * 80}ms both` }}
+ style={live ? undefined : { animation: `pop-in 250ms cubic-bezier(0.23,1,0.32,1) ${i * 80}ms both` }}
>
<span className="min-w-0 truncate">{d.file}</span>
<span className="shrink-0 text-green tabular-nums">+{d.add}</span>
@@ -266,7 +296,7 @@ export default function ToolChips({
className="inline-flex h-7 items-center rounded-chip px-1.5 font-mono text-[11.5px] text-ink-3
underline decoration-transparent underline-offset-2 transition-colors duration-100
hover:text-ink-2 hover:decoration-current"
- style={{ animation: `fade-in 300ms ease-out ${DIFFS.length * 80}ms both` }}
+ style={live ? undefined : { animation: `fade-in 300ms ease-out ${DIFFS.length * 80}ms both` }}
>
{live ? `${diffs.length} files` : "+2 more"}
</button>
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index be3d3d4e..e20f93dd 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -63,10 +63,13 @@ function AssistantBody({ turn }: { turn: AssistantTurn }) {
mono: tool.icon === "run" || tool.icon === "write" || tool.icon === "read",
detailMono: tool.icon === "run" || tool.icon === "write",
detail: tool.detail,
+ status: tool.status,
+ startedAt: tool.startedAt,
+ elapsedMs: tool.elapsedMs,
}));
return (
- <article className="min-w-0" style={{ animation: "fade-up 450ms cubic-bezier(0.23,1,0.32,1) both" }}>
+ <article className="min-w-0">
{(turn.status === "thinking" || reasoningRows.length > 0) && (
<ThinkingState
variant="Reasoning"
diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.ts
index ec5396f1..d82ab932 100644
--- a/apps/native/lib/acp.test.ts
+++ b/apps/native/lib/acp.test.ts
@@ -42,6 +42,7 @@ describe("applyAcpUpdate", () => {
assert.equal(turn.tools[0]?.status, "running");
assert.equal(turn.tools[0]?.chip, "src/main.zig");
assert.equal(turn.tools[0]?.name, "Read");
+ assert.ok((turn.tools[0]?.startedAt ?? 0) > 0);
turn = applyAcpUpdate(turn, {
sessionUpdate: "tool_call_update",
toolCallId: "call-1",
diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index 119b3eb2..d67b0707 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -151,6 +151,11 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
: fromInput.length
? fromInput
: (prev?.detail ?? []);
+ const startedAt = prev?.startedAt ?? Date.now();
+ const elapsedMs =
+ status === "running"
+ ? prev?.elapsedMs
+ : (prev?.elapsedMs ?? Math.max(0, Date.now() - startedAt));
const row: ToolRow = {
id,
name: labelForKind(kind, title),
@@ -159,10 +164,12 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
status,
detail,
path,
+ startedAt,
+ elapsedMs,
};
const tools = turn.tools.slice();
const merged: ToolRow = idx >= 0
- ? { ...prev!, ...row, name: kind ? row.name : prev!.name, icon: kind ? row.icon : prev!.icon }
+ ? { ...prev!, ...row, name: kind ? row.name : prev!.name, icon: kind ? row.icon : prev!.icon, startedAt, elapsedMs }
: row;
if (idx >= 0) tools[idx] = merged;
else tools.push(merged);
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index 7ca7b115..d9ecb449 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -50,6 +50,10 @@ export type ToolRow = {
status: "running" | "ok" | "error";
detail: { text: string; tone?: "add" }[];
path?: string;
+ /** Epoch ms when the chip first appeared — live elapsed from this. */
+ startedAt?: number;
+ /** Frozen duration once the tool finished. */
+ elapsedMs?: number;
};
export type DiffChip = {
diff --git a/docs/adr/0035-first-turn-skips-deferred-mcp-join.md b/docs/adr/0035-first-turn-skips-deferred-mcp-join.md
new file mode 100644
index 00000000..2c05406c
--- /dev/null
+++ b/docs/adr/0035-first-turn-skips-deferred-mcp-join.md
@@ -0,0 +1,23 @@
+# 0035. First model call does not wait for deferred MCP
+
+Status: accepted 2026-08-26
+
+## Context
+
+Interactive `--yolo` (including `graff acp`) starts MCP handshakes in the
+background so the prompt can paint. The first `request()` still called
+`joinPending`, so a silent stdio probe (default 5s) or a 15s handshake cap
+blocked every native tool on the first turn. The chips looked late; the
+model had not even been called.
+
+## Decision
+
+`joinBeforeRequest` skips the wait once. Native tools run on the first
+turn. MCP catalogs merge on the next request, `/mcp`, or teardown. A dim
+notice says so when a TUI sink is attached.
+
+## Consequences
+
+A one-shot first turn that *only* has MCP tools will not see them until
+the second request. `/mcp` still blocks. Revisit if a session is MCP-only
+and the first prompt must use those tools.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 402d02b6..7d8f8072 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -45,6 +45,7 @@ record only when you need the evidence or the edge cases.
| [0032](0032-acp-streams-mid-turn.md) | `graff acp` streams thought / tool / text `session/update`s mid-turn. The native app is an ACP client; it does not need `graff serve`. |
| [0033](0033-user-can-retire-a-standing-constraint.md) | Only the user retires a standing constraint: TTY `/never` picker (two confirms), ACP/`rm`, or an explicit override. The model cannot. |
| [0034](0034-remote-images-stay-native.md) | JSON/serve image inputs are a typed URL/base64 union, validated atomically and preserved as native provider vision blocks; never flatten pixels into prompt text. |
+| [0035](0035-first-turn-skips-deferred-mcp-join.md) | First model call after a deferred MCP boot does not wait for the handshake; native tools run now, MCP catalogs merge on the next request. |
## When to write one
diff --git a/docs/releases/v0.0.279.md b/docs/releases/v0.0.279.md
index 3cefa6b7..94f3a62d 100644
--- a/docs/releases/v0.0.279.md
+++ b/docs/releases/v0.0.279.md
@@ -98,6 +98,15 @@ read) cannot invoke Enter/send, so they no longer steer the live turn or
queue one prompt per line. An explicit Enter after the paste submits or
queues exactly one user prompt.
+## First-turn tools are immediate (ADR 0035)
+
+The first model call after `--yolo` / `graff acp` no longer waits for
+deferred MCP handshakes (silent stdio probe default 5s). Native tools
+run on that turn; MCP catalogs merge on the next request. Live ACP
+`tool_call` is `in_progress` and flushed so chips appear as the tool
+starts. The native app skips the demo fade-up/stagger on live rows and
+shows elapsed from start.
+
## Tests
Unit suite grows by the ACP translator cases (`kindFor`, thought/text
diff --git a/src/acp_stream.zig b/src/acp_stream.zig
index 3c03f8d1..fa9e79d1 100644
--- a/src/acp_stream.zig
+++ b/src/acp_stream.zig
@@ -53,7 +53,7 @@ pub fn writeToolCall(w: *Io.Writer, session_id: []const u8, id: []const u8, name
.toolCallId = id,
.title = titleFor(name, input),
.kind = kindFor(name),
- .status = "pending",
+ .status = "in_progress",
.rawInput = input,
},
});
@@ -250,6 +250,7 @@ test "translateEvent: tool_call then tool_result share a minted id" {
try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"sessionUpdate\":\"tool_call\"") != null);
try testing.expect(std.mem.indexOf(u8, w.buffered(), "call-1") != null);
try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"kind\":\"read\"") != null);
+ try testing.expect(std.mem.indexOf(u8, w.buffered(), "\"status\":\"in_progress\"") != null);
w = .fixed(&buf);
const result = try std.json.parseFromSlice(Value, a, "{\"type\":\"tool_result\",\"name\":\"read_file\",\"is_error\":false,\"text\":\"fn main\"}", .{});
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 192c22da..377325dd 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -117,7 +117,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// title task rendezvous here, then issue their requests concurrently.
http.waitForClientReady(self.io);
if (self.registry) |reg| {
- if (@import("mcp_boot.zig").joinPending(reg)) {
+ if (@import("mcp_boot.zig").joinBeforeRequest(reg)) {
self.invalidateRootTools();
try self.ensureRootTools(self.provider.kind);
}
diff --git a/src/cli.zig b/src/cli.zig
index 985fbe0c..02259ddb 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -27,6 +27,7 @@ pub const changelog_text =
\\ • /never on a TTY is a searchable picker with two confirms; rm and ACP list still work (#638)
\\ • bash_output wait_ms>0 always waits for exit — mid-range values are not a timeout (#640)
\\ • host recipe: docs/embedding.md; @codegraff/sdk/acp spawns graff acp
+ \\ • first-turn tools: no MCP handshake wait, live chips show elapsed from start (ADR 0035)
\\
\\0.0.278
\\ • deleted composer screenshots are not sent: submit keeps [Image #N] / @[path] only (#634)
diff --git a/src/mcp.zig b/src/mcp.zig
index ae0a4895..b24f4168 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -91,6 +91,8 @@ pub const Registry = struct {
task_arenas: []std.heap.ArenaAllocator = &.{},
/// Unjoined startServer futures from a deferred --yolo boot.
pending_starts: []Io.Future(mcp_boot.StartOutcome) = &.{},
+ /// First model call already declined to wait on `pending_starts` (ADR 0035).
+ first_request_join_skipped: bool = false,
pub fn arena(self: *Registry) Allocator {
return self.arena_state.allocator();
diff --git a/src/mcp_boot.zig b/src/mcp_boot.zig
index 90f51ff7..d426b72a 100644
--- a/src/mcp_boot.zig
+++ b/src/mcp_boot.zig
@@ -8,8 +8,9 @@
//! shorter: max(latency) instead of sum(latency).
//!
//! Interactive `--yolo` sets `defer_join`: tasks start immediately but the
-//! REPL prompt is not blocked. `joinPending` merges them before the first
-//! model call, `/mcp`, or teardown.
+//! REPL prompt is not blocked. `joinBeforeRequest` merges them on the *second*
+//! model call (ADR 0035) so the first turn is not charged the handshake.
+//! `joinPending` still blocks for `/mcp` and teardown.
const std = @import("std");
@@ -168,15 +169,57 @@ fn mergeOutcomes(reg: *Registry, futures: []Io.Future(StartOutcome)) void {
reg.task_arenas = a.dupe(std.heap.ArenaAllocator, task_arenas.items) catch reg.task_arenas;
}
+/// Pure policy for the first model call after a deferred MCP boot. The
+/// handshake tasks are already running; waiting here is the delay before
+/// any native tool can start. Skip once, then join.
+pub fn firstRequestJoin(pending_len: usize, already_skipped: *bool) enum { none, skip, join } {
+ if (pending_len == 0) return .none;
+ if (!already_skipped.*) {
+ already_skipped.* = true;
+ return .skip;
+ }
+ return .join;
+}
+
+fn noteMcpDeferred(io: Io) void {
+ const sink = @import("engine_sink.zig").hostedSink() orelse return;
+ sink.emit(io, .{ .session_notice = .{
+ .text = "MCP still connecting — native tools this turn",
+ .tone = .dim,
+ } });
+}
+
+/// First model call: do not wait for deferred MCP handshakes (ADR 0035).
+/// Later requests, `/mcp`, and teardown still `joinPending`.
+pub fn joinBeforeRequest(reg: *Registry) bool {
+ switch (firstRequestJoin(reg.pending_starts.len, &reg.first_request_join_skipped)) {
+ .none => return false,
+ .skip => {
+ noteMcpDeferred(reg.io);
+ return false;
+ },
+ .join => return joinPending(reg),
+ }
+}
+
/// Await deferred startServer tasks and append them to the live registry
/// (companion servers may already be present). Idempotent. Returns true
/// when this call actually merged something, so the agent can rebuild catalogs.
pub fn joinPending(reg: *Registry) bool {
if (reg.pending_starts.len == 0) return false;
+ const t0 = std.time.milliTimestamp();
const futures = reg.pending_starts;
reg.pending_starts = &.{};
mergeOutcomes(reg, futures);
reg.gpa.free(futures);
+ const waited = std.time.milliTimestamp() - t0;
+ if (waited >= 80) {
+ if (@import("engine_sink.zig").hostedSink()) |sink| {
+ var buf: [80]u8 = undefined;
+ const text = std.fmt.bufPrint(&buf, "MCP connect waited {d}ms", .{waited}) catch "";
+ if (text.len > 0) sink.emit(reg.io, .{ .session_notice = .{ .text = text, .tone = .dim } });
+ }
+ }
return true;
}
@@ -192,4 +235,15 @@ test "joinPending is a no-op on an empty registry" {
var reg = Registry.empty(std.testing.allocator, io);
defer reg.deinit();
try std.testing.expect(!joinPending(&reg));
+ try std.testing.expect(!joinBeforeRequest(&reg));
+}
+
+test "firstRequestJoin skips once, then joins" {
+ var skipped = false;
+ try std.testing.expectEqual(.none, firstRequestJoin(0, &skipped));
+ try std.testing.expect(!skipped);
+ try std.testing.expectEqual(.skip, firstRequestJoin(2, &skipped));
+ try std.testing.expect(skipped);
+ try std.testing.expectEqual(.join, firstRequestJoin(2, &skipped));
+ try std.testing.expectEqual(.none, firstRequestJoin(0, &skipped));
}
diff --git a/src/tui_sink.zig b/src/tui_sink.zig
index 0586ff12..b0e7b3f1 100644
--- a/src/tui_sink.zig
+++ b/src/tui_sink.zig
@@ -128,6 +128,7 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {
.name = r.name,
.detail = capLine(r.text, preview_cap),
.is_error = r.is_error,
+ .ms = @intCast(@max(0, r.ms)),
} });
},
// The harness refused the call before it ran. hostedEmit dropped this
@@ -260,6 +261,24 @@ test "prose streams into the live tail; structure never does" {
try std.testing.expect(!evs[1].tool_finished.is_error);
}
+test "tool_finished carries the engine's measured ms" {
+ var qbuf: tui.EventQueue = .{};
+ qbuf.attach(std.testing.allocator);
+ defer qbuf.deinit();
+ var sbuf: [64]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &sbuf };
+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };
+ forBridge(&bridge).emit(undefined, .{ .tool_result = .{
+ .name = "read_file",
+ .text = "ok",
+ .is_error = false,
+ .ms = 240,
+ } });
+ const evs = qbuf.drain();
+ defer qbuf.free(evs);
+ try std.testing.expectEqual(@as(u64, 240), evs[0].tool_finished.ms);
+}
+
test "reasoning reaches the tail only with /thinking on" {
var qbuf: tui.EventQueue = .{};
qbuf.attach(std.testing.allocator);