Skip to content

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

Python

fix ACP background child session and frame ownership

Rach Pradhan117f9291d47e
diff --git a/scripts/test-acp-background-subagent.py b/scripts/test-acp-background-subagent.py
index bbd4375c..0ff4f461 100644
--- a/scripts/test-acp-background-subagent.py
+++ b/scripts/test-acp-background-subagent.py
@@ -66,11 +66,23 @@ def child_events(client):
return [row['params'] for row in client.events if row.get('method') == 'graff/subagent_event']
-def run(binary, capability=True, cancel=False, disconnect=False):
+def run(binary, capability=True, cancel=False, disconnect=False, switch_session=False):
with tempfile.TemporaryDirectory(prefix='graff-acp-background-') as temporary:
work = Path(temporary)
home = work / 'home'
home.mkdir()
+ other_sid = None
+ if switch_session:
+ seed_model = load.ScriptedModel([])
+ seed_port = seed_model.start(0)
+ seed = load.Acp(binary, work, home, seed_port, extra_env={'GRAFF_NO_NATIVE_FOLD': '1'})
+ try:
+ seed.request('initialize', {'protocolVersion': 1})
+ other_sid = seed.request('session/new', {'cwd': str(work), 'mcpServers': []})['result']['sessionId']
+ finally:
+ seed.close()
+ seed_model.stop()
+ assert (work / '.graff' / 'sessions' / f'{other_sid}.session.json').exists()
model = Model()
port = model.start(0)
client = load.Acp(binary, work, home, port, extra_env={'GRAFF_NO_NATIVE_FOLD': '1'},
@@ -99,6 +111,14 @@ def run(binary, capability=True, cancel=False, disconnect=False):
assert all(row['subagentSessionId'] == spawn['subagentSessionId'] and
row['parentToolCallId'] == spawn['parentToolCallId'] for row in rows), rows
assert not any(row['event']['type'] == 'terminal' for row in rows), rows
+ if switch_session:
+ assert other_sid != sid
+ loaded = client.request('session/load', {'sessionId': other_sid,
+ 'cwd': str(work), 'mcpServers': []})
+ assert 'result' in loaded, loaded
+ # Reinitialization may disable future children; this child was
+ # already announced and must retain its stream and parent ID.
+ client.request('initialize', {'protocolVersion': 1, 'clientCapabilities': {}})
if disconnect:
client.proc.stdin.close()
# ACP detaches its emitter before waiting for the held worker
@@ -131,6 +151,7 @@ def run(binary, capability=True, cancel=False, disconnect=False):
and row['params']['event']['type'] == 'terminal')
assert terminal['params']['event']['state'] == ('cancelled' if cancel else 'completed')
rows = child_events(client)
+ assert all(row['parentSessionId'] == sid for row in rows), rows
assert [row['seq'] for row in rows] == list(range(len(rows))), rows
assert rows[-1]['event']['type'] == 'terminal', rows
assert rows[-1]['seq'] > 0, rows
@@ -146,4 +167,5 @@ if __name__ == '__main__':
run(binary)
run(binary, cancel=True)
run(binary, disconnect=True)
- print('ACP background subagents: opt-in, cross-turn stream, cancellation, ordered JSON frames, teardown')
+ run(binary, switch_session=True)
+ print('ACP background subagents: opt-in, cross-turn stream, session switch, cancellation, ordered JSON frames, teardown')
diff --git a/src/acp.zig b/src/acp.zig
index c36f86a6..27e82df7 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -212,7 +212,10 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
framed.init(io, out, &transport_lock);
defer framed.deinit();
const wire = &framed.writer;
- var permission_bridge: @import("acp_permission.zig").Bridge = .{ .io = io, .out = wire };
+ var permission_framed: @import("acp_line_writer.zig").LineWriter = undefined;
+ permission_framed.init(io, out, &transport_lock);
+ defer permission_framed.deinit();
+ var permission_bridge: @import("acp_permission.zig").Bridge = .{ .io = io, .out = &permission_framed.writer };
const previous_permission = root.permission;
root.permission = permission_bridge.handler();
defer root.permission = previous_permission;
diff --git a/src/acp_line_writer.zig b/src/acp_line_writer.zig
index 5052cee1..05c50871 100644
--- a/src/acp_line_writer.zig
+++ b/src/acp_line_writer.zig
@@ -68,3 +68,26 @@ test "ACP writer does not expose partial JSON lines" {
try framed.writer.flush();
try std.testing.expectEqualStrings("{\"id\":1}\n{\"id\":2}\n", transport.buffered());
}
+
+test "independent producers keep interleaved partial JSON frames intact" {
+ const io = std.testing.io;
+ var transport_buf: [256]u8 = undefined;
+ var transport: Io.Writer = .fixed(&transport_buf);
+ var lock: Io.Mutex = .init;
+ var main_writer: LineWriter = undefined;
+ main_writer.init(io, &transport, &lock);
+ defer main_writer.deinit();
+ var permission_writer: LineWriter = undefined;
+ permission_writer.init(io, &transport, &lock);
+ defer permission_writer.deinit();
+ try main_writer.writer.writeAll("{\"from\":\"main\"");
+ try main_writer.writer.flush();
+ try permission_writer.writer.writeAll("{\"from\":\"permission\"");
+ try permission_writer.writer.flush();
+ try std.testing.expectEqual(@as(usize, 0), transport.buffered().len);
+ try permission_writer.writer.writeAll("}\n");
+ try permission_writer.writer.flush();
+ try main_writer.writer.writeAll("}\n");
+ try main_writer.writer.flush();
+ try std.testing.expectEqualStrings("{\"from\":\"permission\"}\n{\"from\":\"main\"}\n", transport.buffered());
+}
diff --git a/src/acp_subagent_live.zig b/src/acp_subagent_live.zig
index d8f57256..3791f2d6 100644
--- a/src/acp_subagent_live.zig
+++ b/src/acp_subagent_live.zig
@@ -23,13 +23,24 @@ pub const BackgroundState = struct {
output_lock: *Io.Mutex,
parent: []const u8 = "",
enabled: bool = false,
+ generation: u64 = 0,
};
var background: ?*BackgroundState = null;
+var next_background_generation: u64 = 0;
+
+/// Owned by the detached child, rather than the mutable ACP dispatch session.
+pub const BackgroundHandle = struct {
+ parent: []const u8,
+ generation: u64,
+ parent_call_id: []const u8,
+};
pub fn installBackground(io: Io, state: *BackgroundState) void {
main.g_gui_mu.lockUncancelable(io);
defer main.g_gui_mu.unlock(io);
+ next_background_generation +%= 1;
+ state.generation = next_background_generation;
background = state;
}
@@ -49,17 +60,15 @@ pub fn configureBackground(io: Io, parent: []const u8, enabled: bool) void {
state.enabled = enabled;
}
-fn backgroundSend(io: Io, id: []const u8, parent_call_id: []const u8, seq: u64, event: anytype) bool {
- main.g_gui_mu.lockUncancelable(io);
- defer main.g_gui_mu.unlock(io);
+fn backgroundSendLocked(io: Io, handle: BackgroundHandle, id: []const u8, seq: u64, event: anytype) bool {
const state = background orelse return false;
- if (!state.enabled or state.parent.len == 0) return false;
+ if (state.generation != handle.generation) return false;
state.output_lock.lockUncancelable(io);
defer state.output_lock.unlock(io);
proto.writeNotification(state.out, "graff/subagent_event", .{
- .parentSessionId = state.parent,
+ .parentSessionId = handle.parent,
.subagentSessionId = id,
- .parentToolCallId = parent_call_id,
+ .parentToolCallId = handle.parent_call_id,
.seq = seq,
.event = event,
}) catch return false;
@@ -67,16 +76,32 @@ fn backgroundSend(io: Io, id: []const u8, parent_call_id: []const u8, seq: u64,
return true;
}
-pub fn announceBackground(io: Io, id: []const u8, name: []const u8, task: []const u8, parent_call_id: []const u8) bool {
- return backgroundSend(io, id, parent_call_id, 0, .{
+fn backgroundSend(io: Io, handle: BackgroundHandle, id: []const u8, seq: u64, event: anytype) bool {
+ main.g_gui_mu.lockUncancelable(io);
+ defer main.g_gui_mu.unlock(io);
+ return backgroundSendLocked(io, handle, id, seq, event);
+}
+
+pub fn announceBackground(a: std.mem.Allocator, io: Io, id: []const u8, name: []const u8, task: []const u8, parent_call_id: []const u8) ?BackgroundHandle {
+ main.g_gui_mu.lockUncancelable(io);
+ defer main.g_gui_mu.unlock(io);
+ const state = background orelse return null;
+ if (!state.enabled or state.parent.len == 0) return null;
+ const handle: BackgroundHandle = .{
+ .parent = a.dupe(u8, state.parent) catch return null,
+ .generation = state.generation,
+ .parent_call_id = parent_call_id,
+ };
+ if (!backgroundSendLocked(io, handle, id, 0, .{
.type = "spawn",
.name = util.utf8Prefix(name, 256),
.task = util.utf8Prefix(task, 2048),
- });
+ })) return null;
+ return handle;
}
-pub fn finishBackground(io: Io, id: []const u8, parent_call_id: []const u8, seq: u64, outcome: []const u8) void {
- _ = backgroundSend(io, id, parent_call_id, seq, .{ .type = "terminal", .state = outcome });
+pub fn finishBackground(io: Io, handle: BackgroundHandle, id: []const u8, seq: u64, outcome: []const u8) void {
+ _ = backgroundSend(io, handle, id, seq, .{ .type = "terminal", .state = outcome });
}
pub fn eligible(kind: []const u8, depth: u8, detached: bool) bool {
@@ -133,7 +158,7 @@ pub const ChildSink = struct {
id: []const u8,
io: Io,
recorder: ?sink.EngineSink = null,
- background_call_id: ?[]const u8 = null,
+ background_handle: ?BackgroundHandle = null,
seq: u64 = 1,
pub fn engineSink(self: *ChildSink) sink.EngineSink {
@@ -145,8 +170,8 @@ pub const ChildSink = struct {
fn emit(ctx: *anyopaque, stamped: sink.Stamped) void {
const self: *ChildSink = @ptrCast(@alignCast(ctx));
if (self.recorder) |record| record.vt.emit(record.ctx, stamped);
- if (self.background_call_id) |call_id| {
- self.emitBackground(stamped, call_id);
+ if (self.background_handle) |handle| {
+ self.emitBackground(stamped, handle);
return;
}
main.g_gui_mu.lockUncancelable(self.io);
@@ -172,7 +197,7 @@ pub const ChildSink = struct {
w.flush() catch {};
}
- fn emitBackground(self: *ChildSink, stamped: sink.Stamped, call_id: []const u8) void {
+ fn emitBackground(self: *ChildSink, stamped: sink.Stamped, handle: BackgroundHandle) void {
var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
@@ -197,7 +222,7 @@ pub const ChildSink = struct {
const params = parsed.object.get("params") orelse return;
if (params != .object) return;
const update = params.object.get("update") orelse return;
- if (backgroundSend(self.io, self.id, call_id, self.seq, .{ .type = "update", .update = update }))
+ if (backgroundSend(self.io, handle, self.id, self.seq, .{ .type = "update", .update = update }))
self.seq += 1;
}
};
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 5ea50c05..7f727e56 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -363,18 +363,21 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const detached = ctx.subagent_feedback != null;
const announce_child = acp_children.eligible(kind, ctx.depth, detached);
const announced = announce_child and acp_children.announce(ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id);
- const background_announced = detached and std.mem.eql(u8, kind, "subagent") and ctx.depth == 0 and ctx.parent_tool_call_id.len > 0 and
- acp_children.announceBackground(ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id);
+ const background_handle: ?acp_children.BackgroundHandle = if (detached and std.mem.eql(u8, kind, "subagent") and ctx.depth == 0 and ctx.parent_tool_call_id.len > 0)
+ acp_children.announceBackground(arena, ctx.io, sub_id, label, prompt, ctx.parent_tool_call_id)
+ else
+ null;
+ const background_announced = background_handle != null;
var child_stream: acp_children.ChildSink = .{
.id = sub_id,
.io = ctx.io,
.recorder = agent.sink,
- .background_call_id = if (background_announced) ctx.parent_tool_call_id else null,
+ .background_handle = background_handle,
};
if (announced or background_announced) agent.sink = child_stream.engineSink();
var child_state: []const u8 = "failed";
defer if (announced) acp_children.finish(ctx.io, sub_id, child_state, ctx.parent_tool_call_id);
- defer if (background_announced) acp_children.finishBackground(ctx.io, sub_id, ctx.parent_tool_call_id, child_stream.seq, child_state);
+ defer if (background_handle) |handle| acp_children.finishBackground(ctx.io, handle, sub_id, child_stream.seq, child_state);
const wf_task = std.mem.eql(u8, kind, "workflow_task");
if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });