diff --git a/sdk/tests/package-size-budgets.json b/sdk/tests/package-size-budgets.json index c91bbc2f5b..e8da7514b4 100644 --- a/sdk/tests/package-size-budgets.json +++ b/sdk/tests/package-size-budgets.json @@ -7,7 +7,7 @@ "bytes": 2475000 }, "fx-term.wasm": { - "bytes": 4254000 + "bytes": 4270000 }, "engine.js": { "gzip": 34600 diff --git a/src/core/agent/worker_runtime.zig b/src/core/agent/worker_runtime.zig index 593aae54d3..dbb1585c45 100644 --- a/src/core/agent/worker_runtime.zig +++ b/src/core/agent/worker_runtime.zig @@ -417,6 +417,10 @@ pub const StateSnapshot = struct { } }; +/// The file review a pending request shows. `review` is an identity, not a +/// lifetime: the tool call that built it frees it as soon as the request is +/// answered, and the answer can come from another thread, so only +/// `copyPendingReview`, which copies under the worker's lock, may read it. pub const PendingPermissionReview = struct { request_id: u64, review: *const diff_mod.FileReview, @@ -2785,6 +2789,26 @@ pub const WorkerRuntime = struct { }; } + /// Returns a copy of the file review the pending request `request_id` waits + /// on, which the caller owns and frees with `OwnedReview.deinit`, or null + /// when no request with that id still waits for a decision or it has no + /// review. The copy is made under `worker_mutex`: the tool call that owns + /// the review waits on this worker, so it cannot end and free the review + /// while the lock is held (`tests/tla/subagent/TuiParentApproval.tla` + /// NoStalePrompt). + pub fn copyPendingReview( + self: *WorkerRuntime, + alloc: std.mem.Allocator, + request_id: u64, + ) std.mem.Allocator.Error!?diff_mod.OwnedReview { + self.worker_mutex.lockUncancelable(io_mod.getIo()); + defer self.worker_mutex.unlock(io_mod.getIo()); + if (!self.permissionRequestAwaitingDecisionLocked()) return null; + if (self.pending_permission_request_shared.?.id != request_id) return null; + const review = self.pending_permission_review orelse return null; + return try diff_mod.OwnedReview.init(alloc, review); + } + pub fn activeTurnId(self: *WorkerRuntime) u64 { self.worker_mutex.lockUncancelable(io_mod.getIo()); defer self.worker_mutex.unlock(io_mod.getIo()); @@ -7761,6 +7785,71 @@ test "permission snapshot keeps the full file review borrowed and request-bound" try std.testing.expectEqual(@as(usize, 7), snapshot.pending_permission_review.?.review.rowCount()); } +test "worker copies a pending review under its lock" { + const alloc = std.testing.allocator; + var runtime = WorkerRuntime{}; + defer runtime.deinit(alloc); + var review = try diff_mod.FileReview.init(alloc, "one\ntwo\n", "one\nTWO\n"); + var review_freed = false; + defer if (!review_freed) review.deinit(alloc); + + runtime.worker_processing = true; + runtime.pending_permission_waiting = true; + runtime.pending_permission_request_shared = try permission_request.OwnedPermissionRequest.dupe( + alloc, + .{ + .id = 44, + .label = "file_mutation", + .file = .{ + .kind = .write, + .intent = .mutation, + .preview = .{ + .path = "note.txt", + .lines = &.{ + .{ .op = .deletion, .old_line = 2, .text = "two" }, + .{ .op = .addition, .new_line = 2, .text = "TWO" }, + }, + .additions = 1, + .deletions = 1, + .truncated = false, + }, + .scope = .workspace_files, + }, + }, + ); + runtime.pending_permission_review = &review; + + // A request with another id, waiting or not, has no copy to give. + try std.testing.expect(try runtime.copyPendingReview(alloc, 45) == null); + + var copied = (try runtime.copyPendingReview(alloc, 44)).?; + defer copied.deinit(alloc); + try std.testing.expect(copied.view() != &review); + const rows = review.rowCount(); + try std.testing.expectEqual(rows, copied.view().rowCount()); + const before = try review.viewport(alloc, 0, rows); + defer alloc.free(before.lines); + const first_row = try alloc.dupe(u8, before.lines[0].text); + defer alloc.free(first_row); + + // The copy keeps the rows after the tool call that built the review frees it. + review.deinit(alloc); + review_freed = true; + const after = try copied.view().viewport(alloc, 0, rows); + defer alloc.free(after.lines); + try std.testing.expectEqualStrings(first_row, after.lines[0].text); + + // Once the request is answered, it waits on nothing, so it has no copy. + try std.testing.expectEqual( + PermissionSubmissionResult.accepted, + runtime.submitPermissionResponse( + 44, + permission_request.OwnedPermissionResponse.init(alloc, .once, null), + ), + ); + try std.testing.expect(try runtime.copyPendingReview(alloc, 44) == null); +} + test "held turn propagation refreshes queued prompt trusted reviewer context" { const alloc = std.testing.allocator; var runtime = WorkerRuntime{}; diff --git a/src/core/app/app_agent_runtime.zig b/src/core/app/app_agent_runtime.zig index f97a7f1fb7..40d07d35fb 100644 --- a/src/core/app/app_agent_runtime.zig +++ b/src/core/app/app_agent_runtime.zig @@ -251,9 +251,15 @@ pub fn Runtime(comptime App: type) type { .disabled; // A child's `subagent` calls go to its own host, which the tool // context already holds, as main's go to main's. - // A child's approvals and questions go to its own worker, as - // main's do, for main's runs and the user's alike; main's screen - // borrows them while the child is hidden. + // A run main started asks through its turn, so the request is + // registered and main is told; it still waits on this child's own + // worker, whose screen shows it too. A turn the person typed has no + // turn of main's, so it keeps the worker's prompter and stays with + // the person (`tests/tla/subagent/TuiParentApproval.tla` + // TypedStaysWithPerson). + if (run.turn) |turn| { + if (run.startedByParent()) ctx.permission_prompter = turn.permissionPrompter(); + } ctx.interactive = false; ctx.ask_user_questions = true; ctx.provider = run.admission.provider; diff --git a/src/core/app/app_agents_runtime.zig b/src/core/app/app_agents_runtime.zig index b2521d1a41..daf9b9aee3 100644 --- a/src/core/app/app_agents_runtime.zig +++ b/src/core/app/app_agents_runtime.zig @@ -1203,7 +1203,7 @@ pub fn Runtime(comptime App: type) type { for (app.child_agents.items) |child| { if (!lendsTo(app, child, borrower)) continue; const approval = &child.agent.approval_prompt; - if (approval.isActive() and approval.rule_management == null) { + if (approval.isActive() and approval.rule_management == null and !parentRoutedApproval(child)) { if (oldest == null or child.approval_asked < oldest.?.asked) oldest = .{ .child = child, .kind = .approval, .asked = child.approval_asked }; } if (child.agent.question_prompt.isActive()) { @@ -1267,8 +1267,10 @@ pub fn Runtime(comptime App: type) type { /// Lends `child`'s approval to `borrower`'s prompt. Its request comes /// from the subagent's own worker and stays labeled with its name. /// It goes back when the subagent is shown, the instance gets its - /// own, or the subagent stops waiting (`keepLentApproval`). + /// own, or the subagent stops waiting (`keepLentApproval`). A request + /// main answers is never lent: main's screen does not show it. fn lendApproval(app: *App, borrower: *AppAgent, child: *ChildAgent) void { + if (parentRoutedApproval(child)) return; std.mem.swap(@TypeOf(child.agent.approval_prompt), &borrower.approval_prompt, &child.agent.approval_prompt); app.approval_lender = child; debug_trace.eventf("host", "approval_lent", .{}, "agent={s}", .{child.id}); @@ -1591,7 +1593,9 @@ pub fn Runtime(comptime App: type) type { } for (app.child_agents.items) |child| { if (child == app.agent_on_screen) continue; - const approval = child.agent.approval_prompt.isActive(); + // A request main answers is not a wait for the person: the + // screen shows no prompt for it and the footer stays quiet. + const approval = child.agent.approval_prompt.isActive() and !parentRoutedApproval(child); const asks = child.agent.question_prompt.isActive(); if (!approval and !asks and !requestWaitsForUser(app, child)) continue; if (!found) { @@ -2401,11 +2405,29 @@ pub fn Runtime(comptime App: type) type { return null; } + /// The person answered a subagent's request on its own screen, so the + /// registry binding goes with it. An agent that is not a hosted child + /// does nothing. + pub fn withdrawAnsweredApproval(app: *App, agent: *AppAgent) void { + const child = hostedOf(app, agent) orelse return; + const host = hostOf(app, child) orelse return; + _ = host.withdrawAnsweredApproval(child.id); + } + fn hostedOf(app: *App, agent: *const AppAgent) ?*ChildAgent { for (app.child_agents.items) |child| if (&child.agent == agent) return child; return null; } + /// Whether `child`'s waiting approval came from a run main started. Main + /// answers those, so no instance's screen lends one and the footer and + /// the agent list never say the child needs the person + /// (`tests/tla/subagent/TuiParentApproval.tla` NoPersonPromptForParentRouted). + fn parentRoutedApproval(child: *const ChildAgent) bool { + const run = if (child.agent.child_run) |*value| value else return false; + return run.turn != null and run.startedByParent(); + } + /// A subagent's approval or question is lent to an instance's screen /// only when that instance's tree holds it: an instance's are its /// own, and a subagent of another instance belongs to that one. @@ -2606,6 +2628,9 @@ pub fn Runtime(comptime App: type) type { if (target) |child| { if (app.approval_lender == child) return .needs_approval; if (app.question_lender == child) return .has_question; + // A request main answers is main's work, not a wait for the + // person, so the list says working, not "needs approval". + if (parentRoutedApproval(child) and child.agent.approval_prompt.isActive()) return .working; } const last_end: LastEnd = if (target) |child| (if (child.agent.role == .subagent) child.last_end else .done) else .done; const state = instanceState(targetAgent(app, target), requestWaitsForUser(app, target), last_end); diff --git a/src/core/app/app_render_runtime.zig b/src/core/app/app_render_runtime.zig index 3f43d789e8..5b2339f999 100644 --- a/src/core/app/app_render_runtime.zig +++ b/src/core/app/app_render_runtime.zig @@ -6104,7 +6104,7 @@ test "core.app_render_runtime file approval returns to the preserved inline skil try std.testing.expect(!app.terminal.catalogMenuScreenActive()); try std.testing.expect(try app.agent().approval_prompt.syncRequest(alloc, request)); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.modal); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); @@ -6197,7 +6197,7 @@ test "core.app_render_runtime file approvals commit the alternate screen for eac alloc, request_a, )); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.first_frame); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); @@ -6233,7 +6233,7 @@ test "core.app_render_runtime file approvals commit the alternate screen for eac alloc, request_b, )); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.modal); try std.testing.expect(!approval_screen.fileApprovalAffirmativeReady( &app.shell, @@ -6325,7 +6325,7 @@ test "core.app_render_runtime restores file review before rendering a generic ap try app.shell.initBacking(alloc); try app.shell.enableShadowVt(alloc); try std.testing.expect(try app.agent().approval_prompt.syncRequest(alloc, file_request)); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.first_frame); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); @@ -6543,7 +6543,7 @@ test "core.app_render_runtime file approval takes over the full transcript alter try app.shell.writeTranscript(alloc, &app.metrics, "prior transcript\n", true); try app_lifecycle.openFullTranscript(app.alloc, &app.terminal, &app.shell, &app.metrics); try std.testing.expect(try app.agent().approval_prompt.syncRequest(alloc, request)); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.modal); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); @@ -6667,7 +6667,7 @@ test "core.app_render_runtime lifecycle rewrite recovers normal buffer after fil var review = try diff_mod.FileReview.init(alloc, "", "pending\n"); defer review.deinit(alloc); try std.testing.expect(try app.agent().approval_prompt.syncRequest(alloc, request)); - try std.testing.expect(app.agent().approval_prompt.syncReview(&review)); + try std.testing.expect(app.agent().approval_prompt.adoptReview(alloc, app.agent().approval_prompt.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); app.shell.render_requests.request(.modal); try Runtime(CoordinatorTestApp).flushRequestedFrame(&app, (&app).agent()); try std.testing.expect(app.terminal.fileApprovalScreenActive()); diff --git a/src/core/app/app_worker_runtime.zig b/src/core/app/app_worker_runtime.zig index 3351122c61..8c181b39b7 100644 --- a/src/core/app/app_worker_runtime.zig +++ b/src/core/app/app_worker_runtime.zig @@ -827,6 +827,30 @@ pub fn Runtime(comptime App: type) type { try pushOwnedEvent(app, agent, .{ .diff_block = payload }); } + /// Mirrors the pending request's file review into the approval prompt. + /// The prompt gets its own copy, taken under the worker's lock + /// (`WorkerRuntime.copyPendingReview`): the tool call that built the + /// review frees it as soon as its request is answered, and the answer + /// can come from another thread, so the snapshot's pointer only tells + /// one review from another and is never read. Returns whether the + /// prompt's review changed. + fn syncApprovalReview( + app: *App, + agent: *AppAgent, + waiting: ?worker_runtime.PendingPermissionReview, + ) bool { + const prompt = &agent.approval_prompt; + if (waiting) |pending| { + if (prompt.reviewCopyMatches(pending.request_id, pending.review)) return false; + const review = agent.worker.copyPendingReview(app.alloc, pending.request_id) catch |err| { + debug_trace.logf("approval", "review copy dropped request={d} reason={s}", .{ pending.request_id, @errorName(err) }); + return false; + }; + return prompt.adoptReview(app.alloc, pending.request_id, pending.review, review); + } + return prompt.adoptReview(app.alloc, null, null, null); + } + pub fn syncState( app: *App, agent: *AppAgent, @@ -866,19 +890,21 @@ pub fn Runtime(comptime App: type) type { false else agent.approval_prompt.syncRequest(app.alloc, pending_request) catch false; - const review_changed = if (comptime @hasDecl(@TypeOf(agent.approval_prompt), "syncReview")) blk: { + const review_changed = if (comptime @hasDecl(@TypeOf(agent.approval_prompt), "adoptReview") and + @hasDecl(@TypeOf(agent.worker), "copyPendingReview")) + blk: { if (keep_lent) break :blk false; - const review = if (comptime @hasField(@TypeOf(snapshot), "pending_permission_review")) + const waiting: ?worker_runtime.PendingPermissionReview = if (comptime @hasField(@TypeOf(snapshot), "pending_permission_review")) if (snapshot.pending_permission_review) |pending| if (pending_request) |request| - if (pending.request_id == request.id) pending.review else null + if (pending.request_id == request.id) pending else null else null else null else null; - break :blk agent.approval_prompt.syncReview(review); + break :blk syncApprovalReview(app, agent, waiting); } else false; if (approval_changed and in_child and agent.approval_prompt.isActive()) { debug_trace.eventf("host", "approval_requested", .{}, "agent={s}", .{subagentIdOf(app, agent).?}); @@ -2008,6 +2034,15 @@ const FakeWorker = struct { }; } + /// A copy of the review the pending request waits on, as + /// `WorkerRuntime.copyPendingReview` gives the app one. + pub fn copyPendingReview(self: *FakeWorker, alloc: std.mem.Allocator, request_id: u64) std.mem.Allocator.Error!?diff_mod.OwnedReview { + const request = self.pending_permission_request orelse return null; + if (request.id != request_id) return null; + const review = self.pending_permission_review orelse return null; + return try diff_mod.OwnedReview.init(alloc, review); + } + pub fn interactiveAdmissionSnapshot(self: *FakeWorker) worker_runtime.InteractiveAdmissionSnapshot { return self.admission_snapshot; } @@ -2060,12 +2095,23 @@ const FakeApprovalPrompt = struct { sync_count: usize = 0, force_active: bool = false, request: ?permission_request.OwnedPermissionRequest = null, - review: ?*const diff_mod.FileReview = null, + review: ?diff_mod.OwnedReview = null, + /// The review the owned copy was taken from, only to tell one review from + /// another, as `ApprovalPrompt` does. + review_source: ?*const diff_mod.FileReview = null, review_request_id: u64 = 0, fn deinit(self: *FakeApprovalPrompt, alloc: std.mem.Allocator) void { if (self.request) |*request| request.deinit(alloc); self.request = null; + self.clearReview(alloc); + } + + fn clearReview(self: *FakeApprovalPrompt, alloc: std.mem.Allocator) void { + if (self.review) |*owned| owned.deinit(alloc); + self.review = null; + self.review_source = null; + self.review_request_id = 0; } fn syncRequest( @@ -2083,21 +2129,38 @@ const FakeApprovalPrompt = struct { const changed = self.request != null; if (self.request) |*current| current.deinit(alloc); self.request = null; - self.review = null; - self.review_request_id = 0; + self.clearReview(alloc); return changed; } - pub fn syncReview(self: *FakeApprovalPrompt, review: ?*const diff_mod.FileReview) bool { - const request = self.request orelse { + fn reviewCopyMatches(self: *const FakeApprovalPrompt, request_id: u64, source: ?*const diff_mod.FileReview) bool { + return self.review_request_id == request_id and self.review_source == source; + } + + /// Takes `review` as this fake's copy, freeing it when it cannot keep it, + /// as `ApprovalPrompt.adoptReview` does. + pub fn adoptReview( + self: *FakeApprovalPrompt, + alloc: std.mem.Allocator, + request_id: ?u64, + source: ?*const diff_mod.FileReview, + review: ?diff_mod.OwnedReview, + ) bool { + var incoming = review; + const keeps = if (request_id) |id| + if (self.request) |request| request.id == id else false + else + false; + if (!keeps) { + if (incoming) |*owned| owned.deinit(alloc); const changed = self.review != null; - self.review = null; - self.review_request_id = 0; + self.clearReview(alloc); return changed; - }; - if (self.review == review and self.review_request_id == request.id) return false; - self.review = review; - self.review_request_id = if (review == null) 0 else request.id; + } + self.clearReview(alloc); + self.review = incoming; + self.review_source = source; + self.review_request_id = if (incoming == null) 0 else request_id.?; return true; } @@ -3823,7 +3886,8 @@ test "core.app_worker_runtime syncState mirrors approvals without opening a pend @as(?u32, 2), app.agent().approval_prompt.request.?.file.?.preview.lines[0].old_line, ); - try std.testing.expect(app.agent().approval_prompt.review == &review); + try std.testing.expect(app.agent().approval_prompt.review != null); + try std.testing.expect(app.agent().approval_prompt.review_source == &review); try std.testing.expectEqual( app.agent().approval_prompt.request.?.id, app.agent().approval_prompt.review_request_id, @@ -3843,7 +3907,15 @@ test "core.app_worker_runtime syncState mirrors approvals without opening a pend app.agent().worker.pending_permission_review = &replacement_review; Runtime(FakeApp).syncState(&app, (&app).agent(), NoopBridge.lifecyclePresenter(&app)); - try std.testing.expect(app.agent().approval_prompt.review == &replacement_review); + try std.testing.expect(app.agent().approval_prompt.review_source == &replacement_review); + const kept = &(app.agent().approval_prompt.review orelse return error.MissingReview); + const viewport = try kept.view().viewport(std.testing.allocator, 0, kept.view().rowCount()); + defer std.testing.allocator.free(viewport.lines); + var shows_replacement = false; + for (viewport.lines) |line| { + shows_replacement = shows_replacement or std.mem.eql(u8, line.text, "after again"); + } + try std.testing.expect(shows_replacement); try std.testing.expectEqual(@as(usize, 0), app.approval_screen.document_scroll_rows); try std.testing.expect(app.approval_screen.screen_commit == null); diff --git a/src/core/app/input_approval_runtime.zig b/src/core/app/input_approval_runtime.zig index 6f4c7e96c8..a151af16d4 100644 --- a/src/core/app/input_approval_runtime.zig +++ b/src/core/app/input_approval_runtime.zig @@ -267,6 +267,12 @@ pub fn ApprovalRuntime(comptime App: type) type { if (asker) |id| debug_trace.eventf("host", "approval_answered", .{}, "agent={s} screen={s}", .{ id, app.screenAgentId() }); } clearApprovalPromptAfterSubmission(app, agent); + // A subagent's request answered on its own screen leaves no + // binding behind, so main's later answer says it no longer + // waits instead of answering it a second time. + if (comptime @hasDecl(App, "withdrawAnsweredApproval")) { + app.withdrawAnsweredApproval(agent); + } app.input_runtime.input_limit_rejection = input_limit_rejection.clear(); requestActiveSurfaceFrame(app); }, @@ -458,7 +464,7 @@ test "approval wheel keeps scrolling a committed command review after review syn .document_scrollable = true, }); - try std.testing.expect(!app.agent().approval_prompt.syncReview(null)); + try std.testing.expect(!app.agent().approval_prompt.adoptReview(alloc, null, null, null)); try ApprovalRuntime(WheelApp).handleApprovalWheel(&app, (&app).agent(), .up); try std.testing.expectEqual(@as(usize, 3), app.approval_screen.document_scroll_rows); try std.testing.expect(app.shell.render_requests.hasReason(.modal)); diff --git a/src/core/output/diff.zig b/src/core/output/diff.zig index 6bd474859a..886ab1b399 100644 --- a/src/core/output/diff.zig +++ b/src/core/output/diff.zig @@ -392,6 +392,175 @@ pub const FileReview = struct { } }; +/// A review that owns the text it reads, so a screen can keep it after the tool +/// call that built it has ended (`approval_prompt.zig` keeps one). `review`'s +/// own arrays are freed by its `deinit`; `owned` holds the text those arrays +/// point into. +pub const OwnedReview = struct { + review: FileReview, + owned: union(enum) { + /// Every row's text, in row order, which each row points into. + computed: []u8, + /// The two file texts the fallback mode reads its rows from. + fallback: struct { old: []u8, new: []u8 }, + }, + + pub fn init(alloc: Allocator, source: *const FileReview) Allocator.Error!OwnedReview { + switch (source.mode) { + .computed => |lines| { + var text_bytes: usize = 0; + for (lines) |line| text_bytes += line.text.len; + const text = try alloc.alloc(u8, text_bytes); + errdefer alloc.free(text); + const copy = try alloc.alloc(DiffLine, lines.len); + errdefer alloc.free(copy); + var at: usize = 0; + for (lines, 0..) |line, index| { + const owned = text[at..][0..line.text.len]; + @memcpy(owned, line.text); + at += line.text.len; + copy[index] = line; + copy[index].text = owned; + } + return .{ + .review = .{ + .mode = .{ .computed = copy }, + .additions = source.additions, + .deletions = source.deletions, + }, + .owned = .{ .computed = text }, + }; + }, + .fallback => |fallback| { + const old_text = try alloc.dupe(u8, fallback.old_text); + errdefer alloc.free(old_text); + const new_text = try alloc.dupe(u8, fallback.new_text); + errdefer alloc.free(new_text); + const old_starts = try alloc.alloc(usize, fallback.old_line_starts.len); + errdefer alloc.free(old_starts); + @memcpy(old_starts, fallback.old_line_starts); + const new_starts = try alloc.alloc(usize, fallback.new_line_starts.len); + errdefer alloc.free(new_starts); + @memcpy(new_starts, fallback.new_line_starts); + var copied = fallback; + copied.old_text = old_text; + copied.new_text = new_text; + copied.old_line_starts = old_starts; + copied.new_line_starts = new_starts; + return .{ + .review = .{ + .mode = .{ .fallback = copied }, + .additions = source.additions, + .deletions = source.deletions, + }, + .owned = .{ .fallback = .{ .old = old_text, .new = new_text } }, + }; + }, + } + } + + pub fn deinit(self: *OwnedReview, alloc: Allocator) void { + self.review.deinit(alloc); + switch (self.owned) { + .computed => |text| alloc.free(text), + .fallback => |text| { + alloc.free(text.old); + alloc.free(text.new); + }, + } + self.* = undefined; + } + + pub fn view(self: *const OwnedReview) *const FileReview { + return &self.review; + } +}; + +fn captureRowTexts(alloc: Allocator, review: *const FileReview, limit: usize) ![][]u8 { + const viewport = try review.viewport(alloc, 0, limit); + defer alloc.free(viewport.lines); + const texts = try alloc.alloc([]u8, viewport.lines.len); + var filled: usize = 0; + errdefer { + for (texts[0..filled]) |text| alloc.free(text); + alloc.free(texts); + } + for (viewport.lines, 0..) |line, index| { + texts[index] = try alloc.dupe(u8, line.text); + filled = index + 1; + } + return texts; +} + +fn freeRowTexts(alloc: Allocator, texts: [][]u8) void { + for (texts) |text| alloc.free(text); + alloc.free(texts); +} + +fn expectSameRowTexts(alloc: Allocator, review: *const FileReview, expected: [][]u8) !void { + const actual = try captureRowTexts(alloc, review, expected.len); + defer freeRowTexts(alloc, actual); + try std.testing.expectEqual(expected.len, actual.len); + for (expected, actual) |want, got| try std.testing.expectEqualStrings(want, got); +} + +test "an owned review keeps its rows after the review it copied is freed" { + const alloc = std.testing.allocator; + var source = try FileReview.init(alloc, "one\ntwo\n", "one\nTWO\n"); + var owned = try OwnedReview.init(alloc, &source); + defer owned.deinit(alloc); + + const rows = source.rowCount(); + try std.testing.expectEqual(rows, owned.view().rowCount()); + const expected = try captureRowTexts(alloc, &source, rows); + defer freeRowTexts(alloc, expected); + + source.deinit(alloc); + try expectSameRowTexts(alloc, owned.view(), expected); +} + +test "an owned review keeps a fallback review's rows after the source is freed" { + const alloc = std.testing.allocator; + const line_count = canonical_max_indexed_lines + 1; + const text = try alloc.alloc(u8, line_count * 2); + defer alloc.free(text); + for (0..line_count) |index| text[index * 2 ..][0..2].* = "x\n".*; + + var source = try FileReview.init(alloc, "", text); + try std.testing.expectEqual(std.meta.Tag(@TypeOf(source.mode)).fallback, std.meta.activeTag(source.mode)); + var owned = try OwnedReview.init(alloc, &source); + defer owned.deinit(alloc); + + try std.testing.expectEqual(source.rowCount(), owned.view().rowCount()); + const expected = try captureRowTexts(alloc, &source, max_preview_lines); + defer freeRowTexts(alloc, expected); + + source.deinit(alloc); + try expectSameRowTexts(alloc, owned.view(), expected); +} + +test "an owned review copies a review at the fallback limit with the same rows" { + const alloc = std.testing.allocator; + const Case = struct { lines: usize, mode: std.meta.Tag(@TypeOf(@as(FileReview, undefined).mode)) }; + const cases = [_]Case{ + .{ .lines = canonical_max_indexed_lines, .mode = .computed }, + .{ .lines = canonical_max_indexed_lines + 1, .mode = .fallback }, + }; + for (cases) |case| { + const text = try alloc.alloc(u8, case.lines * 2); + defer alloc.free(text); + for (0..case.lines) |index| text[index * 2 ..][0..2].* = "y\n".*; + var source = try FileReview.init(alloc, "", text); + defer source.deinit(alloc); + try std.testing.expectEqual(case.mode, std.meta.activeTag(source.mode)); + var owned = try OwnedReview.init(alloc, &source); + defer owned.deinit(alloc); + try std.testing.expectEqual(case.mode, std.meta.activeTag(owned.view().mode)); + try std.testing.expectEqual(source.rowCount(), owned.view().rowCount()); + try std.testing.expectEqual(source.additions, owned.view().additions); + } +} + pub const FileReviewError = error{ OutOfMemory, ArithmeticOverflow, diff --git a/src/core/permissions/approval_prompt.zig b/src/core/permissions/approval_prompt.zig index 30a6c637d5..c867cb7569 100644 --- a/src/core/permissions/approval_prompt.zig +++ b/src/core/permissions/approval_prompt.zig @@ -50,7 +50,10 @@ pub const Projection = struct { pub const ApprovalPrompt = struct { request: ?permission_request.OwnedPermissionRequest = null, decision: approval_decision.State = .{}, - review: ?*const diff_mod.FileReview = null, + review: ?diff_mod.OwnedReview = null, + /// The review the owned copy was taken from, only to tell one review from + /// another without copying it again on every pass. + review_source: ?*const diff_mod.FileReview = null, review_request_id: u64 = 0, rule_management: ?session_permission_state.OwnedConfirmedRuleEvent = null, @@ -88,7 +91,7 @@ pub const ApprovalPrompt = struct { self.rule_management = null; self.request = null; self.decision.reset(alloc, reason); - self.clearReview(); + self.clearReview(alloc); } pub fn syncRequest( @@ -145,28 +148,56 @@ pub const ApprovalPrompt = struct { self.decision.setConfirmationOnly(true); } - pub fn syncReview(self: *ApprovalPrompt, review: ?*const diff_mod.FileReview) bool { - const request = self.request orelse { - const changed = self.review != null or self.review_request_id != 0; - self.clearReview(); - return changed; - }; - if (request.file == null) { + /// Whether the prompt already holds a copy of `source` as the review for + /// `request_id`, so the caller needs no new copy for it. + pub fn reviewCopyMatches( + self: *const ApprovalPrompt, + request_id: u64, + source: ?*const diff_mod.FileReview, + ) bool { + return self.review_request_id == request_id and self.review_source == source; + } + + /// Takes `review` as the prompt's own copy of the file review for + /// `request_id`, which it frees when it clears; `source` only tells one + /// review from another. The caller hands the copy over even when the + /// prompt cannot keep it, which happens once the request is gone or names + /// no file. Pass no request id and no review to clear what it holds. + /// Returns whether the prompt's review changed. The copy comes from the + /// worker, made under its lock (`WorkerRuntime.copyPendingReview`), + /// because the tool call that built the review frees it as soon as its + /// request is answered (`tests/tla/subagent/TuiParentApproval.tla` + /// NoStalePrompt). + pub fn adoptReview( + self: *ApprovalPrompt, + alloc: Allocator, + request_id: ?u64, + source: ?*const diff_mod.FileReview, + review: ?diff_mod.OwnedReview, + ) bool { + var incoming = review; + const keeps = if (request_id) |id| + if (self.request) |request| request.file != null and request.id == id else false + else + false; + if (!keeps) { + if (incoming) |*owned| owned.deinit(alloc); const changed = self.review != null or self.review_request_id != 0; - self.clearReview(); + self.clearReview(alloc); return changed; } - - if (self.review == review and self.review_request_id == request.id) return false; - self.review = review; - self.review_request_id = if (review == null) 0 else request.id; + self.clearReview(alloc); + self.review = incoming; + self.review_source = source; + self.review_request_id = if (incoming == null) 0 else request_id.?; return true; } - pub fn currentReview(self: ApprovalPrompt) ?*const diff_mod.FileReview { + pub fn currentReview(self: *const ApprovalPrompt) ?*const diff_mod.FileReview { const request = self.request orelse return null; if (request.file == null or self.review_request_id != request.id) return null; - return self.review; + if (self.review) |*owned| return owned.view(); + return null; } pub fn isAmending(self: ApprovalPrompt) bool { @@ -196,11 +227,13 @@ pub const ApprovalPrompt = struct { self.rule_management = null; self.request = null; self.decision.resetAfterSubmission(alloc); - self.clearReview(); + self.clearReview(alloc); } - fn clearReview(self: *ApprovalPrompt) void { + fn clearReview(self: *ApprovalPrompt, alloc: Allocator) void { + if (self.review) |*owned| owned.deinit(alloc); self.review = null; + self.review_source = null; self.review_request_id = 0; } }; @@ -290,7 +323,6 @@ test "approval prompt treats byte-identical replacement ids as new requests" { test "approval prompt keeps full review request-bound" { const alloc = std.testing.allocator; var review = try diff_mod.FileReview.init(alloc, "", "one\ntwo\n"); - defer review.deinit(alloc); var prompt = ApprovalPrompt{}; defer prompt.deinit(alloc); @@ -301,8 +333,22 @@ test "approval prompt keeps full review request-bound" { .file = approvalFileRequest(approvalPreview()), }; try std.testing.expect(try prompt.syncRequest(alloc, request_a)); - try std.testing.expect(prompt.syncReview(&review)); - try std.testing.expect(prompt.currentReview() == &review); + try std.testing.expect(prompt.adoptReview(alloc, request_a.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); + // The prompt keeps its own copy, so the review can go with the tool call + // that built it and the prompt still reads the same rows. + try std.testing.expect(prompt.currentReview() != &review); + const kept = prompt.currentReview().?; + const rows = kept.rowCount(); + const before = try kept.viewport(alloc, 0, rows); + defer alloc.free(before.lines); + const first_row = try alloc.dupe(u8, before.lines[0].text); + defer alloc.free(first_row); + review.deinit(alloc); + + try std.testing.expectEqual(rows, prompt.currentReview().?.rowCount()); + const after = try prompt.currentReview().?.viewport(alloc, 0, rows); + defer alloc.free(after.lines); + try std.testing.expectEqualStrings(first_row, after.lines[0].text); var request_b = request_a; request_b.id = 11; @@ -313,7 +359,6 @@ test "approval prompt keeps full review request-bound" { test "approval projection borrows immutable active state" { const alloc = std.testing.allocator; var review = try diff_mod.FileReview.init(alloc, "", "one\ntwo\n"); - defer review.deinit(alloc); var prompt = ApprovalPrompt{}; defer prompt.deinit(alloc); @@ -323,7 +368,11 @@ test "approval projection borrows immutable active state" { .label = "edit_file note.txt", .file = approvalFileRequest(approvalPreview()), })); - try std.testing.expect(prompt.syncReview(&review)); + try std.testing.expect(prompt.adoptReview(alloc, 41, &review, try diff_mod.OwnedReview.init(alloc, &review))); + const kept_rows = prompt.currentReview().?.rowCount(); + // The projection reads the prompt's own copy, so it outlives the review the + // tool call built. + review.deinit(alloc); _ = try prompt.decision.apply(alloc, .tab, true, null); _ = try prompt.decision.apply(alloc, .{ .insert_ascii = 'y' }, true, null); _ = try prompt.decision.apply(alloc, .{ .move_choice = .previous }, true, null); @@ -341,7 +390,7 @@ test "approval projection borrows immutable active state" { try std.testing.expectEqualStrings("n", projection.draftForChoice(2)); try std.testing.expectEqual(@as(usize, 1), projection.draftCursorForChoice(0)); try std.testing.expectEqual(@as(usize, 1), projection.draftCursorForChoice(2)); - try std.testing.expect(projection.currentReview() == &review); + try std.testing.expectEqual(kept_rows, projection.currentReview().?.rowCount()); } test "command approval ignores absent file review" { @@ -353,7 +402,7 @@ test "command approval ignores absent file review" { .label = "shell.run printf '%s' command-review", })); - try std.testing.expect(!prompt.syncReview(null)); + try std.testing.expect(!prompt.adoptReview(alloc, null, null, null)); try std.testing.expect(prompt.review == null); try std.testing.expectEqual(@as(u64, 0), prompt.review_request_id); } diff --git a/src/core/subagent/approval_registry.zig b/src/core/subagent/approval_registry.zig index 87260d144e..00336a8a2a 100644 --- a/src/core/subagent/approval_registry.zig +++ b/src/core/subagent/approval_registry.zig @@ -449,6 +449,66 @@ pub const Registry = struct { return counts; } + /// Refuses every pending request of `child_id` with `feedback`: what a stop + /// or a close of that subagent does before it ends the turn, so the + /// subagent's call is refused with the reason and nothing runs + /// (`tests/tla/subagent/ParentApproval.tla` Stop, which drops the request). + /// Takes only the registry's mutex, and releases it before answering a + /// worker (`resolveIndexLocked`), so a caller that holds no other lock + /// cannot deadlock with the note path (worker mutex, then registry) or with + /// a stopper (admission, then owner, then worker). Logs the ids and counts, + /// never the content (RULES.md R3.8). + pub fn refuseChild(self: *Registry, child_id: []const u8, feedback: []const u8) RefusedCounts { + var counts: RefusedCounts = .{}; + var ids: [192]u8 = undefined; + var ids_len: usize = 0; + while (true) { + self.mutex.lockUncancelable(io_mod.getIo()); + if (self.closed) { + self.mutex.unlock(io_mod.getIo()); + break; + } + const index = self.firstIndexForChildLocked(child_id) orelse { + self.mutex.unlock(io_mod.getIo()); + break; + }; + const id = self.bindings.items[index].request_id; + if (ids_len + 1 + id.len <= ids.len) { + if (ids_len > 0) { + ids[ids_len] = ','; + ids_len += 1; + } + @memcpy(ids[ids_len..][0..id.len], id); + ids_len += id.len; + } + const owned_feedback = self.alloc.dupe(u8, feedback) catch |err| { + self.mutex.unlock(io_mod.getIo()); + debug_trace.logf("subagent", "approval refusals stopped child={s} refused={d} gone={d} err={s}", .{ child_id, counts.accepted, counts.gone, @errorName(err) }); + break; + }; + var feedback_owned = true; + const outcome = self.resolveIndexLocked(index, .deny, owned_feedback, &feedback_owned) catch |err| { + debug_trace.logf("subagent", "approval refusals stopped child={s} refused={d} gone={d} err={s}", .{ child_id, counts.accepted, counts.gone, @errorName(err) }); + break; + }; + switch (outcome) { + .accepted => counts.accepted += 1, + .rejected => counts.gone += 1, + } + } + if (counts.accepted > 0 or counts.gone > 0) { + debug_trace.logf("subagent", "approval requests refused child={s} refused={d} gone={d} ids={s}", .{ child_id, counts.accepted, counts.gone, ids[0..ids_len] }); + } + return counts; + } + + fn firstIndexForChildLocked(self: *Registry, child_id: []const u8) ?usize { + for (self.bindings.items, 0..) |binding, index| { + if (std.mem.eql(u8, binding.child_id, child_id)) return index; + } + return null; + } + fn firstNotedIndexLocked(self: *Registry, root_id: []const u8) ?usize { for (self.bindings.items, 0..) |binding, index| { if (!binding.noted) continue; @@ -458,6 +518,32 @@ pub const Registry = struct { return null; } + /// Drops every binding of `child_id` without answering its worker: the + /// person already answered it on the child's own screen, so the worker has + /// its decision and the binding must not outlive it. Main's later answer + /// then finds nothing and says the request is no longer waiting. Takes the + /// registry's mutex and no other lock, so a listener's worker never waits + /// behind it. + pub fn withdrawChild(self: *Registry, child_id: []const u8) usize { + self.mutex.lockUncancelable(io_mod.getIo()); + var removed: usize = 0; + var index = self.bindings.items.len; + while (index > 0) { + index -= 1; + if (!std.mem.eql(u8, self.bindings.items[index].child_id, child_id)) continue; + var binding = self.bindings.items[index]; + _ = self.bindings.orderedRemove(index); + binding.deinit(self.alloc); + removed += 1; + } + if (removed > 0) { + self.pending_revision +|= 1; + debug_trace.logf("subagent", "approval requests withdrawn child={s} count={d} reason=answered_on_screen", .{ child_id, removed }); + } + self.mutex.unlock(io_mod.getIo()); + return removed; + } + pub fn invalidateChild( self: *Registry, child_id: []const u8, diff --git a/src/core/subagent/execution.zig b/src/core/subagent/execution.zig index 58a3c5f887..d4ff4816c6 100644 --- a/src/core/subagent/execution.zig +++ b/src/core/subagent/execution.zig @@ -1182,3 +1182,126 @@ test "a request is not counted as noted while its note is being posted" { try std.testing.expect(marked_seen); try std.testing.expectEqual(types.ToolPermissionDecision.once, answered.decision); } + +test "a refused stop answer ends a child's permission wait with the reason" { + const alloc = std.testing.allocator; + const Host = struct { + fn resolve(_: ?*anyopaque, a: Allocator, _: []const u8) authority_mod.HostResolveError!authority_mod.HostAuthority { + return authority_mod.HostAuthority.capture(a, &.{ "read_file", "shell" }, &.{}, .{}, &.{}) catch + return error.OutOfMemory; + } + }; + var parent: child_state.TestParent = undefined; + try parent.init(alloc); + defer parent.deinit(); + var child_registry = try child_state.Registry.init(alloc, parent.parent.id()); + defer child_registry.deinit(alloc); + var work = child_state.ActiveWork{ + .id = try alloc.dupe(u8, "work-1"), + .message = try alloc.dupe(u8, "task"), + .permission_mode = .ask, + .created_at_ms = 1, + }; + defer work.deinit(alloc); + try child_registry.appendPersistent(alloc, "child-1", "worker", "", work); + try parent.stateStore().save(alloc, child_registry); + var resolver = authority_mod.Resolver{ + .children = &parent.children, + .root_id = parent.parent.id(), + .host = .{ .resolve_fn = Host.resolve }, + }; + var approvals = approval_registry_mod.Registry{ .alloc = alloc }; + defer approvals.deinit(); + const Route = struct { + fn submit( + raw: *anyopaque, + request_id: u64, + response: permission_request.OwnedPermissionResponse, + commit: ?worker_runtime.WorkerRuntime.PermissionCommit, + ) worker_runtime.WorkerRuntime.PermissionCommitError!worker_runtime.PermissionSubmissionResult { + const worker: *worker_runtime.WorkerRuntime = @ptrCast(@alignCast(raw)); + return worker.submitPermissionResponseAfterCommit(request_id, response, commit); + } + + fn cancel(_: *anyopaque) void {} + + fn pin(_: *anyopaque) bool { + return true; + } + + fn release(_: *anyopaque) void {} + }; + const Phase = struct { + fn apply(_: *anyopaque, _: []const u8, _: []const u8, _: child_state.Phase) anyerror!void {} + }; + // The note signals that the request is registered, so the refusal below + // meets it without polling. + const Note = struct { + registered: *std.Io.Event, + + fn post(raw: *anyopaque, _: []const u8, _: []const u8, _: []const u8) bool { + const self: *@This() = @ptrCast(@alignCast(raw)); + self.registered.set(io_mod.getIo()); + return true; + } + }; + var context: u8 = 0; + var registered: std.Io.Event = .unset; + var note = Note{ .registered = ®istered }; + var turn = TurnContext{ + .alloc = alloc, + .runtime = undefined, + .managed_executions = undefined, + .child = null, + .child_id = "child-1", + .active_work_id = "work-1", + .approval_registry = &approvals, + .live_authority = &resolver, + .phase_context = &context, + .phase_fn = Phase.apply, + .approval_note_context = ¬e, + .approval_note_fn = Note.post, + }; + turn.approval_worker_route = .{ + .context = &turn.worker, + .submit_fn = Route.submit, + .cancel_fn = Route.cancel, + .pin_fn = Route.pin, + .release_fn = Route.release, + }; + _ = turn.worker.beginDirectProcessing(1); + defer turn.worker.finishProcessing(); + + const Runner = struct { + fn run(prompter: permission_prompter.Prompter, out: *?permission_request.OwnedPermissionResponse, done: *std.Io.Event) void { + out.* = prompter.request( + std.testing.allocator, + .{ .label = "Allow?" }, + .{ .id = "call-1", .name = "shell", .arguments_json = "{}" }, + null, + null, + ) catch null; + done.set(io_mod.getIo()); + } + }; + var response: ?permission_request.OwnedPermissionResponse = null; + var done: std.Io.Event = .unset; + const thread = try std.Thread.spawn(.{}, Runner.run, .{ turn.permissionPrompter(), &response, &done }); + registered.waitTimeout(io_mod.getIo(), .{ .duration = .{ .clock = .awake, .raw = .fromSeconds(5) } }) catch { + thread.join(); + return error.Timeout; + }; + + const refused = approvals.refuseChild("child-1", "Your parent stopped you before answering this request. Do not retry it."); + try std.testing.expectEqual(@as(usize, 1), refused.accepted); + done.waitTimeout(io_mod.getIo(), .{ .duration = .{ .clock = .awake, .raw = .fromSeconds(5) } }) catch { + thread.join(); + return error.Timeout; + }; + thread.join(); + + var answered = response orelse return error.TestUnexpectedResult; + defer answered.deinit(); + try std.testing.expectEqual(types.ToolPermissionDecision.deny, answered.decision); + try std.testing.expect(std.mem.find(u8, answered.feedback.?, "Your parent stopped you before answering this request") != null); +} diff --git a/src/core/subagent/managed_owner.zig b/src/core/subagent/managed_owner.zig index 347db75899..7bd1039cf4 100644 --- a/src/core/subagent/managed_owner.zig +++ b/src/core/subagent/managed_owner.zig @@ -1506,9 +1506,11 @@ fn runOne(slot: *Slot) OneOutcome { turn.phase_fn = Owner.phaseTransition; turn.begin_context = slot; turn.begin_fn = hostedTurnBegins; - // Only a run fx ask or ACP opens gets the note. A hosted child (the app's) - // keeps its approval on its own screen until Part 2 routes it. - if (!hosted) { + // A run main started is noted, whether this host runs the turn in a session + // of its own (fx ask, ACP) or on the child's agent (the app). A turn the + // person typed on the child's screen is not: its approval stays with the + // person (`tests/tla/subagent/TuiParentApproval.tla` TypedStaysWithPerson). + if (snapshot.active.started_by == .parent) { if (owner.approval_note) |hook| { turn.approval_note_context = hook.context; turn.approval_note_fn = hook.note_fn; diff --git a/src/core/subagent/tool_host.zig b/src/core/subagent/tool_host.zig index f2ab385d3a..1cda3a4c1d 100644 --- a/src/core/subagent/tool_host.zig +++ b/src/core/subagent/tool_host.zig @@ -400,6 +400,15 @@ pub const ApprovalCheck = struct { /// What a child reads when main's own check could not be made (R4.2). const unchecked_approval_feedback = "fx could not check this request against your parent's permissions, so it was refused."; +/// What a subagent reads when its parent stopped it before answering. +const stopped_approval_feedback = "Your parent stopped you before answering this request. Do not retry it."; + +/// What a subagent reads when its parent closed it before answering. +const parent_closed_approval_feedback = "Your parent closed you before answering this request. Do not retry it."; + +/// What a subagent reads when the person closed it before its request was answered. +const user_closed_approval_feedback = "The person closed you before this request was answered. Do not retry it."; + /// What a child reads when fx ask refuses a request main left unanswered. const unanswered_approval_feedback = "Your parent ended its turn without answering, so this request was refused."; @@ -2656,6 +2665,13 @@ pub const Runtime = struct { const child = registry.findPersistent(agent) orelse break :blk null; break :blk try a.dupe(u8, child.id); } orelse return self.refuseNotOpen(alloc, agent); + // Refuse the request the child waits on before the stop takes + // admission: the stopper holds admission and the owner's mutex while it + // waits for the child's worker, and `refuseChild` takes neither (it + // releases the registry mutex before it answers the worker), so the + // note path's worker -> registry order and this registry -> owner -> + // worker order cannot cycle (the E1 rule). + _ = self.approvals.refuseChild(child_id, stopped_approval_feedback); const dropped, const stopped = blk: { self.admission_mutex.lockUncancelable(io_mod.getIo()); defer self.admission_mutex.unlock(io_mod.getIo()); @@ -2845,6 +2861,10 @@ pub const Runtime = struct { @memcpy(name_buf[0..value.len], value); break :blk name_buf[0..value.len]; }; + // As a stop does, refuse the request this child waits on before the + // close takes admission, so the call is refused with the reason and + // nothing runs. `refuseChild` holds no lock across its wait (see it). + _ = self.approvals.refuseChild(child_id, if (by == .user) user_closed_approval_feedback else parent_closed_approval_feedback); const result: Closed, const settle_now = blk: { self.admission_mutex.lockUncancelable(io_mod.getIo()); defer self.admission_mutex.unlock(io_mod.getIo()); @@ -3130,6 +3150,14 @@ pub const Runtime = struct { debug_trace.logf("mailbox", "waiting note lost child={s} err={s}", .{ child_id, @errorName(err) }); } + /// The person answered `child_id`'s request on its own screen, so its + /// registry binding goes with it: main's later answer finds nothing and + /// reads that the request is no longer waiting + /// (`tests/tla/subagent/TuiParentApproval.tla` AnswerOnce). + pub fn withdrawAnsweredApproval(self: *Runtime, child_id: []const u8) usize { + return self.approvals.withdrawChild(child_id); + } + /// Tells the owner, as child `child_id`'s own message, that it waits on /// the owner's approval for `label`, so a parent that would otherwise /// wait hears of it. A note for a child that is closing or gone, or one @@ -12167,3 +12195,58 @@ test "an answer whose request ends during the check says it is no longer waiting // Nothing reached the worker: the request had already ended. try std.testing.expect(t.worker.decision == null); } + +test "a stop refuses the child's waiting request once, with the reason" { + var t: ApprovalFixture = undefined; + try t.init(); + defer t.deinit(); + try t.register("run touch marker"); + + const stopped = try t.runtime.stopChild(t.arena(), "reviewer"); + // The fixture's work already ended, so the stop answers that it was not + // working; the refusal is what this test reads. + try expectAnswerHas(stopped.body, "reviewer"); + try std.testing.expectEqual(@as(?types.ToolPermissionDecision, .deny), t.worker.decision); + try expectAnswerHas(t.worker.feedbackText(), "Your parent stopped you before answering this request"); + try std.testing.expect((try t.runtime.approvals.firstPendingForChild(t.arena(), "child-1")) == null); + + // A second stop finds nothing to refuse. + t.worker = .{}; + _ = try t.runtime.stopChild(t.arena(), "reviewer"); + try std.testing.expect(t.worker.decision == null); + try std.testing.expectEqualStrings("", t.worker.feedbackText()); +} + +test "a close refuses the child's waiting request with the reason of who closed it" { + for ([_]Runtime.CloseBy{ .parent, .user }) |by| { + var t: ApprovalFixture = undefined; + try t.init(); + defer t.deinit(); + try t.register("run touch marker"); + + // The close's own result is not what this test reads: the refusal comes first. + _ = t.runtime.closeChild("child-1", by) catch |err| switch (err) { + error.CloseNotSaved => null, + else => return err, + }; + try std.testing.expectEqual(@as(?types.ToolPermissionDecision, .deny), t.worker.decision); + if (by == .user) { + try expectAnswerHas(t.worker.feedbackText(), "The person closed you before this request was answered"); + } else { + try expectAnswerHas(t.worker.feedbackText(), "Your parent closed you before answering this request"); + } + try std.testing.expect((try t.runtime.approvals.firstPendingForChild(t.arena(), "child-1")) == null); + } +} + +test "a stop or close with nothing waiting refuses nothing" { + var t: ApprovalFixture = undefined; + try t.init(); + defer t.deinit(); + + _ = try t.runtime.stopChild(t.arena(), "reviewer"); + try std.testing.expect(t.worker.decision == null); + // The close's own result is not what this test reads. + _ = try t.runtime.closeChild("child-1", .parent); + try std.testing.expect(t.worker.decision == null); +} diff --git a/src/main.zig b/src/main.zig index b4eb96be95..4bacf5ba4c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -3621,6 +3621,13 @@ const App = struct { AgentsAppRuntime.notePromptAsked(self, agent, kind); } + /// The person answered a subagent's request on its own screen, so its + /// registry binding goes with it and main's later answer reads that it no + /// longer waits. + pub fn withdrawAnsweredApproval(self: *App, agent: *agents.Agent) void { + AgentsAppRuntime.withdrawAnsweredApproval(self, agent); + } + /// Whether `agent` keeps its approval prompt this pass, /// because an approval is lent between main and a subagent. pub fn keepLentApproval(self: *App, agent: *agents.Agent, pending: ?permission_request.PermissionRequest) bool { diff --git a/src/ui/approval_screen.zig b/src/ui/approval_screen.zig index 0e42d315ab..82417fe50b 100644 --- a/src/ui/approval_screen.zig +++ b/src/ui/approval_screen.zig @@ -1861,7 +1861,7 @@ test "file approval screen exposes a scrollable full review" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var first = try paintTest(alloc, approval.projection().?, &screen_state, &.{}, .{}, testLayout(12, 32), true); defer first.deinit(alloc); @@ -1901,7 +1901,7 @@ test "file approval screen anchors transcript and review at the document tail" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var tail = try paintTest(alloc, approval.projection().?, &screen_state, entries.items, .{}, testLayout(14, 100), true); defer tail.deinit(alloc); @@ -1999,7 +1999,7 @@ test "large file approval paints a bounded tail before hydrating the full docume var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var first_frame_storage: [64 * 1024]u8 = undefined; var first_frame_allocator = std.heap.FixedBufferAllocator.init(&first_frame_storage); @@ -2071,7 +2071,7 @@ test "file approval document separates transcript, diff, and controls" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var screen = try paintTest(alloc, approval.projection().?, &screen_state, &entries, .{}, testLayout(14, 48), true); defer screen.deinit(alloc); @@ -2116,7 +2116,7 @@ test "file approval transcript uses the current rail presentation" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var screen = try paintTest( alloc, @@ -2161,12 +2161,12 @@ test "file approval top-aligns a fitting welcome document and clears below" { var grid = try vt_emulator.Grid.init(alloc, 80, 24); defer grid.deinit(); - try std.testing.expect(approval.syncReview(&previous_review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &previous_review, try diff_mod.OwnedReview.init(alloc, &previous_review))); var previous = try paintTest(alloc, approval.projection().?, &screen_state, &entries, .{}, testLayout(24, 80), true); defer previous.deinit(alloc); try grid.feed(previous.bytes); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var screen = try paintTest(alloc, approval.projection().?, &screen_state, &entries, .{}, testLayout(24, 80), false); defer screen.deinit(alloc); try grid.feed(screen.bytes); @@ -2219,7 +2219,7 @@ test "file approval transcript viewport resumes styled links without leaking int var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var screen = try paintTest(alloc, approval.projection().?, &screen_state, &entries, .{}, testLayout(14, 12), true); defer screen.deinit(alloc); @@ -2255,7 +2255,7 @@ test "file approval screen wraps changed source without omitting bytes" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var first = try paintTest(alloc, approval.projection().?, &screen_state, &.{}, .{}, testLayout(12, 12), true); defer first.deinit(alloc); @@ -2283,7 +2283,7 @@ test "file approval renders exact unchanged-line elision markers" { var approval = approval_prompt.ApprovalPrompt{}; defer approval.deinit(alloc); try std.testing.expect(try approval.syncRequest(alloc, testFileRequest())); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var screen = try paintTest(alloc, approval.projection().?, &screen_state, &.{}, .{}, testLayout(40, 80), true); defer screen.deinit(alloc); @@ -2315,7 +2315,7 @@ test "file approval readiness retains an observed change for the same request" { defer approval.deinit(alloc); const request = testFileRequest(); try std.testing.expect(try approval.syncRequest(alloc, request)); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var shell = struct { render_requests: render_request.RenderRequestState = .{}, @@ -2350,7 +2350,7 @@ test "file approval readiness retains an observed change for the same request" { replacement.id += 1; try std.testing.expect(try approval.syncRequest(alloc, replacement)); screen_state.clear(); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); screen_state.recordScreenCommit(approval.request.?.id, .{ .request_id = replacement.id, .rows = shell.layout.rows, @@ -2380,7 +2380,7 @@ test "file approval renders controls ready after inspecting a changed row" { defer approval.deinit(alloc); const request = testFileRequest(); try std.testing.expect(try approval.syncRequest(alloc, request)); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); screen_state.recordScreenCommit(approval.request.?.id, .{ .request_id = request.id, .rows = 14, @@ -2423,7 +2423,7 @@ test "file approval readiness requires a committed matching screen" { defer approval.deinit(alloc); const request = testFileRequest(); try std.testing.expect(try approval.syncRequest(alloc, request)); - try std.testing.expect(approval.syncReview(&review)); + try std.testing.expect(approval.adoptReview(alloc, approval.request.?.id, &review, try diff_mod.OwnedReview.init(alloc, &review))); var shell = struct { render_requests: render_request.RenderRequestState = .{}, diff --git a/src/ui/footer/interaction_state.zig b/src/ui/footer/interaction_state.zig index dadf0c8369..62f1da0409 100644 --- a/src/ui/footer/interaction_state.zig +++ b/src/ui/footer/interaction_state.zig @@ -117,7 +117,7 @@ test "command approval retains its committed screen state across review sync" { .document_scrollable = true, }); - try std.testing.expect(!prompt.syncReview(null)); + try std.testing.expect(!prompt.adoptReview(alloc, null, null, null)); try std.testing.expect(prompt.review == null); try std.testing.expectEqual(@as(usize, 6), screen.document_scroll_rows); try std.testing.expectEqual(request.id, screen.screen_commit.?.request_id); diff --git a/tests/e2e/gateway-stream-lifecycle.test.ts b/tests/e2e/gateway-stream-lifecycle.test.ts index 93bc18f2d0..321b200aba 100644 --- a/tests/e2e/gateway-stream-lifecycle.test.ts +++ b/tests/e2e/gateway-stream-lifecycle.test.ts @@ -10935,6 +10935,58 @@ printf '%s' ${JSON.stringify(trailingMarker)} > ${JSON.stringify(effectPath)} } }, 30_000); +const LIST_HINT = "enter switch"; + +// A promise the fake resolves when it records a value, so a test waits on the +// record itself instead of sampling for it. +function heldValue() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => (resolve = res)); + return { promise, resolve }; +} + +// Awaits `promise`, failing with `what` when it is not settled within `ms`. The +// race only bounds the wait: what the test waits on is the signal the fake sends. +async function within(promise: Promise, ms: number, what: string): Promise { + const expired = new Promise((_, reject) => { + AbortSignal.timeout(ms).addEventListener("abort", () => reject(new Error(`timed out waiting for ${what}`)), { once: true }); + }); + return await Promise.race([promise, expired]); +} + +// Shows `agent`, "main" or a subagent's name, through the agent list: Ctrl+X +// opens it whatever the composer holds, each arrow shows the next row's agent, +// and Enter keeps it. Main's row comes first, then its working subagents, then +// the rest by their latest reply. Those rows can move while the list is open, +// so each step reads the rows again instead of counting them. +async function showAgent(session: TmuxSession, agent: string) { + await selectAgent(session, agent); + await session.sendKeys("Enter"); + // The list's header is gone once Enter kept the highlighted agent. + await session.waitForPane((pane) => !pane.includes("Agents 1"), 10_000); +} + +// Opens the agent list and highlights `agent`'s row: the list's search box +// narrows the rows to that agent's own, and it reports how many it kept, so the +// state to wait for is its one-row header. +async function selectAgent(session: TmuxSession, agent: string) { + await session.sendKeys("C-x"); + await session.waitForText(LIST_HINT, 10_000); + await session.sendLiteral(agent); + await session.waitForPane((pane) => pane.includes("Agents 1"), 15_000); +} + +// The person opens the subagent's own screen and types a task there, so its turn +// is one the person started. A turn main started is answered by main and its +// request is never lent; a turn the person typed still lends its approval to +// main's screen, which is the path these tests keep +// (`tests/tla/subagent/TuiParentApproval.tla` NoStaleLent). +async function typeTaskOnSubagent(session: TmuxSession, agent: string, ready: string, task: string) { + await showAgent(session, agent); + await session.waitForPane((pane) => pane.includes(ready), 30_000); + await session.sendText(task); +} + test("subagent search recovers when its target disappears during approval", async () => { const root = createFixtureRoot("subagent-search-recheck"); const trace = join(root.root, "trace.log"), stderr = join(root.root, "stderr.log"); @@ -10943,12 +10995,21 @@ printf '%s' ${JSON.stringify(trailingMarker)} > ${JSON.stringify(effectPath)} writeFileSync(join(target, "match.txt"), "APPROVAL_SEARCH\n"); writeFileSync(join(root.workspace, "notes.txt"), "AFTER_APPROVAL\n"); writeFileSync(join(root.home, ".fx/settings.json"), JSON.stringify({ permission: { grep_files: "ask" } })); + const readyToken = "SEARCHER_READY_TASK"; let childRequests = 0; - const gateway = startDynamicFakeGateway((body) => { + // The searcher's task request waits until the person is back on main, so the + // lent prompt finds them there. A typed turn owes no report, so the evidence + // at the end is what the child read; the note test beside this one covers + // main's side. + let releaseTask!: () => void; + const backOnMain = new Promise((resolve) => (releaseTask = resolve)); + const childReadBack = heldValue(); + const gateway = startDynamicFakeGateway(async (body) => { // The child's report starts main's next turn. + // A typed turn owes no report; only the ready turn's report reaches main. if (latestUserIsReport(body)) { - expect(body).toContain("CHILD_RECOVERED"); - return fakeGatewayFinalText("APPROVAL_RECOVERY_COMPLETE"); + expect(latestUserText(body)).not.toContain("CHILD_RECOVERED"); + return fakeGatewayFinalText("MAIN_SAW_SEARCHER_READY"); } if (hasCurrentToolResult(body, "approval-child")) { expect(JSON.parse(toolResultOutput(body, "approval-child")).ok).toBe(true); @@ -10957,18 +11018,23 @@ printf '%s' ${JSON.stringify(trailingMarker)} > ${JSON.stringify(effectPath)} // An interactive subagent is offered the subagent tool too, so its // requests tell apart by main's prompt, which they never carry. if (!body.includes("Delegate the prepared search.")) { + // The searcher's first turn only makes it ready: the person then types + // the task on its own screen, so the turn keeps its three requests. + if (latestUserText(body).includes(readyToken)) return fakeGatewayFinalText("SEARCHER_CHILD_READY"); childRequests++; if (hasCurrentToolResult(body, "after-approval")) { expect(toolResultOutput(body, "after-approval")).toContain("AFTER_APPROVAL"); + childReadBack.resolve(); return fakeGatewayFinalText("CHILD_RECOVERED"); } if (hasCurrentToolResult(body, "approval-search")) { expect(toolResultOutput(body, "approval-search")).toContain("Path not found: search-target"); return fakeGatewayToolCall("after-approval", "read_file", { path: "notes.txt" }); } + await backOnMain; return fakeGatewayToolCall("approval-search", "grep_files", { pattern: "APPROVAL_SEARCH", path: "search-target" }); } - return fakeGatewayToolCall("approval-child", "subagent", { request: { action: "message", agent: "searcher", message: "Search the fixture, then read notes.txt." } }); + return fakeGatewayToolCall("approval-child", "subagent", { request: { action: "message", agent: "searcher", message: readyToken } }); }, { classifierDecision: "clear" }); let session: TmuxSession | null = null; try { @@ -10979,11 +11045,16 @@ printf '%s' ${JSON.stringify(trailingMarker)} > ${JSON.stringify(effectPath)} }); await session.waitForStableComposer(15_000); await session.sendText("Delegate the prepared search."); + // The person types the searcher's task on its own screen, so the turn is + // theirs, and returns to main, where the request is lent to them. + await typeTaskOnSubagent(session, "searcher", "SEARCHER_CHILD_READY", "Search the fixture, then read notes.txt."); + await showAgent(session, "main"); + releaseTask(); await session.waitForPane(pane => pane.includes("APPROVAL_SEARCH") && pane.includes("esc cancel"), 15_000); expect(existsSync(join(target, "match.txt"))).toBe(true); renameSync(target, join(root.workspace, "moved-target")); await session.sendKeys("Enter"); - await session.waitForText("APPROVAL_RECOVERY_COMPLETE", 15_000); + await within(childReadBack.promise, 15_000, "the child to read notes.txt back"); await session.waitForStableComposer(15_000); expect(childRequests).toBe(3); const lines = readFileSync(trace, "utf8").split("\n").filter(line => line.includes("call_id=approval-search ")); @@ -11001,6 +11072,110 @@ printf '%s' ${JSON.stringify(trailingMarker)} > ${JSON.stringify(effectPath)} } }, 60_000); + test("subagent search approved through main's note is refused when its target disappears", async () => { + const root = createFixtureRoot("subagent-search-recheck-note"); + const trace = join(root.root, "trace.log"), stderr = join(root.root, "stderr.log"); + const target = join(root.workspace, "search-target"); + mkdirSync(target); + writeFileSync(join(target, "match.txt"), "APPROVAL_SEARCH\n"); + writeFileSync(join(root.workspace, "notes.txt"), "AFTER_APPROVAL\n"); + writeFileSync(join(root.home, ".fx/settings.json"), JSON.stringify({ permission: { grep_files: "ask" } })); + // The searcher asks under its own profile, so its request reaches main, + // which is in full access and can approve it. + mkdirSync(join(root.home, ".fx", "agents", "searcher"), { recursive: true }); + writeFileSync(join(root.home, ".fx", "agents", "searcher", "profile.json"), JSON.stringify({ + description: "Searches and reads", tools: ["grep_files", "read_file"], permission_mode: "ask", + })); + // Each step of the child's turn: it asks for the search, the refusal + // reaches it, and it reads notes.txt. + const childSteps: string[] = []; + // The child's request starts in main's turn, so main hears it as one note + // and answers it with the subagent tool. The note waits here until the test + // has moved the search target away. + let note: string | null = null; + let releaseApprove!: () => void; + const approveMayGo = new Promise((resolve) => (releaseApprove = resolve)); + const gateway = startDynamicFakeGateway(async (body) => { + // The child's report starts main's next turn. + if (latestUserIsReport(body)) { + expect(body).toContain("CHILD_RECOVERED"); + return fakeGatewayFinalText("APPROVAL_RECOVERY_COMPLETE"); + } + if (latestUserText(body).includes("I wait for your approval to run") && !body.includes("approval-approve")) { + note = latestUserText(body); + await approveMayGo; + return fakeGatewayToolCall("approval-approve", "subagent", { request: { action: "approve", agent: "searcher" } }); + } + if (hasCurrentToolResult(body, "approval-approve")) return fakeGatewayFinalText("APPROVAL_ANSWERED"); + if (hasCurrentToolResult(body, "approval-child")) { + expect(JSON.parse(toolResultOutput(body, "approval-child")).ok).toBe(true); + return fakeGatewayFinalText("APPROVAL_SEARCH_SENT"); + } + // An interactive subagent is offered the subagent tool too, so its + // requests tell apart by main's prompt, which they never carry. + if (!body.includes("Delegate the prepared search.")) { + if (hasCurrentToolResult(body, "after-approval")) { + childSteps.push("read"); + expect(toolResultOutput(body, "after-approval")).toContain("AFTER_APPROVAL"); + return fakeGatewayFinalText("CHILD_RECOVERED"); + } + if (hasCurrentToolResult(body, "approval-search")) { + childSteps.push("refused"); + // Main's approval checks the search as its own call, finds the + // target gone, and refuses it with that reason, which the child + // reads before it goes on. + expect(body).toContain("Path not found: search-target"); + return fakeGatewayToolCall("after-approval", "read_file", { path: "notes.txt" }); + } + childSteps.push("asked"); + return fakeGatewayToolCall("approval-search", "grep_files", { pattern: "APPROVAL_SEARCH", path: "search-target" }); + } + return fakeGatewayToolCall("approval-child", "subagent", { request: { action: "message", agent: "searcher", profile: "searcher", message: "Search the fixture, then read notes.txt." } }); + }, { classifierDecision: "clear" }); + let session: TmuxSession | null = null; + try { + session = await TmuxSession.create({ + cmd: FX_BIN, cwd: root.workspace, isolated: true, remainOnExit: true, width: 120, height: 38, stderrPath: stderr, + env: { ...fixtureEnv(root, gateway, trace), FX_PERMISSION_MODE: "yolo", FX_DISABLE_KEYCHAIN: "1", FX_SOUND: "0", FX_AUTO_UPGRADE: "0", + FX_TRACE_SCOPES: "agent,tool,permission,subagent" }, + }); + await session.waitForStableComposer(15_000); + await session.sendText("Delegate the prepared search."); + // The note names the search the child asks for, and no screen asks the + // person for it: main answers it. + expect(await waitUntil(() => note !== null, 15_000)).toBe(true); + const noteText = note!; + expect(noteText).toContain("grep_files"); + expect(noteText).toContain("APPROVAL_SEARCH"); + const waiting = await session.capturePane(); + expect(waiting).not.toContain("Would you like to allow this action?"); + expect(waiting).not.toContain("searcher needs approval"); + expect(existsSync(join(target, "match.txt"))).toBe(true); + renameSync(target, join(root.workspace, "moved-target")); + releaseApprove(); + await session.waitForText("APPROVAL_RECOVERY_COMPLETE", 15_000); + await session.waitForStableComposer(15_000); + // The child asks for the search once, the refusal reaches it, and it + // reads notes.txt; no second search is asked. + expect([...new Set(childSteps)].sort()).toEqual(["asked", "read", "refused"]); + const lines = readFileSync(trace, "utf8").split("\n").filter(line => line.includes("call_id=approval-search ")); + // The request was asked and answered, and its target was gone at the + // answer, so it never ran. + expect(lines.some(line => line.includes("event=permission_requested"))).toBe(true); + expect(lines.some(line => line.includes("event=permission_decision") && line.includes("decision=once"))).toBe(false); + expect(lines.some(line => line.includes("event=execution_start"))).toBe(false); + expect(readFileSync(join(root.workspace, "moved-target/match.txt"), "utf8")).toBe("APPROVAL_SEARCH\n"); + await session.sendText("/quit"); + await session.waitForPane(() => session!.paneStatus().dead, 10_000); + expect(session.paneStatus().status).toBe(0); + expect(readFileSync(stderr, "utf8")).toBe(""); + } finally { + await session?.kill(); + gateway.stop(); + rmSync(root.root, { recursive: true, force: true }); + } + }, 60_000); + test("ask fake Gateway exercises named subagents, each message answered by its report", async () => { const root = createFixtureRoot("subagent-managed-flow"); const tracePath = join(root.root, "trace.log"); diff --git a/tests/e2e/sessions.test.ts b/tests/e2e/sessions.test.ts index 10be335298..aff790794f 100644 --- a/tests/e2e/sessions.test.ts +++ b/tests/e2e/sessions.test.ts @@ -300,10 +300,10 @@ function command(fixture: Fixture, gateway: any, args: string[], cwd = fixture.w return runFx(args, { cwd, env: env(fixture, gateway), timeoutMs: TIMEOUT }); } -async function ask(fixture: Fixture, gateway: any, args: string[]) { +async function ask(fixture: Fixture, gateway: any, args: string[], extraEnv: Record = {}) { const result = await runFx(["ask", "--json", "--auto", ...args], { cwd: fixture.workspace, - env: env(fixture, gateway), + env: { ...env(fixture, gateway), ...extraEnv }, timeoutMs: TIMEOUT, }); return result; @@ -3882,6 +3882,50 @@ test("fx ask: main's deny refuses a subagent's approval request with its reason" } }, TIMEOUT * 2); +test("fx ask: main's stop refuses a subagent's approval request, and nothing runs", async () => { + const fixture = createFixture("fx-v2-subagent-approval-stop-"); + const profileDir = join(fixture.home, ".fx", "agents", "asker"); + mkdirSync(profileDir, { recursive: true }); + writeFileSync(join(profileDir, "profile.json"), JSON.stringify({ description: "Runs one command", tools: ["shell"], permission_mode: "ask" })); + const gateway = startDynamicFakeGateway(async (body) => { + if (isChildRequest(body) && !body.includes("call_child_shell")) { + await waitForRootTurnCommitted(fixture.home); + return fakeGatewayToolCall("call_child_shell", "shell", { request: { action: "run", command: "touch stopped.txt" } }); + } + if (isChildRequest(body)) { + return fakeGatewayFinalText(body.includes("Your parent stopped you before answering this request") ? "CHILD_SAW_STOP" : "CHILD_NO_REASON"); + } + if (body.includes("I wait for your approval to run") && !body.includes("call_main_stop")) { + return fakeGatewayToolCall("call_main_stop", "subagent", { action: "stop", agent: "asker" }); + } + if (body.includes("call_main_stop") && !isReportTurn(body)) return fakeGatewayFinalText("MAIN_STOPPED"); + if (isReportTurn(body)) return fakeGatewayFinalText("PARENT_DONE"); + if (body.includes("delegate-asker")) return fakeGatewayFinalText("PARENT_SENT"); + return fakeGatewayToolCall("delegate-asker", "subagent", { request: { action: "message", agent: "asker", profile: "asker", message: "Touch stopped.txt." } }); + }, { classifierDecision: "clear" }); + try { + const trace = join(fixture.root, "fx-trace.log"); + const result = await ask(fixture, gateway, ["Delegate the command."], { FX_TRACE_LOG: trace, FX_TRACE_SCOPES: "subagent,mailbox" }); + expect(result.code).toBe(0); + expect(result.stderr).not.toContain("panic"); + const output = JSON.parse(result.stdout); + expect(existsSync(join(fixture.workspace, "stopped.txt"))).toBe(false); + expect(output.output).toContain("MAIN_STOPPED"); + // The stop refused the waiting request before it ended the turn: the trace + // names the request it refused, and the unit test proves the worker read + // the reason. The call never returned a result, so nothing ran. + expect(readFileSync(trace, "utf8")).toMatch(/approval requests refused child=\S+ refused=1 gone=0 ids=\S+/); + const lines = childLines(fixture.home, output.session_id); + const childLog = JSON.stringify(logLines(fixture.home, lines[0].child)); + expect(childLog).toContain("call_child_shell"); + expect(childLog).toContain("turn_interrupted"); + expect(childLog).not.toContain("tool_result"); + } finally { + gateway.stop(); + rmSync(fixture.root, { recursive: true, force: true }); + } +}, TIMEOUT * 2); + test("fx ask: main's approve is refused when main's own review holds the action", async () => { const fixture = createFixture("fx-v2-subagent-approval-caution-"); // The same subagent as the approve test, but main's own safety review holds diff --git a/tests/e2e/tui-command-permissions.test.ts b/tests/e2e/tui-command-permissions.test.ts index de3ae11a57..2b627430b1 100644 --- a/tests/e2e/tui-command-permissions.test.ts +++ b/tests/e2e/tui-command-permissions.test.ts @@ -4020,6 +4020,58 @@ describe("effect-aware command permissions", () => { 60_000, ); +const LIST_HINT = "enter switch"; + +// A promise the fake resolves when it records a value, so a test waits on the +// record itself instead of sampling for it. +function heldValue() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => (resolve = res)); + return { promise, resolve }; +} + +// Awaits `promise`, failing with `what` when it is not settled within `ms`. The +// race only bounds the wait: what the test waits on is the signal the fake sends. +async function within(promise: Promise, ms: number, what: string): Promise { + const expired = new Promise((_, reject) => { + AbortSignal.timeout(ms).addEventListener("abort", () => reject(new Error(`timed out waiting for ${what}`)), { once: true }); + }); + return await Promise.race([promise, expired]); +} + +// Shows `agent`, "main" or a subagent's name, through the agent list: Ctrl+X +// opens it whatever the composer holds, each arrow shows the next row's agent, +// and Enter keeps it. Main's row comes first, then its working subagents, then +// the rest by their latest reply. Those rows can move while the list is open, +// so each step reads the rows again instead of counting them. +async function showAgent(session: TmuxSession, agent: string) { + await selectAgent(session, agent); + await session.sendKeys("Enter"); + // The list's header is gone once Enter kept the highlighted agent. + await session.waitForPane((pane) => !pane.includes("Agents 1"), 10_000); +} + +// Opens the agent list and highlights `agent`'s row: the list's search box +// narrows the rows to that agent's own, and it reports how many it kept, so the +// state to wait for is its one-row header. +async function selectAgent(session: TmuxSession, agent: string) { + await session.sendKeys("C-x"); + await session.waitForText(LIST_HINT, 10_000); + await session.sendLiteral(agent); + await session.waitForPane((pane) => pane.includes("Agents 1"), 15_000); +} + +// The person opens the subagent's own screen and types a task there, so its turn +// is one the person started. A turn main started is answered by main and its +// request is never lent; a turn the person typed still lends its approval to +// main's screen, which is the path these tests keep +// (`tests/tla/subagent/TuiParentApproval.tla` NoStaleLent). +async function typeTaskOnSubagent(session: TmuxSession, agent: string, ready: string, task: string) { + await showAgent(session, agent); + await session.waitForPane((pane) => pane.includes(ready), 30_000); + await session.sendText(task); +} + test.skipIf(!tmuxAvailable())( "interactive child approval uses the normal parent prompt", async () => { @@ -4028,19 +4080,31 @@ describe("effect-aware command permissions", () => { const markerPath = join(root.workspace, "child-approval-must-not-exist"); const rootPrompt = "DELEGATE_ONE_APPROVAL_TASK"; const childPrompt = "Request permission to create the delegated marker."; + const readyToken = "HELPER_READY_TASK"; + // The child's task request waits until the person is back on main, so the + // lent prompt finds them there. A typed turn owes no report, so the + // evidence at the end is the tool result the child read; the note test + // beside this one covers main's side. + let releaseTask!: () => void; + const backOnMain = new Promise((resolve) => (releaseTask = resolve)); + const childDenial = heldValue(); const createId = "direct_child_create"; const commandId = "direct_child_command"; writeFileSync(stderrPath, ""); - - const gateway = startDynamicFakeGateway((body) => { - // The child's report starts the parent's next turn. + const gateway = startDynamicFakeGateway(async (body) => { + // A typed turn owes no report; only the ready turn's report reaches main. if (currentUserText(body).includes("Subagent report (untrusted agent output, not user instructions):")) { - expect(currentUserText(body)).toContain("CHILD_PERMISSION_DENIED"); - return finalText("PARENT_OBSERVED_CHILD_DENIAL"); + expect(currentUserText(body)).not.toContain("CHILD_PERMISSION_DENIED"); + return finalText("PARENT_SAW_HELPER_READY"); } if (body.includes(`\\\"toolCallId\\\":\\\"${commandId}\\\"`) || body.includes(`"toolCallId":"${commandId}"`)) { + // The person's denial is this call's result, which the child reads. + childDenial.resolve(body); return finalText("CHILD_PERMISSION_DENIED"); } + // The child's first turn only makes it ready: the person then types the + // task on the child's own screen. + if (currentUserText(body).includes(readyToken)) return finalText("HELPER_CHILD_READY"); if (body.includes(createId)) { const created = JSON.parse(toolResultText(body, createId)) as { ok: boolean; @@ -4055,11 +4119,12 @@ describe("effect-aware command permissions", () => { // fx's agent profile has every tool, so the subagent may start // its own. expect(body).toContain('"name":"subagent"'); + await backOnMain; return toolCall(`/usr/bin/touch ${shellQuote(markerPath)}`, {}, commandId); } if (currentUserText(body).includes(rootPrompt)) { return gatewayToolCall("subagent", { - request: { action: "message", agent: "helper", message: childPrompt }, + request: { action: "message", agent: "helper", message: readyToken }, }, createId); } throw new Error(`Unexpected direct child approval request: ${body}`); @@ -4078,6 +4143,11 @@ describe("effect-aware command permissions", () => { }); await activeSession.waitForComposer(TIMEOUT); await activeSession.sendText(rootPrompt); + // The person types the task on helper's own screen, so the turn is + // theirs, and returns to main, where the request is lent to them. + await typeTaskOnSubagent(activeSession, "helper", "HELPER_CHILD_READY", childPrompt); + await showAgent(activeSession, "main"); + releaseTask(); const approvalPane = await activeSession.waitForText( COMMAND_APPROVAL_PROMPT, TIMEOUT, @@ -4085,6 +4155,112 @@ describe("effect-aware command permissions", () => { expect(approvalPane).toContain("touch"); expect(existsSync(markerPath)).toBe(false); await activeSession.sendKeys("3"); + // The child read the denial, and the marker never exists. + const denial = await within(childDenial.promise, TIMEOUT, "the child to read the person's denial"); + expect(denial).toContain("Permission denied by user"); + expect(existsSync(markerPath)).toBe(false); + await activeSession.sendText("/quit"); + expect(await activeSession.waitForSessionEnd(5_000)).toBe(true); + activeSession = null; + expect(readFileSync(stderrPath, "utf8")).toBe(""); + }, + 90_000, + ); + + test.skipIf(!tmuxAvailable())( + "interactive child approval asks the parent as a note the parent denies", + async () => { + const root = createIsolatedRoot(); + const stderrPath = join(root.root, "interactive-child-approval-stderr.log"); + const markerPath = join(root.workspace, "child-approval-must-not-exist"); + const command = `/usr/bin/touch ${shellQuote(markerPath)}`; + const rootPrompt = "DELEGATE_ONE_APPROVAL_TASK"; + const childPrompt = "Request permission to create the delegated marker."; + const createId = "direct_child_create"; + const commandId = "direct_child_command"; + const denyId = "direct_child_deny"; + writeFileSync(stderrPath, ""); + // The child's request starts in the parent's turn, so the parent hears it + // as one note and answers it with the subagent tool. The note waits until + // the test has looked at the screen. + const note = heldValue(); + let releaseDeny!: () => void; + const denyMayGo = new Promise((resolve) => (releaseDeny = resolve)); + + const gateway = startDynamicFakeGateway(async (body) => { + // The child's report starts the parent's next turn. + if (currentUserText(body).includes("Subagent report (untrusted agent output, not user instructions):")) { + expect(currentUserText(body)).toContain("CHILD_PERMISSION_DENIED"); + return finalText("PARENT_OBSERVED_CHILD_DENIAL"); + } + // The note names the command the child asks for and the child itself. + if (currentUserText(body).includes("I wait for your approval to run") && !body.includes(denyId)) { + note.resolve(currentUserText(body)); + await denyMayGo; + return gatewayToolCall("subagent", { + request: { action: "deny", agent: "helper", message: "Not in this workspace." }, + }, denyId); + } + if (body.includes(`\\\"toolCallId\\\":\\\"${commandId}\\\"`) || body.includes(`"toolCallId":"${commandId}"`)) { + return finalText("CHILD_PERMISSION_DENIED"); + } + if (body.includes(createId)) { + const created = JSON.parse(toolResultText(body, createId)) as { + ok: boolean; + result?: string; + }; + expect(created.ok).toBe(true); + expect(created.result).toContain("Sent to helper"); + expect(toolResultText(body, createId)).not.toContain("child_id"); + return finalText("PARENT_TURN_DONE"); + } + if (currentUserText(body).includes(childPrompt)) { + // fx's agent profile has every tool, so the subagent may start + // its own. + expect(body).toContain('"name":"subagent"'); + return toolCall(command, {}, commandId); + } + if (currentUserText(body).includes(rootPrompt)) { + return gatewayToolCall("subagent", { + request: { action: "message", agent: "helper", message: childPrompt }, + }, createId); + } + throw new Error(`Unexpected direct child approval request: ${body}`); + }); + gateways.push(gateway); + + activeSession = await TmuxSession.create({ + cmd: FX_BIN, + cwd: root.workspace, + env: gatewayEnv(root, gateway, { + FX_PERMISSION_MODE: "ask", + }), + stderrPath, + width: 120, + height: 40, + }); + await activeSession.waitForComposer(TIMEOUT); + await activeSession.sendText(rootPrompt); + // The note names the command and the child that asks, and no screen offers + // the request to the person. Its action is one terminal-safe line + // (`live_metrics.storeLabel`'s 160 bytes around the cut command), so a long + // workspace path, as macOS makes, hides the marker's tail. + const noteText = await within(note.promise, TIMEOUT, "the note to reach the parent"); + expect(noteText).toContain("/usr/bin/touch"); + expect(noteText).toContain("helper"); + const label = `shell.run ${command}`; + const after = "I wait for your approval to run: "; + const action = noteText.slice(noteText.indexOf(after) + after.length).split(". Answer with the subagent tool")[0]!; + // The action is the label itself, or the label's own head cut for one line + // with a cut marker; a long workspace path, as macOS makes, cuts before the + // marker's name, so only the label held whole shows that name. + expect(label.startsWith(action.replace(/(?:\.\.\.|…)+$/, ""))).toBe(true); + if (action === label) expect(noteText).toContain("child-approval-must-not-exist"); + else expect(action).toMatch(/(?:\.\.\.|…)+$/); + const waiting = await activeSession.capturePane(); + expect(waiting).not.toContain(COMMAND_APPROVAL_PROMPT); + expect(existsSync(markerPath)).toBe(false); + releaseDeny(); const reported = await activeSession.waitForText("PARENT_OBSERVED_CHILD_DENIAL", TIMEOUT); // The report shows as a finished subagent row, not as the user's prompt. expect(reported).toContain("helper finished"); diff --git a/tests/e2e/tui-host-instances.test.ts b/tests/e2e/tui-host-instances.test.ts index 879ef5699e..da84de4295 100644 --- a/tests/e2e/tui-host-instances.test.ts +++ b/tests/e2e/tui-host-instances.test.ts @@ -38,7 +38,7 @@ function agentRows(paneEscapes: string): Array<{ name: string; selected: boolean const rows: Array<{ name: string; selected: boolean }> = []; for (const line of paneEscapes.split("\n")) { const plain = line.replace(/\x1b\[[0-9;]*m/g, ""); - const row = /^ {2}(?:(fx \d+|main)|[\u251c\u2514] (\S+)) {2,}\S/.exec(plain); + const row = /^ {2}(?:(fx \d+|main)|(?:[\u2502 ] )?[\u251c\u2514] (\S+)) {2,}\S/.exec(plain); if (row) rows.push({ name: (row[1] ?? row[2])!, selected: line.includes("\x1b[1m") }); } return rows; @@ -58,6 +58,52 @@ async function waitForSelected(session: TmuxSession, name: string, ms = 10_000): // Directions follow the list's order: the instances as they started, each // followed by its own subagents. A number selects that fx instance. +// Opens the agent list and selects `name`, an instance's or a subagent's row. +// A subagent's row appears once its parent has started it, which can be a +// moment after the parent's turn shows it did. +async function showNamedAgent(session: TmuxSession, name: string) { + const deadline = Date.now() + 30_000; + await session.sendKeys("C-x"); + await session.waitForText(LIST_HINT, 10_000); + // The list redraws as agents come, so its pane is the signal that a row a + // parent started a moment ago is drawn. + await session.waitForPane( + (value) => agentRows(value).some((row) => row.name === name), + Math.max(1, deadline - Date.now()), + ); + const pane = await session.capturePaneEscapes(); + const rows = agentRows(pane); + const from = rows.findIndex((row) => row.selected); + const to = rows.findIndex((row) => row.name === name); + if (from < 0 || to < 0) throw new Error(`no ${name} row in the agent list:\n${pane}`); + for (let step = 0; step < Math.abs(to - from); step += 1) await session.sendKeys(to > from ? "Down" : "Up"); + await session.sendKeys("Enter"); + await session.waitForPane((value) => !value.includes(LIST_HINT), 10_000); +} + +// Opens the agent list and selects the row `name` that follows `anchor`, for a +// host whose instances each have a subagent of the same name. +async function showAgentAfter(session: TmuxSession, anchor: string, name: string) { + await session.sendKeys("C-x"); + await session.waitForText(LIST_HINT, 10_000); + const rows = agentRows(await session.capturePaneEscapes()); + const from = rows.findIndex((row) => row.selected); + const under = rows.findIndex((row) => row.name === anchor); + const to = under < 0 ? -1 : rows.findIndex((row, index) => index > under && row.name === name); + if (to < 0) throw new Error(`no ${name} row after ${anchor}`); + for (let step = 0; step < Math.abs(to - from); step += 1) await session.sendKeys(to > from ? "Down" : "Up"); + await session.sendKeys("Enter"); + await session.waitForPane((value) => !value.includes(LIST_HINT), 10_000); +} + +// The person types the task on the subagent's own screen, so its turn is theirs +// and its approval is answered there. +async function typeChildTask(session: TmuxSession, agent: string, ready: string, task: string) { + await showNamedAgent(session, agent); + await session.waitForPane((pane) => pane.includes(ready), 30_000); + await session.sendText(task); +} + async function switchAgent(session: TmuxSession, target: "next" | "previous" | number) { await session.sendKeys("C-x"); await session.waitForText(LIST_HINT, 10_000); @@ -432,7 +478,11 @@ function held(): Gate { // - TYPED: main starts giver, task 1, and waits for `gates.later`, then ends // its turn. The test types the next prompt, which names the work, while that // turn runs, so fx takes it into the turn. -function sameTurn(base: (body: string) => Response, gates: { later?: Gate; child?: Gate; childTask?: string }) { +function sameTurn(base: (body: string) => Response, gates: { later?: Gate; child?: Gate; childTask?: string; boss?: Gate; typed?: boolean }) { + // A typed harness answers the ready token, so its fake must be typed too. + if (gates.typed && (base as { typed_child?: boolean }).typed_child !== true) { + throw new Error("sameTurn: typed needs grantRuns(…, true)"); + } const give = (agent: string, profile: string, message: string, id: string) => ({ type: "tool-call", toolCallId: id, toolName: "subagent", input: { request: { action: "message", agent, profile, message } } }); const steps = (...calls: object[]) => fakeGatewaySse([...calls, { type: "finish", finishReason: { unified: "tool-calls", raw: "tool-calls" } }]); @@ -454,16 +504,22 @@ function sameTurn(base: (body: string) => Response, gates: { later?: Gate; child }; return async (body: string): Promise => { const joined = userTexts(body).join("\n"); + const latest = userTexts(body).at(-1) ?? ""; const task = joined.match(/GRANT_TASK_(\d+) /)?.[1]; if (task) { if (gates.child && task === gates.childTask && resultsSince(body, /GRANT_TASK_\d+ /) === 0) await gates.child.promise; return base(body); } - const boss = joined.match(/GRANT_BOSS_(\d+) RUN\[(.*?)\]/); + const boss = latest.match(/GRANT_BOSS_(\d+) RUN\[(.*?)\]/); if (boss) { const [, turn, what] = boss as unknown as [string, string, string]; const done = resultsSince(body, /GRANT_BOSS_\d+ /); - if (done === 0) return shellRun(`boss_${turn}`, what); + if (done === 0) { + // Hold the lead's first request until the person is back on main, so + // its prompt is lent there and no prompt takes their keys. + await gates.boss?.promise; + return shellRun(`boss_${turn}`, what); + } if (done === 1) return steps(give("inner", "runner", `GRANT_TASK_${turn} RUN[${what}]`, `inner_${turn}`)); return text(`boss_done_${turn}`, `GRANT_BOSS_DONE_${turn}`); } @@ -487,20 +543,20 @@ function sameTurn(base: (body: string) => Response, gates: { later?: Gate; child } return text(`done_${turn}`, `GRANT_DONE_${turn}`); case "LATER": - if (results === 0) return steps(give(name!, "runner", `GRANT_TASK_${turn} ${taskKind}[${what}]`, `start_${turn}`)); + if (results === 0) return steps(give(name!, "runner", gates.typed ? `GRANT_READY_${turn}` : `GRANT_TASK_${turn} ${taskKind}[${what}]`, `start_${turn}`)); if (results === 1) await gates.later!.promise; return work(turn, kind!, what!, results - 1, typed.text.match(/THEN\[(.*?)\]/)?.[1]); case "BEFORE": - if (results === 0) return steps(give(name!, "runner", `GRANT_TASK_2 ${taskKind}[${what}]`, `start_${turn}`)); + if (results === 0) return steps(give(name!, "runner", gates.typed ? `GRANT_READY_${turn}` : `GRANT_TASK_2 ${taskKind}[${what}]`, `start_${turn}`)); return work(turn, kind!, what!, results - 1); case "PAIR": - if (results === 0) return steps(give("alpha", "runner", `GRANT_TASK_1 RUN[${what}]`, `alpha_${turn}`), give("beta", "runner", `GRANT_TASK_2 RUN[${what}]`, `beta_${turn}`)); + if (results === 0) return steps(give("alpha", "runner", gates.typed ? `GRANT_READY_1` : `GRANT_TASK_1 RUN[${what}]`, `alpha_${turn}`), give("beta", "runner", `GRANT_TASK_2 RUN[${what}]`, `beta_${turn}`)); return text(`done_${turn}`, `GRANT_DONE_${turn}`); case "BOSS": - if (results === 0) return steps(give(name!, "lead", `GRANT_BOSS_${turn} RUN[${what}]`, `start_${turn}`)); + if (results === 0) return steps(give(name!, "lead", gates.typed ? `GRANT_READY_${turn}` : `GRANT_BOSS_${turn} RUN[${what}]`, `start_${turn}`)); return text(`sent_${turn}`, `GRANT_SENT_${turn}`); default: - if (results === 0) return steps(give("giver", "runner", `GRANT_TASK_1 RUN[${what}]`, `giver_${turn}`)); + if (results === 0) return steps(give("giver", "runner", gates.typed ? `GRANT_READY_${turn}` : `GRANT_TASK_1 RUN[${what}]`, `giver_${turn}`)); if (results === 1) await gates.later!.promise; return text(`sent_${turn}`, `GRANT_SENT_${turn}`); } @@ -601,12 +657,21 @@ async function resetSessionGrants(session: TmuxSession): Promise<{ before: strin // and `SUB[name]` makes main start that subagent with the task GRANT_TASK_ // instead of doing it itself. `finished` is filled with each subagent turn's // number when its report is sent. -function grantRuns(finished: Set) { +function grantRuns(finished: Set, typed_child = false) { const shell = shellRun; - return (body: string): Response => { + const run = (body: string): Response => { const results = resultsSince(body, /GRANT_TASK_\d+ /); const texts = userTexts(body); - const task = texts.join("\n").match(/GRANT_TASK_(\d+) (RUN|FILE|MCP)\[(.*?)\]/); + // A typed child's first turn only makes it ready: the person then types the + // task on that subagent's own screen, so its approval stays with them. + // Each turn is answered by the text the person just sent, so a child with + // several typed tasks answers the newest one. + const latest = texts.at(-1) ?? ""; + if (typed_child && /GRANT_READY_\d+/.test(latest)) { + const ready = latest.match(/GRANT_READY_(\d+)/); + if (ready) return text(`child_ready_${ready[1]}`, `GRANT_CHILD_READY_${ready[1]}`); + } + const task = latest.match(/GRANT_TASK_(\d+) (RUN|FILE|MCP)\[(.*?)\]/); if (task) { const [, turn, kind, what] = task as unknown as [string, string, string, string]; if (kind === "MCP") { @@ -620,11 +685,11 @@ function grantRuns(finished: Set) { return text(`sub_done_${turn}`, `GRANT_CHILD_DONE_${turn}`); } // A lead starts its own subagent once, and its turn ends there. - const nest = texts.join("\n").match(/GRANT_NEST_(\d+) RUN\[(.*?)\]/); + const nest = latest.match(/GRANT_NEST_(\d+) RUN\[(.*?)\]/); if (nest) { const [, turn, what] = nest as unknown as [string, string, string]; if (body.includes(`nest_${turn}`)) return text(`nest_done_${turn}`, `GRANT_NEST_SENT_${turn}`); - return call(`nest_${turn}`, "subagent", { request: { action: "message", agent: "inner", profile: "runner", message: `GRANT_TASK_${turn} RUN[${what}]` } }); + return call(`nest_${turn}`, "subagent", { request: { action: "message", agent: "inner", profile: "runner", message: typed_child ? `GRANT_READY_${turn}` : `GRANT_TASK_${turn} RUN[${what}]` } }); } const typed = typedTurn(body); if (!typed) return text("ack", "GRANT_ACK"); @@ -636,15 +701,15 @@ function grantRuns(finished: Set) { const [kind, what] = [work?.[1] ?? "RUN", work?.[2] ?? "true"]; if (lead) { if (typed.results >= 1) return text(`sent_${turn}`, `GRANT_SENT_${turn}`); - return call(`start_${turn}`, "subagent", { request: { action: "message", agent: lead, profile: "lead", message: `GRANT_NEST_${turn} RUN[${what}]` } }); + return call(`start_${turn}`, "subagent", { request: { action: "message", agent: lead, profile: "lead", message: typed_child ? `GRANT_READY_${turn}` : `GRANT_NEST_${turn} RUN[${what}]` } }); } if (again) { if (typed.results >= 1) return text(`sent_${turn}`, `GRANT_SENT_${turn}`); - return call(`start_${turn}`, "subagent", { request: { action: "message", agent: again, message: `GRANT_TASK_${turn} ${kind}[${what}]` } }); + return call(`start_${turn}`, "subagent", { request: { action: "message", agent: again, message: typed_child ? `GRANT_READY_${turn}` : `GRANT_TASK_${turn} ${kind}[${what}]` } }); } if (sub) { if (typed.results >= 1) return text(`sent_${turn}`, `GRANT_SENT_${turn}`); - return call(`start_${turn}`, "subagent", { request: { action: "message", agent: sub, profile: "runner", message: `GRANT_TASK_${turn} ${kind}[${what}]` } }); + return call(`start_${turn}`, "subagent", { request: { action: "message", agent: sub, profile: "runner", message: typed_child ? `GRANT_READY_${turn}` : `GRANT_TASK_${turn} ${kind}[${what}]` } }); } if (kind === "MCP") { if (typed.results === 0) return call(`open_${turn}`, "toolbox", { open: "mcp_fixture_echo" }); @@ -655,6 +720,8 @@ function grantRuns(finished: Set) { if (kind === "RUN") return shell(`run_${turn}`, what); return call(`write_${turn}`, "write_file", { path: `${what}.txt`, content: "GRANT\n" }); }; + run.typed_child = typed_child; + return run; } // Waits until `done()` holds, and fails with `what` when it does not. @@ -1039,19 +1106,23 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a subagent's always approval of a command is kept: it is not asked again, nor is its sibling or main", async () => { const command = "echo RAN >> grant.log"; - await withHost(grantRuns(new Set()), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(grantRuns(new Set(), true), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "grant.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 SUB[alpha] RUN[${command}]`); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); // Its second run comes at once after the first and is not asked. await waitUntil("the subagent's two runs", () => countLines(log) === 2, 30_000, session, () => `workspace: ${readdirSync(workspace).join(" ")}; log: ${existsSync(log) ? readFileSync(log, "utf8") : "none"}`); // A sibling runs the same command with no prompt. + await showNamedAgent(session, "main"); await session.waitForComposer(15_000); await session.sendText(`GRANT_2 SUB[beta] RUN[${command}]`); + await typeChildTask(session, "beta", "GRANT_CHILD_READY_2", `GRANT_TASK_2 RUN[${command}]`); + await showNamedAgent(session, "main"); await waitUntil("the sibling's two runs", () => countLines(log) === 4, 30_000, session); // So does main, which is in ask mode itself. @@ -1072,10 +1143,11 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { test( "a subagent's always approval of a file change is kept: it is not asked again, nor is its sibling or main", async () => { - await withHost(grantRuns(new Set()), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { +await withHost(grantRuns(new Set(), true), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Writes files", tools: ["write_file"], permission_mode: "ask" }); await session.waitForComposer(15_000); await session.sendText("GRANT_1 SUB[alpha] FILE[grant-a]"); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", "GRANT_TASK_1 FILE[grant-a]"); await waitShows(session, "alpha's file prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes("Apply this change?")); await session.sendKeys("2"); // Its second write comes at once after the first and is not asked. @@ -1083,10 +1155,13 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { expect(existsSync(join(workspace, "grant-a-0.txt"))).toBe(true); await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); await session.sendText("GRANT_2 SUB[beta] FILE[grant-b]"); + await typeChildTask(session, "beta", "GRANT_CHILD_READY_2", "GRANT_TASK_2 FILE[grant-b]"); await waitUntil("the sibling's two writes", () => existsSync(join(workspace, "grant-b-1.txt")), 30_000, session); await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); await session.sendText("GRANT_3 FILE[grant-main]"); await session.waitForText("GRANT_DONE_3", 30_000); expect(existsSync(join(workspace, "grant-main.txt"))).toBe(true); @@ -1104,23 +1179,27 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const fixture = join(import.meta.dirname, "fixtures", "mcp-modern-stdio.mjs"); const finished = new Set(); - await withHost(grantRuns(finished), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, session }) => { + await withHost(grantRuns(finished, true), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, session }) => { writeFileSync(join(home, ".fx", "mcp.json"), JSON.stringify({ mcp: { fixture: { type: "local", command: [process.execPath, fixture], enabled: true, environment: { FX_MCP_EXPECT_ELICITATION: "both" } } }, })); writeProfile(home, "runner", { description: "Uses the fixture", tools: ["read_file", "mcp_select_tool"], mcp_servers: ["fixture"], permission_mode: "ask" }); await session.waitForComposer(15_000); await session.sendText("GRANT_1 SUB[alpha] MCP[]"); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", "GRANT_TASK_1 MCP[]"); await session.waitForText("Subagent alpha needs permission", 45_000); await session.sendKeys("2"); // Its second call comes at once after the first and is not asked. await waitUntil("the subagent's two calls", () => finished.has("1"), 45_000, session); await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); await session.sendText("GRANT_2 SUB[beta] MCP[]"); + await typeChildTask(session, "beta", "GRANT_CHILD_READY_2", "GRANT_TASK_2 MCP[]"); await waitUntil("the sibling's two calls", () => finished.has("2"), 45_000, session); await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); await session.sendText("GRANT_3 MCP[]"); await session.waitForText("GRANT_DONE_3", 45_000); }); @@ -1132,20 +1211,30 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a nested subagent's always approval is kept: its parent subagent and main are not asked again", async () => { const command = "echo RAN >> grant.log"; - await withHost(grantRuns(new Set()), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(grantRuns(new Set(), true), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { // `boss` may start subagents; `inner` runs the command. writeProfile(home, "lead", { description: "Starts a subagent and runs a command", tools: ["shell", "subagent"], permission_mode: "ask" }); writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "grant.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 LEAD[boss] RUN[${command}]`); + // Boss's turn is the person's, so boss starts inner from it; inner's + // turn is the person's too, so its approval is answered on its screen. + await typeChildTask(session, "boss", "GRANT_CHILD_READY_1", `GRANT_NEST_1 RUN[${command}]`); + // Inner exists once boss's turn has started it. + await session.waitForPane((pane) => pane.includes("GRANT_NEST_SENT_1"), 30_000); + await typeChildTask(session, "inner", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); await waitShows(session, "inner's command prompt", (pane) => pane.includes("Subagent inner needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("the nested subagent's two runs", () => countLines(log) === 2, 30_000, session, () => `workspace: ${readdirSync(workspace).join(" ")}`); // The subagent that started it runs the same command with no prompt. await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); + await session.waitForComposer(15_000); await session.sendText(`GRANT_2 AGAIN[boss] RUN[${command}]`); + await typeChildTask(session, "boss", "GRANT_CHILD_READY_2", `GRANT_TASK_2 RUN[${command}]`); + await showNamedAgent(session, "main"); await waitUntil("the parent subagent's two runs", () => countLines(log) === 4, 30_000, session); // So does main, which is in ask mode itself. @@ -1166,11 +1255,12 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a subagent's always approval stays in its instance: another instance's subagent still asks", async () => { const command = "echo RAN >> grant.log"; - await withHost(grantRuns(new Set()), { instances: 2, env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(grantRuns(new Set(), true), { instances: 2, env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "grant.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 SUB[alpha] RUN[${command}]`); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("the first instance's subagent's two runs", () => countLines(log) === 2, 30_000, session); @@ -1180,6 +1270,9 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { await session.waitForPane((pane) => pane.includes("fx 2/2"), 15_000); await session.waitForComposer(15_000); await session.sendText(`GRANT_2 SUB[alpha] RUN[${command}]`); + await showAgentAfter(session, "fx 2", "alpha"); + await session.waitForPane((pane) => pane.includes("GRANT_CHILD_READY_2"), 30_000); + await session.sendText(`GRANT_TASK_2 RUN[${command}]`); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); expect(countLines(log)).toBe(2); await session.sendKeys("1"); @@ -1197,12 +1290,13 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a subagent's one-time approval is not kept: its next run, and main's, ask again", async () => { const command = "echo RAN >> grant.log"; - await withHost(grantRuns(new Set()), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(grantRuns(new Set(), true), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "grant.log"); const asking = (pane: string, who: string) => pane.includes(who) && pane.includes(COMMAND_APPROVAL_PROMPT); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 SUB[alpha] RUN[${command}]`); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); await waitShows(session, "alpha's command prompt", (pane) => asking(pane, "Subagent alpha needs permission")); await session.sendKeys("1"); // Its second run asks again once the first has run. @@ -1213,6 +1307,7 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { // Main asks too. await session.waitForComposer(15_000); + await showNamedAgent(session, "main"); await session.sendText(`GRANT_2 RUN[${command}]`); await waitShows(session, "main's command prompt", (pane) => asking(pane, "") && !pane.includes("Subagent")); await session.sendKeys("1"); @@ -1230,11 +1325,17 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const command = "echo RAN >> same.log"; const gates = { later: held() }; - await withHost(sameTurn(grantRuns(new Set()), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(new Set(), true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 LATER[alpha] RUN[${command}]`); + // The child's turn is the person's; its first request waits until they + // are back on main, so the prompt is lent there during main's turn. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); + await showNamedAgent(session, "main"); + child.release(); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("the subagent's two runs", () => countLines(log) === 2, 30_000, session); @@ -1251,11 +1352,17 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { const granted = "echo RAN >> same.log"; const other = "echo OTHER >> other.log"; const gates = { later: held() }; - await withHost(sameTurn(grantRuns(new Set()), gates), { env: { FX_PERMISSION_MODE: "auto" } }, async ({ home, workspace, session, classifierRequests }) => { + const child = held(); + await withHost(sameTurn(grantRuns(new Set(), true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "auto" } }, async ({ home, workspace, session, classifierRequests }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 LATER[alpha] RUN[${granted}] THEN[${other}]`); + // The child's turn is the person's; the visit happens before the + // subject event, and its request waits until the person is back. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${granted}]`); + await showNamedAgent(session, "main"); + child.release(); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("the subagent's two runs", () => countLines(log) === 2, 30_000, session); @@ -1279,11 +1386,17 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const command = "echo RAN >> same.log"; const gates = { later: held() }; - await withHost(sameTurn(grantRuns(new Set()), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(new Set(), true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); - await session.sendText(`GRANT_1 LATER[alpha] RUN[${command}]`); + await session.sendText(`GRANT_1 LATER[alpha] RUN[${command}]`) + // The child's turn is the person's; its first request waits until + // they are back on main, so the prompt is lent there. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); + await showNamedAgent(session, "main"); + child.release();; await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("the subagent's two runs", () => countLines(log) === 2, 30_000, session); @@ -1332,10 +1445,16 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a subagent's always approval of a file change reaches main's running turn: main writes later in that turn with no prompt", async () => { const gates = { later: held() }; - await withHost(sameTurn(grantRuns(new Set()), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(new Set(), true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Writes files", tools: ["write_file"], permission_mode: "ask" }); await session.waitForComposer(15_000); await session.sendText("GRANT_1 LATER[alpha] FILE[same-a]"); + // The child's turn is the person's; its first request waits until + // they are back on main, so the prompt is lent there. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 FILE[same-a]`); + await showNamedAgent(session, "main"); + child.release(); await waitShows(session, "alpha's file prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes("Apply this change?")); await session.sendKeys("2"); await waitUntil("the subagent's two writes", () => existsSync(join(workspace, "same-a-1.txt")), 30_000, session); @@ -1352,13 +1471,19 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { const fixture = join(import.meta.dirname, "fixtures", "mcp-modern-stdio.mjs"); const finished = new Set(); const gates = { later: held() }; - await withHost(sameTurn(grantRuns(finished), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(finished, true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, session }) => { writeFileSync(join(home, ".fx", "mcp.json"), JSON.stringify({ mcp: { fixture: { type: "local", command: [process.execPath, fixture], enabled: true, environment: { FX_MCP_EXPECT_ELICITATION: "both" } } }, })); writeProfile(home, "runner", { description: "Uses the fixture", tools: ["read_file", "mcp_select_tool"], mcp_servers: ["fixture"], permission_mode: "ask" }); await session.waitForComposer(15_000); await session.sendText("GRANT_1 LATER[alpha] MCP[]"); + // The child's turn is the person's; its first request waits until + // they are back on main, so the prompt is lent there. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 MCP[]`); + await showNamedAgent(session, "main"); + child.release(); await session.waitForText("Subagent alpha needs permission", 45_000); await session.sendKeys("2"); await waitUntil("the subagent's two calls", () => finished.has("1"), 45_000, session); @@ -1373,12 +1498,16 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const finished = new Set(); const gates = { later: held() }; - await withHost(sameTurn(grantRuns(finished), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(finished, true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { useMcpFixture(home); // Main's commands do not wait: the call is made as soon as they start. writeFileSync(join(workspace, "go"), ""); await session.waitForComposer(15_000); await session.sendText("GRANT_1 LATER[alpha] MCPCALL[]"); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 MCP[]`); + await showNamedAgent(session, "main"); + child.release(); await session.waitForText("Subagent alpha needs permission", 45_000); await session.sendKeys("2"); await waitUntil("the subagent's two calls", () => finished.has("1"), 45_000, session); @@ -1400,10 +1529,14 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const finished = new Set(); const gates = { child: held(), childTask: "2" }; - await withHost(sameTurn(grantRuns(finished), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(sameTurn(grantRuns(finished, true), { ...gates, typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { useMcpFixture(home); await session.waitForComposer(15_000); await session.sendText("GRANT_1 BEFORE[alpha] MCPCALL[]"); + // The child's turn is the person's; its first request waits until + // they are back on main, so the prompt is lent there. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_2 MCP[]`); + await showNamedAgent(session, "main"); // Main's first command asks for itself, then runs and waits for `go`. await allowOnce(session, await waitShows(session, "main's command prompt", (pane) => pane.includes(COMMAND_APPROVAL_PROMPT) && !pane.includes("Subagent"), 45_000)); // The subagent's approval comes while that command runs. @@ -1430,10 +1563,14 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { async () => { const finished = new Set(); const gates = { later: held() }; - await withHost(sameTurn(grantRuns(finished), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const child = held(); + await withHost(sameTurn(grantRuns(finished, true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { useMcpFixture(home); await session.waitForComposer(15_000); await session.sendText("GRANT_1 LATER[alpha] MCPCALL[]"); + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 MCP[]`); + await showNamedAgent(session, "main"); + child.release(); await session.waitForText("Subagent alpha needs permission", 45_000); await session.sendKeys("2"); await waitUntil("the subagent's two calls", () => finished.has("1"), 45_000, session); @@ -1487,12 +1624,15 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { const command = "echo RAN >> same.log"; const finished = new Set(); const gates = { child: held(), childTask: "2" }; - await withHost(sameTurn(grantRuns(finished), gates), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + await withHost(sameTurn(grantRuns(finished, true), { ...gates, typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); // Alpha asks first; beta is running, with its first request held. await session.sendText(`GRANT_1 PAIR RUN[${command}]`); + // Beta is main-started and stays running across the grant, held at its + // first request; alpha's turn is the person's, answered on its screen. + await typeChildTask(session, "alpha", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); await waitShows(session, "alpha's command prompt", (pane) => pane.includes("Subagent alpha needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("alpha's two runs", () => finished.has("1"), 30_000, session); @@ -1509,12 +1649,18 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { "a lead subagent's always approval reaches the subagent it starts: inner is not asked", async () => { const command = "echo RAN >> same.log"; - await withHost(sameTurn(grantRuns(new Set()), {}), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { + const backOnMain = held(); + await withHost(sameTurn(grantRuns(new Set(), true), { boss: backOnMain, typed: true }), { env: { FX_PERMISSION_MODE: "ask" } }, async ({ home, workspace, session }) => { writeProfile(home, "lead", { description: "Runs a command and starts a subagent", tools: ["shell", "subagent"], permission_mode: "ask" }); writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 BOSS[boss] RUN[${command}]`); + // The lead's turn is the person's, typed on its own screen; its request + // then waits until the person is back on main. + await typeChildTask(session, "boss", "GRANT_CHILD_READY_1", `GRANT_BOSS_1 RUN[${command}]`); + await showNamedAgent(session, "main"); + backOnMain.release(); await waitShows(session, "boss's command prompt", (pane) => pane.includes("Subagent boss needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); // Boss runs it once, then inner runs it twice, with no prompt. @@ -1530,12 +1676,18 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { const command = "echo RAN >> same.log"; const trace = join(tmpdir(), `fx-same-turn-${process.pid}-${Date.now()}.log`); const gates = { later: held() }; + const child = held(); try { - await withHost(sameTurn(grantRuns(new Set()), gates), { env: { FX_PERMISSION_MODE: "ask", FX_TRACE_LOG: trace } }, async ({ home, workspace, session }) => { + await withHost(sameTurn(grantRuns(new Set(), true), { later: gates.later, child, childTask: "1", typed: true }), { env: { FX_PERMISSION_MODE: "ask", FX_TRACE_LOG: trace } }, async ({ home, workspace, session }) => { writeProfile(home, "runner", { description: "Runs one thing", tools: ["shell"], permission_mode: "ask" }); const log = join(workspace, "same.log"); await session.waitForComposer(15_000); await session.sendText(`GRANT_1 TYPED RUN[${command}]`); + // The child's turn is the person's; the visit happens before the + // subject event, and its request waits until the person is back. + await typeChildTask(session, "giver", "GRANT_CHILD_READY_1", `GRANT_TASK_1 RUN[${command}]`); + await showNamedAgent(session, "main"); + child.release(); await waitShows(session, "giver's command prompt", (pane) => pane.includes("Subagent giver needs permission") && pane.includes(COMMAND_APPROVAL_PROMPT)); await session.sendKeys("2"); await waitUntil("giver's two runs", () => countLines(log) === 2, 30_000, session); @@ -2156,18 +2308,80 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { TIMEOUT, ); + test( + "a launched instance's subagent asks that instance's agent, not the person or main", + async () => { + // Every request: the text the turn's agent was last given, and whether the + // body carries the note an instance's agent gets when its child asks. + const requests: Array<{ note: boolean; first: boolean; second: boolean }> = []; + await withHost((body) => { + const latest = userTexts(body).at(-1) ?? ""; + requests.push({ + note: body.includes("I wait for your approval to run"), + first: body.includes("RULE_A_FIRST"), + second: body.includes("RULE_A_USER"), + }); + if (latest.includes("I wait for your approval to run")) { + return call("rule_a_approve", "subagent", { request: { action: "approve", agent: "writer" } }); + } + if (latest.includes("RULE_A_USER")) { + if (answered(body)) return text("rule_a_done", "RULE_A_DONE"); + return call("rule_a_sub", "subagent", { request: { action: "message", agent: "writer", profile: "writer", message: "RULE_A_WRITE" } }); + } + if (latest.includes("RULE_A_WRITE")) { + if (answered(body)) return text("rule_a_child_done", "RULE_A_CHILD_DONE"); + return call("rule_a_write", "write_file", { path: "rule-a.txt", content: "RULE_A\n" }); + } + return answerByLetter(body); + }, { instances: 2 }, async ({ home, workspace, session }) => { + writeProfile(home, "writer", { description: "Writes one file", tools: ["read_file", "write_file"], permission_mode: "ask" }); + await session.waitForPane((pane) => pane.includes("fx 1/2"), 15_000); + // Main's conversation gets its own marker, so each request can be + // classified by whose conversation it belongs to. + await session.waitForComposer(15_000); + await session.sendText("RULE_A_FIRST hello"); + await session.waitForComposer(30_000); + await switchAgent(session, "next"); + await session.waitForPane((pane) => pane.includes("fx 2/2"), 15_000); + await session.waitForComposer(15_000); + // fx 2's agent starts the child with its real task, so the request is + // parent-routed: its agent answers, and no screen shows it. + await session.sendText("RULE_A_USER write the file"); + await waitUntil("the child's write", () => existsSync(join(workspace, "rule-a.txt")), 30_000, session); + expect(readFileSync(join(workspace, "rule-a.txt"), "utf8")).toBe("RULE_A\n"); + const second = await session.capturePane(); + expect(second).not.toContain("needs permission"); + // The first instance never sees the request either. + await switchAgent(session, 1); + const first = await session.capturePane(); + expect(first).toContain("fx 1/2"); + expect(first).not.toContain("needs permission"); + expect(first).not.toContain("Subagent writer needs permission"); + // The note went to the instance's agent: some request carries it, and the + // text that request's agent was last given is not one of main's turns. + const notes = requests.filter((entry) => entry.note); + expect(notes.length).toBeGreaterThan(0); + // The note reaches the launched instance's agent, and never main. + expect(notes.every((entry) => entry.second && !entry.first)).toBe(true); + expect(requests.some((entry) => entry.first && entry.note)).toBe(false); + }); + }, + TIMEOUT, + ); + test( "a launched instance's subagent asks on that instance's screen, not the first's", async () => { await withHost((body) => { const texts = userTexts(body).join("\n"); + if (texts.includes("TREE_READY") && !texts.includes("TREE_LEND_TASK")) return text("lend_ready", "TREE_CHILD_READY"); if (texts.includes("TREE_LEND_TASK")) { if (answered(body)) return text("lend_child_done", "TREE_LEND_CHILD_DONE"); return call("lend_write", "write_file", { path: "lent.txt", content: "TREE_LENT\n" }); } if (texts.includes("TREE_LEND_USER")) { if (answered(body)) return text("lend_main_done", "TREE_LEND_MAIN_DONE"); - return call("lend_sub", "subagent", { request: { action: "message", agent: "writer", profile: "writer", message: "TREE_LEND_TASK" } }); + return call("lend_sub", "subagent", { request: { action: "message", agent: "writer", profile: "writer", message: "TREE_READY" } }); } return answerByLetter(body); }, { instances: 2 }, async ({ home, workspace, session }) => { @@ -2177,6 +2391,12 @@ describe.skipIf(!tmuxAvailable())("TUI host instances", () => { await session.waitForPane((pane) => pane.includes("fx 2/2"), 15_000); await session.waitForComposer(15_000); await session.sendText("TREE_LEND_USER write the file"); + // The writer's turn is the person's, typed on its own screen; its + // approval is then lent to the launched instance's screen. + await showAgentAfter(session, "fx 2", "writer"); + await session.waitForPane((pane) => pane.includes("TREE_CHILD_READY"), 30_000); + await session.sendText("TREE_LEND_TASK write the file"); + await showNamedAgent(session, "fx 2"); // fx 2's own screen, shown by its conversation, holds its subagent's // approval, which replaces the footer while it waits. await session.waitForPane((pane) => pane.includes("TREE_LEND_USER") && pane.includes("Subagent writer needs permission"), 30_000); diff --git a/tests/e2e/tui-host-switch.test.ts b/tests/e2e/tui-host-switch.test.ts index 62948b8d0b..d701d0de3c 100644 --- a/tests/e2e/tui-host-switch.test.ts +++ b/tests/e2e/tui-host-switch.test.ts @@ -68,6 +68,17 @@ async function showAgent(session: TmuxSession, agent: string) { await session.waitForPane((pane) => !pane.includes(LIST_HINT), 10_000); } +// The person opens the subagent's own screen and types a task there, so its turn +// is one the person started. A turn main started is answered by main and its +// request is never lent; a turn the person typed still lends its approval to +// main's screen, which is the path these tests keep +// (`tests/tla/subagent/TuiParentApproval.tla` NoStaleLent). +async function typeTaskOnSubagent(session: TmuxSession, agent: string, ready: string, task: string) { + await showAgent(session, agent); + await session.waitForPane((pane) => pane.includes(ready), 30_000); + await session.sendText(task); +} + // Waits until the open agent list highlights `agent`'s row, and returns the // pane then. async function waitForSelectedRow(session: TmuxSession, agent: string, timeoutMs = 10_000): Promise { @@ -225,13 +236,13 @@ function outOfCredits(): Response { } // One model step that calls the subagent tool once per message, in order. -function messageSteps(calls: Array<{ id: string; agent: string; message: string; profile?: string }>): Response { +function messageSteps(calls: Array<{ id: string; agent: string; message: string; profile?: string; report?: string }>): Response { return fakeGatewaySse([ ...calls.map((call) => ({ type: "tool-call", toolCallId: call.id, toolName: "subagent", - input: { request: { action: "message", agent: call.agent, message: call.message, ...(call.profile ? { profile: call.profile } : {}) } }, + input: { request: { action: "message", agent: call.agent, message: call.message, ...(call.profile ? { profile: call.profile } : {}), ...(call.report ? { report: call.report } : {}) } }, })), { type: "finish", finishReason: { unified: "tool-calls", raw: "tool-calls" } }, ]); @@ -340,18 +351,23 @@ async function reportBehindAnsweredPrompt(prompt: "approval" | "question") { const mainTurnEnded = held(); const reports: string[] = []; let writerCalls = 0; + let writerDone = false; let tracePath = ""; const env: Record = {}; const promptText = prompt === "approval" ? "Subagent writer needs permission" : "SWITCH_QUESTION pick one"; - await withFx((body) => { + await withFx(async (body) => { const latest = latestUserText(body); if (latest.startsWith(REPORT_HEADER)) { reports.push(body); return text(`main_report_${reports.length}`, `SWITCH_MAIN_REPORT_${reports.length}`); } + if (latest.includes("SWITCH_READY_TASK")) return text("child_ready", "SWITCH_WRITER_READY"); if (latest.includes("SWITCH_WRITE_TASK")) { writerCalls += 1; - if (writerCalls > 1) return text("child_done", "SWITCH_WRITER_DONE"); + if (writerCalls > 1) { + writerDone = true; + return text("child_done", "SWITCH_WRITER_DONE"); + } return prompt === "approval" ? toolCall("child_write", "write_file", { path: "switch-child.txt", content: "SWITCH_WROTE\n" }) : toolCall("child_ask", "ask_user_question", { @@ -361,13 +377,17 @@ async function reportBehindAnsweredPrompt(prompt: "approval" | "question") { if (latest.includes("SWITCH_HELPER_TASK")) return mainTurnEnded.promise.then(() => text("helper_done", "SWITCH_HELPER_DONE")); if (!body.includes('"main_w"')) { return messageSteps([ - { id: "main_w", agent: "writer", message: "SWITCH_WRITE_TASK", ...(prompt === "approval" ? { profile: "writer" } : {}) }, + { id: "main_w", agent: "writer", message: prompt === "approval" ? "SWITCH_READY_TASK" : "SWITCH_WRITE_TASK", ...(prompt === "approval" ? { profile: "writer", report: "never" } : {}) }, { id: "main_h", agent: "helper", message: "SWITCH_HELPER_TASK" }, ]); } return promptShown.promise.then(() => text("main_one", "SWITCH_MAIN_ONE")); }, async (session) => { await session.sendText("SWITCH_USER"); + if (prompt === "approval") { + await typeTaskOnSubagent(session, "writer", "SWITCH_WRITER_READY", "SWITCH_WRITE_TASK"); + await showAgent(session, "main"); + } await session.waitForText(promptText, 30_000); promptShown.release(); await until("main's first turn to end", () => traceHas(tracePath, "event=processing_finished turn_id=1 ")); @@ -388,7 +408,7 @@ async function reportBehindAnsweredPrompt(prompt: "approval" | "question") { mkdirSync(folder, { recursive: true }); writeFileSync(join(folder, "profile.json"), JSON.stringify({ description: "Writes one file", - tools: ["read_file", "write_file"], + tools: ["read_file", "write_file", "glob_files"], permission_mode: "ask", })); }, false, env); @@ -497,27 +517,37 @@ async function withFx( // the loop committed them. async function reportWhilePromptStaysOpen(prompt: "approval" | "question" | "none", reportDelayMs = 0, secondReport = false) { const promptShown = held(); + const turnStarted = held(); const writerReleased = held(); const mainTurnEnded = held(); const reportTurnEnded = held(); const reports: string[] = []; let writerCalls = 0; + let writerDone = false; let tracePath = ""; const env: Record = {}; const promptText = prompt === "approval" ? "Subagent writer needs permission" : "SWITCH_QUESTION pick one"; - await withFx((body) => { + await withFx(async (body) => { const latest = latestUserText(body); if (latest.startsWith(REPORT_HEADER)) { reports.push(body); return text(`main_report_${reports.length}`, `SWITCH_MAIN_REPORT_${reports.length}`); } + if (latest.includes("SWITCH_READY_TASK")) return text("child_ready", "SWITCH_WRITER_READY"); if (latest.includes("SWITCH_WRITE_TASK")) { writerCalls += 1; - if (writerCalls > 1) return text("child_done", "SWITCH_WRITER_DONE"); + if (writerCalls > 1) { + writerDone = true; + return text("child_done", "SWITCH_WRITER_DONE"); + } if (prompt === "none") return writerReleased.promise.then(() => text("child_done", "SWITCH_WRITER_DONE")); - return prompt === "approval" - ? toolCall("child_write", "write_file", { path: "switch-child.txt", content: "SWITCH_WROTE\n" }) - : toolCall("child_ask", "ask_user_question", { + if (prompt === "approval") { + // The request waits for the turn under test, so the prompt is up while + // main's turn runs, as it was before Part 2. + await turnStarted.promise; + return toolCall("child_write", "write_file", { path: "switch-child.txt", content: "SWITCH_WROTE\n" }); + } + return toolCall("child_ask", "ask_user_question", { questions: [{ question: "SWITCH_QUESTION pick one", options: [{ label: "SWITCH_A" }, { label: "SWITCH_B" }] }], }); } @@ -528,20 +558,51 @@ async function reportWhilePromptStaysOpen(prompt: "approval" | "question" | "non return reportTurnEnded.promise.then(() => Bun.sleep(reportDelayMs)).then(() => text("scout_done", "SWITCH_SCOUT_DONE")); } if (!body.includes('"main_w"')) { + // For an approval the first turn only starts the writer and ends with its + // own marker, so no screen switch happens during the turn under test. + if (prompt === "approval") { + return messageSteps([ + { id: "main_w", agent: "writer", message: "SWITCH_READY_TASK", profile: "writer", report: "never" }, + ]); + } return messageSteps([ - { id: "main_w", agent: "writer", message: "SWITCH_WRITE_TASK", ...(prompt === "approval" ? { profile: "writer" } : {}) }, + { id: "main_w", agent: "writer", message: "SWITCH_WRITE_TASK" }, { id: "main_h", agent: "helper", message: "SWITCH_HELPER_TASK" }, ...(secondReport ? [{ id: "main_s", agent: "scout", message: "SWITCH_SCOUT_TASK" }] : []), ]); } + if (prompt === "approval") { + if (!latest.includes("SWITCH_TURN")) return text("main_ready", "SWITCH_MAIN_READY"); + if (!body.includes('"main_h"')) { + turnStarted.release(); + return messageSteps([ + { id: "main_h", agent: "helper", message: "SWITCH_HELPER_TASK" }, + ...(secondReport ? [{ id: "main_s", agent: "scout", message: "SWITCH_SCOUT_TASK" }] : []), + ]); + } + } return promptShown.promise.then(() => text("main_one", "SWITCH_MAIN_ONE")); - }, async (session, { home }) => { + }, async (session, { home, workspace }) => { const trace = () => (existsSync(tracePath) ? readFileSync(tracePath, "utf8") : ""); await session.sendText("SWITCH_USER"); - if (prompt === "none") await until("the writer's first request", () => writerCalls >= 1); + if (prompt === "approval") { + // The first turn ends first; the person types on the writer's screen and + // comes back; their second prompt starts the turn the report waits on. + await session.waitForText("SWITCH_MAIN_READY", 30_000); + // The write request waits for the turn under test, so the person can get + // back to main and start it before any prompt takes their keys. + await typeTaskOnSubagent(session, "writer", "SWITCH_WRITER_READY", "SWITCH_WRITE_TASK"); + await showAgent(session, "main"); + await session.waitForComposer(15_000); + await session.sendText("SWITCH_USER SWITCH_TURN"); + await session.waitForText(promptText, 30_000); + } else if (prompt === "none") await until("the writer's first request", () => writerCalls >= 1); else await session.waitForText(promptText, 30_000); promptShown.release(); - await until("main's first turn to end", () => traceHas(tracePath, "event=processing_finished turn_id=1 ")); + // For an approval the turn under test is main's second, the first having + // only started the writer. + const turnId = prompt === "approval" ? 2 : 1; + await until("main's turn under test to end", () => traceHas(tracePath, `event=processing_finished turn_id=${turnId} `)); mainTurnEnded.release(); await until("main's request for the helper's report", () => reports.length >= 1); @@ -573,7 +634,7 @@ async function reportWhilePromptStaysOpen(prompt: "approval" | "question" | "non const mainWorker = /event=processing_finished turn_id=1 worker=(\w+)/.exec(trace())?.[1]; expect(mainWorker).toBeDefined(); await until("the report's turn to end", () => - trace().split("\n").filter((line) => line.includes("event=processing_finished") && line.includes(`worker=${mainWorker} `)).length >= 2); + trace().split("\n").filter((line) => line.includes("event=processing_finished") && line.includes(`worker=${mainWorker} `)).length >= (prompt === "approval" ? 3 : 2)); reportTurnEnded.release(); await until("main's request for the scout's report", () => reports.length >= 2); // The second report was posted before the loop committed the report's turn, @@ -589,7 +650,15 @@ async function reportWhilePromptStaysOpen(prompt: "approval" | "question" | "non if (prompt === "none") writerReleased.release(); else await session.sendKeys("1"); - const reportTurns = secondReport ? 3 : 2; + if (prompt === "approval") { + // A typed turn owes no report, so the write and the writer's own answer + // stand in for it; the question and out_of_credits variants still cover + // the writer's report after an answered prompt. + const written = join(workspace, "switch-child.txt"); + await until("the writer's write", () => existsSync(written) && readFileSync(written, "utf8") === "SWITCH_WROTE\n"); + await until("the writer's answer", () => writerDone); + } + const reportTurns = prompt === "approval" ? (secondReport ? 2 : 1) : (secondReport ? 3 : 2); await session.waitForText("SWITCH_MAIN_REPORT_1", 30_000); await until("the writer's report turn", () => reports.length >= reportTurns); await session.waitForText(`SWITCH_MAIN_REPORT_${reportTurns}`, 30_000); @@ -2041,7 +2110,8 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { await withFx((body) => { if (!isMainRequest(body)) { childCalls += 1; - if (childCalls === 1) { + if (childCalls === 1) return text("child_ready", "SWITCH_WRITER_READY"); + if (childCalls === 2) { return toolCall("child_write", "write_file", { path: "switch-child.txt", content: "SWITCH_WROTE\n" }); } return text("child_done", "SWITCH_WRITER_DONE"); @@ -2049,12 +2119,17 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { mainCalls += 1; if (mainCalls === 1) { return toolCall("main_sub", "subagent", { - request: { action: "message", agent: "writer", message: "SWITCH_WRITE_TASK", profile: "writer" }, + request: { action: "message", agent: "writer", message: "SWITCH_READY_TASK", profile: "writer" }, }); } return text("main_done", "SWITCH_MAIN_DONE"); }, async (session, { workspace }) => { await session.sendText("SWITCH_USER"); + // The person types the task on the subagent's own screen; the approval is + // then lent to main's screen as it was before Part 2. + await typeTaskOnSubagent(session, "writer", "SWITCH_WRITER_READY", "SWITCH_WRITE_TASK"); + // The lend moves the prompt to main's screen, so it is not on the child's. + await showAgent(session, "main"); await session.waitForText("Subagent writer needs permission", 30_000); // The open list takes the footer from the prompt, which keys can't @@ -2102,6 +2177,57 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { TIMEOUT, ); + test( + "main's stop refuses a subagent's approval request, and its command never runs", + async () => { + let tracePath = ""; + let mainCalls = 0; + let childCalls = 0; + const env: Record = {}; + await withFx((body) => { + if (!isMainRequest(body)) { + childCalls += 1; + if (childCalls === 1) return toolCall("child_shell", "shell", { action: "run", command: "touch stopped.txt" }); + return text("child_done", "SWITCH_WRITER_DONE"); + } + mainCalls += 1; + if (mainCalls === 1) { + return toolCall("main_sub", "subagent", { + request: { action: "message", agent: "writer", message: "SWITCH_RUN_TASK", profile: "writer" }, + }); + } + if (body.includes("I wait for your approval to run") && !body.includes("main_stop")) { + return toolCall("main_stop", "subagent", { action: "stop", agent: "writer" }); + } + const reportTurn = body.includes(REPORT_HEADER); + if (body.includes("main_stop") && !reportTurn) return text("main_stopped", "SWITCH_MAIN_STOPPED"); + return text("main_done", "SWITCH_MAIN_DONE"); + }, async (session, { workspace }) => { + await session.sendText("SWITCH_USER"); + await session.waitForText("SWITCH_MAIN_STOPPED", 60_000); + // fx answered and stays up: it quits from the composer, cleanly. + await session.sendText("/quit"); + expect(await session.waitForSessionEnd(15_000)).toBe(true); + // The refused command never ran. + expect(existsSync(join(workspace, "stopped.txt"))).toBe(false); + // The stop refused the request with its ids and counts in the trace. + expect(readFileSync(tracePath, "utf8")).toMatch(/approval requests refused child=\S+ refused=1 gone=0 ids=\S+/); + }, (home) => { + const folder = join(home, ".fx", "agents", "writer"); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, "profile.json"), JSON.stringify({ + description: "Runs one command", + tools: ["shell"], + permission_mode: "ask", + })); + tracePath = join(home, "fx-trace.log"); + env.FX_TRACE_LOG = tracePath; + env.FX_TRACE_SCOPES = "subagent,mailbox"; + }, false, env); + }, + TIMEOUT, + ); + test( "a subagent's question shows on main's screen, named for it, and is answered there", async () => { @@ -2195,30 +2321,102 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { test( "main's status says a subagent waits for an approval, and not once it is answered", async () => { - const [waiting, answered] = await mainReadsStatus( - toolCall("child_write", "write_file", { path: "switch-wait.txt", content: "SWITCH_WROTE\n" }), - "writer", - "SWITCH_WRITE_TASK", - async (session) => { - await session.waitForText("Subagent writer needs permission", 30_000); - }, - async (session) => { - await session.sendKeys("1"); - }, - (home) => { - const folder = join(home, ".fx", "agents", "writer"); - mkdirSync(folder, { recursive: true }); - writeFileSync(join(folder, "profile.json"), JSON.stringify({ - description: "Writes one file", - tools: ["read_file", "write_file"], - permission_mode: "ask", - })); - }, - ); - expect(waiting).toContain("writer: waiting for an approval"); - expect(waiting).not.toContain("writer: working"); - expect(answered).toContain("writer: idle"); - expect(answered).not.toContain("waiting for"); + const statuses: string[] = []; + const promptShows = held(); + const writeDone = held(); + await withFx(async (body) => { + if (!isMainRequest(body)) { + if (latestUserText(body).includes("SWITCH_WRITE_TASK")) { + if (body.includes('"child_write"')) return text("child_done", "SWITCH_WRITER_DONE"); + return toolCall("child_write", "write_file", { path: "switch-wait.txt", content: "SWITCH_WROTE\n" }); + } + return text("child_ready", "SWITCH_WRITER_READY"); + } + if (!body.includes('"main_sub"')) { + return toolCall("main_sub", "subagent", { + request: { action: "message", agent: "writer", message: "SWITCH_READY_TASK", profile: "writer" }, + }); + } + // The task is typed on the writer's own screen, so its approval is lent + // to main and stays there while main reads `status`. + if (!body.includes('"main_status_1"')) { + await promptShows.promise; + return toolCall("main_status_1", "subagent", { request: { action: "status" } }); + } + if (!body.includes('"main_status_2"')) { + statuses.push(toolResultText(body, "main_status_1")); + await writeDone.promise; + return toolCall("main_status_2", "subagent", { request: { action: "status" } }); + } + if (statuses.length === 1) { + statuses.push(toolResultText(body, "main_status_2")); + return text("main_done", "SWITCH_MAIN_DONE"); + } + return text("main_tail", "SWITCH_MAIN_TAIL"); + }, async (session, { workspace }) => { + await session.sendText("SWITCH_USER"); + await typeTaskOnSubagent(session, "writer", "SWITCH_WRITER_READY", "SWITCH_WRITE_TASK"); + await session.waitForPane((pane) => pane.includes("Subagent writer needs permission"), 30_000); + promptShows.release(); + await until("main's first status", () => statuses.length === 1); + await session.sendKeys("1"); + await until("the write", () => existsSync(join(workspace, "switch-wait.txt"))); + writeDone.release(); + await until("main's second status", () => statuses.length === 2, 60_000); + }, writeSpikeWriter); + expect(statuses[0]).toContain("writer: waiting for an approval"); + expect(statuses[0]).not.toContain("writer: working"); + expect(statuses[1]).toContain("writer: idle"); + expect(statuses[1]).not.toContain("waiting for"); + }, + TIMEOUT, + ); + + test( + "main's status says a subagent waits for an approval main answers, and the footer stays quiet", + async () => { + const statuses: string[] = []; + await withFx((body) => { + if (!isMainRequest(body)) { + if (body.includes('"child_write"')) return text("child_done", "SWITCH_WRITER_DONE"); + return toolCall("child_write", "write_file", { path: "switch-wait2.txt", content: "SWITCH_WROTE\n" }); + } + if (!body.includes('"main_sub"')) { + return toolCall("main_sub", "subagent", { + request: { action: "message", agent: "writer", message: "SWITCH_WRITE_TASK", profile: "writer" }, + }); + } + // The note turn: main reads `status`, then answers its own request. + if (latestUserText(body).includes("I wait for your approval to run")) { + if (!body.includes('"main_status_1"')) { + return toolCall("main_status_1", "subagent", { request: { action: "status" } }); + } + if (!body.includes('"main_approve"')) { + statuses.push(toolResultText(body, "main_status_1")); + return toolCall("main_approve", "subagent", { action: "approve", agent: "writer" }); + } + if (!body.includes('"main_second_done"')) { + return text("main_second_done", "SWITCH_MAIN_SECOND_DONE"); + } + } + if (body.includes(REPORT_HEADER) && !body.includes('"main_status_2"')) { + return toolCall("main_status_2", "subagent", { request: { action: "status" } }); + } + if (statuses.length === 1) { + statuses.push(toolResultText(body, "main_status_2")); + return text("main_done", "SWITCH_MAIN_DONE"); + } + return text("main_tail", "SWITCH_MAIN_TAIL"); + }, async (session) => { + await session.sendText("SWITCH_USER"); + const pane = await session.waitForText("SWITCH_MAIN_DONE", 30_000); + // The person's footer never asks for this request: main answers it. + expect(pane).not.toContain("writer needs approval"); + expect(pane).not.toContain("needs permission"); + }, writeSpikeWriter); + expect(statuses[0]).toContain("writer: waiting for an approval"); + expect(statuses[1]).toContain("writer: idle"); + expect(statuses[1]).not.toContain("waiting for"); }, TIMEOUT, ); @@ -2314,8 +2512,6 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { test( "main's list of subagents says a wait began when the turn started, also once the wait is over, and the next turn's list says working", async () => { - let stage = 0; - let childCalls = 0; const promptShows = held(); const answered = held(); const writerResumes = held(); @@ -2323,81 +2519,137 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { let statusDuring = ""; await withFx(async (body) => { if (!isMainRequest(body)) { - // The helper finishes once the writer's prompt is on screen, and its - // report starts main's second turn while the writer still waits. + // The helper finishes once the writer's prompt is up, and its report + // starts main's turn while the writer still waits. if (body.includes("SWITCH_HELPER_TASK")) { await promptShows.promise; return text("helper_done", "SWITCH_HELPER_DONE"); } - childCalls += 1; - if (childCalls === 1) return toolCall("child_write", "write_file", { path: "switch-row.txt", content: "SWITCH_ROW\n" }); - // After its approval the writer works until the test lets it end. - await writerResumes.promise; - return text("writer_done", "SWITCH_WRITER_DONE"); + if (latestUserText(body).includes("SWITCH_WRITE_TASK")) { + if (body.includes('"child_write"')) { + // After its approval the writer works until the test lets it end. + await writerResumes.promise; + return text("writer_done", "SWITCH_WRITER_DONE"); + } + return toolCall("child_write", "write_file", { path: "switch-row.txt", content: "SWITCH_ROW\n" }); + } + return text("child_ready", "SWITCH_WRITER_READY"); } - stage += 1; - if (stage === 1) { + if (!body.includes('"main_sub"')) { return messageSteps([ - { id: "main_writer", agent: "writer", message: "SWITCH_WRITE_TASK", profile: "writer" }, + { id: "main_sub", agent: "writer", message: "SWITCH_READY_TASK", profile: "writer" }, { id: "main_helper", agent: "helper", message: "SWITCH_HELPER_TASK" }, ]); } - if (stage === 2) return text("main_started", "SWITCH_MAIN_STARTED"); - if (stage === 3) { - // Main's second turn begins with the writer waiting for its approval. + // The turn the ready task's report starts keeps its note, so it ends + // before the person types; the helper's later report starts the turn + // whose note is read here. + if (!body.includes("SWITCH_HELPER_DONE")) { + if (!body.includes(REPORT_HEADER)) return text("main_ready_done", "SWITCH_MAIN_READY"); + return text("main_ready_kept", "SWITCH_MAIN_READY2"); + } + if (!body.includes('"main_status_1"')) { rows.start = teamRow(body, "writer"); await answered.promise; - return toolCall("main_status", "subagent", { request: { action: "status", agent: "writer" } }); + return toolCall("main_status_1", "subagent", { request: { action: "status", agent: "writer" } }); } - if (stage === 4) { + // A text reply has no call id, so the turn it ended is read from its text. + if (!body.includes("SWITCH_MAIN_SECOND_DONE")) { + statusDuring = toolResultText(body, "main_status_1"); rows.later = teamRow(body, "writer"); - statusDuring = toolResultText(body, "main_status"); return text("main_second_done", "SWITCH_MAIN_SECOND_DONE"); } - if (stage === 5) { + if (rows.next === undefined) { rows.next = teamRow(body, "writer"); - return text("main_third_done", "SWITCH_MAIN_THIRD_DONE"); + return text("main_done", "SWITCH_MAIN_DONE"); } - return text("main_reported", "SWITCH_MAIN_REPORTED"); + return text("main_tail", "SWITCH_MAIN_TAIL"); }, async (session) => { await session.sendText("SWITCH_USER"); + // The ready task's report turn ends first: its note is kept, so the row + // must be read from a later turn. + await session.waitForText("SWITCH_MAIN_READY2", 30_000); + await typeTaskOnSubagent(session, "writer", "SWITCH_WRITER_READY", "SWITCH_WRITE_TASK"); + await showAgent(session, "main"); await session.waitForText("Subagent writer needs permission", 30_000); + // Now the helper reports: a fresh turn starts while the writer waits, + // and its note carries the wait. promptShows.release(); - // Main's second turn is under way, held on its first request. - await until("main's second turn", () => stage === 3, 60_000); - // The user answers the approval while that turn runs. + await until("the row of the turn the wait began in", () => rows.start !== undefined, 60_000); await session.sendKeys("1"); - await until("the writer's next request", () => childCalls === 2, 60_000); answered.release(); await until("main's status", () => rows.later !== undefined, 60_000); await session.waitForText("SWITCH_MAIN_SECOND_DONE", 30_000); + // A turn the person typed owes no report, so their next message starts + // main's next turn, and the writer still works while its row is read. await session.waitForComposer(15_000); await session.sendText("SWITCH_USER once more"); - await until("main's third turn", () => rows.next !== undefined, 60_000); + await until("main's next turn", () => rows.next !== undefined, 60_000); writerResumes.release(); - await until("the writer's report", () => stage >= 6, 60_000); - }, (home) => { - const folder = join(home, ".fx", "agents", "writer"); - mkdirSync(folder, { recursive: true }); - writeFileSync(join(folder, "profile.json"), JSON.stringify({ - description: "Writes one file", - tools: ["read_file", "write_file"], - permission_mode: "ask", - })); - }); - // The wait is in the list of the turn it began in, with when it was true. - expect(rows.start).toContain("- writer: waiting for an approval when this turn started."); - // The user answered during that turn: the list still says so, and `status` says working. + }, writeSpikeWriter); + + // A typed turn has no named work, so the row names the last completed one. + expect(rows.start).toContain("- writer: waiting for an approval when this turn started, last work completed. For: SWITCH_READY_TASK"); expect(rows.later).toBe(rows.start); expect(statusDuring).toContain("writer: working"); expect(statusDuring).not.toContain("waiting for"); - // The next turn's list is built again, and has no wait in it. - expect(rows.next).toContain("- writer: working."); + // The typed turn names the last completed work here too. + expect(rows.next).toContain("- writer: working, last work completed. For: SWITCH_READY_TASK"); expect(rows.next).not.toContain("waiting for"); }, TIMEOUT, ); + test( + "main's agent list says a subagent main is answering works, not that it needs the person", + async () => { + const approved = held(); + let noteSeen = false; + let waitingRow = ""; + await withFx(async (body) => { + if (!isMainRequest(body)) { + if (!body.includes('"child_write"')) { + return toolCall("child_write", "write_file", { path: "switch-row2.txt", content: "SWITCH_ROW\n" }); + } + return text("child_done", "SWITCH_WRITER_DONE"); + } + if (!body.includes('"main_sub"')) { + return toolCall("main_sub", "subagent", { + request: { action: "message", agent: "writer", message: "SWITCH_WRITE_TASK", profile: "writer" }, + }); + } + if (body.includes("I wait for your approval to run") && !body.includes('"main_approve"')) { + noteSeen = true; + // Main's team row for the writer, whose turn main started, while + // main answers its request. + waitingRow = teamRow(body, "writer"); + await approved.promise; + return toolCall("main_approve", "subagent", { action: "approve", agent: "writer" }); + } + return text("main_done", "SWITCH_MAIN_DONE"); + }, async (session) => { + await session.sendText("SWITCH_USER"); + await until("main's note turn", () => noteSeen, 60_000); + // While main answers, the list row says the writer is working. + await session.sendKeys("C-x"); + const list = await session.waitForText(LIST_HINT, 10_000); + expect(list).toMatch(/^ {2}\u2514 writer .*working/m); + expect(list).not.toContain("needs approval"); + await session.sendKeys("Escape"); + approved.release(); + await session.waitForText("SWITCH_MAIN_DONE", 30_000); + // And after, it never said the person was needed. + const pane = await session.capturePaneGrid(); + expect(pane).not.toContain("needs approval"); + expect(pane).not.toContain("needs permission"); + }, writeSpikeWriter); + // The registry still says the writer waits for the approval, since main + // started its turn and answers it. + expect(waitingRow).toContain("- writer: waiting for an approval when this turn started."); + }, + TIMEOUT, + ); + test( "main's stop ends a subagent's open question and the turn that asked it", async () => { @@ -2514,35 +2766,39 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { async () => { const gates = { first: held(), second: held() }; const seen = { first: 0, second: 0 }; - const started = { first: false, second: false }; + const started = { both: false }; await withFx(async (body) => { if (!isMainRequest(body)) { - const who: "first" | "second" = userTexts(body).some((t) => t.includes("SWITCH_TASK_SECOND")) ? "second" : "first"; + const who: "first" | "second" = userTexts(body).some((t) => t.includes("SECOND")) ? "second" : "first"; if (body.includes(`"write_${who}"`)) return text(`done_${who}`, `CHILD_DONE_${who.toUpperCase()}`); + // Main gives each subagent a task that ends at once; the write task is + // typed by the person on that subagent's own screen, so its approval is + // the person's and is lent to an instance's screen. + if (!latestUserText(body).includes(`SWITCH_TASK_${who.toUpperCase()}`)) { + return text(`ready_${who}`, `CHILD_READY_${who.toUpperCase()}`); + } seen[who] += 1; await gates[who].promise; return toolCall(`write_${who}`, "write_file", { path: `${who}.txt`, content: `${who}\n` }); } + // A turn the person typed owes no report, so their own message starts the + // turn that reads the writes. + if (latestUserText(body).includes("all answered")) return text("main_saw_first", "SWITCH_MAIN_SAW_FIRST"); if (body.includes("CHILD_DONE_FIRST")) return text("main_saw_first", "SWITCH_MAIN_SAW_FIRST"); if (body.includes("CHILD_DONE_SECOND")) return text("main_saw_second", "SWITCH_MAIN_SAW_SECOND"); - if (latestUserText(body).includes("START_SECOND") && !started.second) { - started.second = true; - return toolCall("main_second", "subagent", { - request: { action: "message", agent: "second", message: "SWITCH_TASK_SECOND write second.txt" }, - }); - } - if (!started.first) { - started.first = true; - return toolCall("main_first", "subagent", { - request: { action: "message", agent: "first", message: "SWITCH_TASK_FIRST write first.txt" }, - }); + if (!started.both) { + started.both = true; + return messageSteps([ + { id: "main_first", agent: "first", message: "SWITCH_READY_FIRST" }, + { id: "main_second", agent: "second", message: "SWITCH_READY_SECOND" }, + ]); } return text("main_idle", "SWITCH_MAIN_IDLE"); }, async (session, { workspace }) => { - await session.sendText("SWITCH_USER start the first"); - await until("the first subagent's request", () => seen.first === 1); - await session.sendText("SWITCH_USER START_SECOND"); - await until("the second subagent's request", () => seen.second === 1); + await session.sendText("SWITCH_USER start them"); + await typeTaskOnSubagent(session, "first", "CHILD_READY_FIRST", "SWITCH_TASK_FIRST write first.txt"); + await typeTaskOnSubagent(session, "second", "CHILD_READY_SECOND", "SWITCH_TASK_SECOND write second.txt"); + await until("both subagents' requests", () => seen.first === 1 && seen.second === 1); // On the first subagent's screen, the second asks, then the first. await showAgent(session, "first"); @@ -2564,6 +2820,8 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { expect(readFileSync(secondFile, "utf8")).toBe("second\n"); expect(existsSync(join(workspace, "first.txt"))).toBe(false); await session.sendKeys("1"); + await session.waitForComposer(15_000); + await session.sendText("SWITCH_USER all answered"); await session.waitForText("SWITCH_MAIN_SAW_FIRST", 30_000); expect(readFileSync(join(workspace, "first.txt"), "utf8")).toBe("first\n"); }, () => {}, false, { FX_PERMISSION_MODE: "ask" }); @@ -5019,3 +5277,256 @@ describe.skipIf(!tmuxAvailable())("TUI agent switching", () => { TIMEOUT, ); }); + +// Part 2: a run main started asks through its turn, so the request is noted and +// main answers it; a turn the person typed keeps the worker's prompter and is +// never noted. A request main answers is never lent to an instance's screen. +const SPIKE_MAIN = (body: string) => body.includes("SPIKE_USER_"); +const SPIKE_NOTE = "I wait for your approval to run"; + +function writeSpikeProfile(home: string, name: string) { + const folder = join(home, ".fx", "agents", name); + mkdirSync(folder, { recursive: true }); + writeFileSync(join(folder, "profile.json"), JSON.stringify({ + description: "Writes one file", + tools: ["read_file", "write_file"], + permission_mode: "ask", + })); +} + +function writeSpikeWriter(home: string) { + writeSpikeProfile(home, "writer"); +} + +// Main answered with an answer of its own, or was told the request is gone. +function mainSaidGone(body: string): boolean { + return body.includes("no longer waiting") || body.includes("has no approval request waiting"); +} + +describe.skipIf(!tmuxAvailable())("TUI subagent approvals go to main", () => { + for (const decision of ["approve", "deny"] as const) { + test( + `a subagent's approval goes to main, which ${decision}s it`, + async () => { + const file = `spike-${decision}.txt`; + let childCalls = 0; + let mainSaid = false; + await withFx((body) => { + if (!SPIKE_MAIN(body)) { + childCalls += 1; + if (childCalls === 1) return toolCall("child_write", "write_file", { path: file, content: "SPIKE_WROTE\n" }); + return text("child_done", "SPIKE_CHILD_DONE"); + } + if (!body.includes('"main_start"')) { + return toolCall("main_start", "subagent", { + request: { action: "message", agent: "writer", message: "SPIKE_TASK", profile: "writer" }, + }); + } + if (body.includes(SPIKE_NOTE) && !body.includes("main_answer")) { + return toolCall("main_answer", "subagent", { + action: decision, + agent: "writer", + ...(decision === "deny" ? { message: "not this" } : {}), + }); + } + if (body.includes("main_answer") && !mainSaid) { + mainSaid = true; + return text("main_said", "SPIKE_MAIN_ANSWERED"); + } + return text("main_done", "SPIKE_MAIN_DONE"); + }, async (session, { workspace }) => { + await session.sendText("SPIKE_USER_e1"); + await session.waitForText("SPIKE_MAIN_ANSWERED", 30_000); + if (decision === "approve") { + await until("the write", () => existsSync(join(workspace, file))); + expect(readFileSync(join(workspace, file), "utf8")).toBe("SPIKE_WROTE\n"); + } else { + expect(existsSync(join(workspace, file))).toBe(false); + } + const pane = await session.capturePaneGrid(); + expect(pane).not.toContain("Subagent writer needs permission"); + }, writeSpikeWriter); + }, + TIMEOUT, + ); + } + + test( + "the person answers on the subagent's screen first, and main is told it no longer waits", + async () => { + const file = "spike-e2.txt"; + const note = held(); + const switched = held(); + let childCalls = 0; + let mainApproved = false; + let mainReported = false; + await withFx((body) => { + if (!SPIKE_MAIN(body)) { + childCalls += 1; + // The first call waits for the person to be on the subagent's own + // screen, so the write's prompt appears there and nowhere else. + if (childCalls === 1) return switched.promise.then(() => toolCall("child_e2_glob", "glob_files", { pattern: "nothing-*" })); + if (childCalls === 2) return toolCall("child_e2_write", "write_file", { path: file, content: "SPIKE_WROTE\n" }); + return text("child_e2_done", "SPIKE_CHILD_E2_DONE"); + } + if (!body.includes('"main_e2_start"')) { + return toolCall("main_e2_start", "subagent", { + request: { action: "message", agent: "writer", message: "SPIKE_E2_TASK", profile: "writer" }, + }); + } + if (body.includes(SPIKE_NOTE) && !mainApproved) { + // Hold main's answer until the person has answered on the + // subagent's own screen, so the order under test is the one that runs. + return note.promise.then(() => { + mainApproved = true; + return toolCall("main_e2_answer", "subagent", { action: "approve", agent: "writer" }); + }); + } + if (body.includes("main_e2_answer") && !mainReported) { + mainReported = true; + return text("main_e2_said", mainSaidGone(body) ? "SPIKE_E2_GONE" : "SPIKE_E2_ANSWERED"); + } + return text("main_e2_tail", "SPIKE_E2_DONE"); + }, async (session, { workspace }) => { + await session.sendText("SPIKE_USER_e2"); + await showAgent(session, "writer"); + await session.waitForPane((pane) => pane.includes("SPIKE_E2_TASK"), 20_000); + switched.release(); + await session.waitForPane((pane) => pane.includes("Apply this change?"), 30_000); + await session.sendKeys("1"); + await until("the write", () => existsSync(join(workspace, file))); + note.release(); + // Back on main, its answer to the note finds no request: the person + // took the binding away, so main reads that it no longer waits. + await showAgent(session, "main"); + await session.waitForText("SPIKE_E2_GONE", 30_000); + expect(readFileSync(join(workspace, file), "utf8")).toBe("SPIKE_WROTE\n"); + }, writeSpikeWriter); + }, + TIMEOUT, + ); + + test( + "a turn the person typed on the subagent's screen keeps its approval, lent as before", + async () => { + let childCalls = 0; + let mainSawNote = false; + await withFx((body) => { + if (SPIKE_MAIN(body) && body.includes(SPIKE_NOTE)) mainSawNote = true; + if (!SPIKE_MAIN(body)) { + childCalls += 1; + if (childCalls === 1) return text("child_e4_ready", "SPIKE_E4_READY"); + if (childCalls === 2) return toolCall("child_e4_write", "write_file", { path: "spike-e4.txt", content: "SPIKE_WROTE\n" }); + return text("child_e4_done", "SPIKE_E4_DONE"); + } + if (!body.includes('"main_e4_start"')) { + return toolCall("main_e4_start", "subagent", { + request: { action: "message", agent: "writer", message: "SPIKE_E4_FIRST", profile: "writer" }, + }); + } + return text("main_e4_tail", "SPIKE_E4_MAIN_DONE"); + }, async (session, { workspace }) => { + await session.sendText("SPIKE_USER_e4"); + await session.waitForText("SPIKE_E4_MAIN_DONE", 30_000); + await showAgent(session, "writer"); + await session.waitForPane((pane) => pane.includes("SPIKE_E4_FIRST"), 20_000); + // A turn the person types on the subagent's own screen. + await session.sendText("SPIKE_E4_TYPED"); + await session.waitForPane((pane) => pane.includes("Apply this change?"), 30_000); + await showAgent(session, "main"); + // Its approval is lent to main's screen, as it was before Part 2. + await session.waitForPane((pane) => pane.includes("Subagent writer needs permission"), 30_000); + await session.sendKeys("1"); + await until("the write", () => existsSync(join(workspace, "spike-e4.txt"))); + expect(mainSawNote).toBe(false); + }, writeSpikeWriter); + }, + TIMEOUT, + ); + + test( + "two subagents wait at once, and main answers both", + async () => { + const childCalls = { writer: 0, helper: 0 }; + const approveCalls = { writer: 0, helper: 0 }; + const approve = (agent: "writer" | "helper") => + toolCall(`main_e5_approve_${agent}_${approveCalls[agent]++}`, "subagent", { action: "approve", agent }); + const approvalAllowed = (body: string, agent: string): boolean => { + let allowed = false; + const walk = (value: any) => { + if (allowed) return; + if (Array.isArray(value)) value.forEach(walk); + else if (value && typeof value === "object") { + if ( + value.type === "tool-result" && + typeof value.toolCallId === "string" && + value.toolCallId.startsWith(`main_e5_approve_${agent}`) && + JSON.stringify(value.output).includes("Allowed") + ) allowed = true; + else Object.values(value).forEach(walk); + } + }; + walk(JSON.parse(body)); + return allowed; + }; + await withFx((body) => { + if (!SPIKE_MAIN(body)) { + const who = body.includes("SPIKE_E5_WRITER") ? "writer" : "helper"; + childCalls[who] += 1; + if (childCalls[who] === 1) { + return toolCall(`child_e5_${who}`, "write_file", { path: `spike-e5-${who}.txt`, content: "SPIKE_WROTE\n" }); + } + return text(`child_e5_${who}_done`, `SPIKE_E5_${who.toUpperCase()}_DONE`); + } + if (!body.includes('"main_e5_start"')) { + return messageSteps([ + { id: "main_e5_start", agent: "writer", message: "SPIKE_E5_WRITER", profile: "writer" }, + { id: "main_e5_helper", agent: "helper", message: "SPIKE_E5_HELPER", profile: "helper" }, + ]); + } + if (body.includes(SPIKE_NOTE)) { + // Approve the agent the newest note names, once per agent: a fixed + // order approved writer before writer's request had reached fx ("has + // no approval request waiting"), and helper's earlier note then made + // the later one find both approve calls in the history and never get + // answered. The note's quotes arrive JSON-escaped inside its message, + // so match the agent's name, not `agent "name"`. + const note = latestUserText(body); + const named: "writer" | "helper" | null = note.includes(SPIKE_NOTE) + ? note.includes("helper") ? "helper" : note.includes("writer") ? "writer" : null + : null; + if (named && !approvalAllowed(body, named)) return approve(named); + // An approve that came too early is made again once that agent's note + // is in the history, under a new call id. + const noted = (agent: "writer" | "helper") => + userTexts(body).some((text) => text.includes(SPIKE_NOTE) && text.includes(agent)); + for (const agent of ["writer", "helper"] as const) { + if (approvalAllowed(body, agent)) continue; + if (!noted(agent)) continue; + return approve(agent); + } + // Both answered only once both approve results said the request was + // answered; otherwise end the turn so the next note starts another. + if (approvalAllowed(body, "writer") && approvalAllowed(body, "helper")) { + return text("main_e5_tail", "SPIKE_E5_BOTH_ANSWERED"); + } + return text("main_e5_waiting", "SPIKE_E5_WAITING"); + } + // Not a note turn (the opening turn's later request): nothing is + // answered yet, so only a note turn may say both were. + return text("main_e5_tail", "SPIKE_E5_STARTED"); + }, async (session, { workspace }) => { + await session.sendText("SPIKE_USER_e5"); + await session.waitForText("SPIKE_E5_BOTH_ANSWERED", 30_000); + await until("the writer's write", () => existsSync(join(workspace, "spike-e5-writer.txt"))); + await until("the helper's write", () => existsSync(join(workspace, "spike-e5-helper.txt"))); + const pane = await session.capturePaneGrid(); + expect(pane).not.toContain("needs permission"); + }, (home) => { + writeSpikeProfile(home, "writer"); + writeSpikeProfile(home, "helper"); + }); + }, + TIMEOUT, + ); +}); diff --git a/tests/tla/README.md b/tests/tla/README.md index fca73c4429..d5426e90a7 100644 --- a/tests/tla/README.md +++ b/tests/tla/README.md @@ -33,6 +33,7 @@ TLA+ specifications for fx, checked with TLC, together with the scripts and Bun | `shell_command/` | How an agent git command is admitted and run (`src/core/shell_command/safe_git.zig`), how a workspace capture writes into fx's own store without reading the repository or its index, and one model turn through the shell tool, for the current design and a redesign. `FailureStreak.tla` models when repeated shell failures end a turn (`ShellExecutionFailureRetryState` in `src/core/agent/runtime/tool_admission.zig`): a step that changed a file never ends it, and three unchanged failures in a row always do. Its driver replays seeded turns of the real binary through TLC. | `shell_command/check.sh`, `bun test drivers/shell_command/` | | `shell_eval_error/` | The error prefix the quoting-error test in `tests/e2e/ask-presentation.test.ts` accepts for each login shell (`tests/e2e/shell-eval-error.ts`). The shell snapshot runs a command through `eval`, so zsh, bash 5, and bash 3.2 each report an unclosed quote under their own prefix. Every supported shell's quoting error is accepted and a run without the error is not. `head.cfg` is the rule before the fix, which rejected bash 3.2, and `mutant-any-line.cfg` plants a matcher that accepts any line. | `shell_eval_error/check.sh`, then `bun test ./tests/tla/drivers/shell_eval_error/`, which runs the built `zig-out/bin/fx` with each login shell on this Mac (zsh, bash 3.2, and a bash 4 or later when installed; macOS only), hands the real output to the test's matcher, and has TLC replay the runs, plus three planted wrong matchers | | `subagent/` | Main's messages into its subagents' running turns (`Owner.steer` in `src/core/subagent/managed_owner.zig`): a subagent with 64 unread messages takes no more until its next step reads them, a read message never counts again, one subagent's full queue never refuses another's, and entries are dropped only at a new work or a saved close, where no worker still holds their receipts. `steer-queue-today.cfg` and `steer-queue-today-close.cfg` show fx before it, and six planted mutations must each be caught by their named rule. | `subagent/check.sh`, then `bun tests/tla/drivers/subagent/driver.ts --self-check`, which runs `fx ask` walks of the built `zig-out/bin/fx` against a local gateway, playing main's and every subagent's model, compares each answer with the model, checks each close's `feedback_forgotten` trace count, and has TLC check every walk (`SteerQueueTrace.tla`); `--stress N` adds 20 subagents taking 30 messages each for N rounds, and `--race N` lets subagents read while messages arrive and checks that each reaches its subagent exactly once. `StopMessage.tla` covers a stop, a close and a message to one subagent in any order, in one step or across steps (`stopChild`, `closeChild` and the message path in `src/core/subagent/tool_host.zig`, the step's subagent group in `src/core/agent/runtime/parallel_execution.zig`): a message right after a stop waits for the next turn, a message to a subagent whose turn is still starting waits for that turn to begin and joins it, calls to one subagent run in the order main wrote them, a message is refused only while its subagent is closing, which lasts until its close is written, and a closing subagent holds no message (`ClosingHoldsNothing`), a stop or close in the gap after a work ended, before its slot goes on, answers truly and leaves no turn running after it (`GapStopHonest`), a stop or close after a turn ended with messages unread, or after the host chose a next work that no turn has begun on, counts and drops those messages and the end hook queues none of them (`StopHoldsForQueued`, `ClosingHoldsNoKept`), every message is read, refused, or counted in a stop's or close's answer, and counted once (`CountedOnce`). Sixteen planted bugs and four configs of the code before the fixes must each break their rule. It also covers what main hears about idle subagents: a message that starts a new subagent names exactly the others that are idle (`NamesTheIdle`), and a report says its subagent is idle exactly when nothing waits to start its next turn (`IdleNoteHonest`); `stop-message-before-idle.cfg` and `stop-message-before-names.cfg` are fx before that, and two more planted bugs must break those rules. `drivers/subagent/stop-message.test.ts` runs fx against a local gateway, holds each turn's start with `FX_TEST_SUBAGENT_START_HELD` and each stopped turn's end with `FX_TEST_SUBAGENT_END_HELD`, reads each report's idle note from fx's `report_queued` trace line and each start's idle names from its answer, and has TLC check every walk (`StopMessageTrace.tla`); `FX_TLA_STOP_STRESS=N` also starts one subagent beside N idle ones. `MainMail.tla` covers how a subagent's report or message reaches main (`postMailWith`, `takeSteeringBoundaryIntoInner`, `takeQueuedPromptForTurn` and `finishProcessing` in `src/core/agent/worker_runtime.zig`, `runAskTurn` in `src/core/cli/cli_ask.zig`) and what `wait` says about it: where turns take mail (the app, `fx ask`), mail posted while main's turn is open with nothing older waiting reaches main in that turn (`JoinsOpenTurn`), main reads each piece once (`EachOnce`), in order (`InOrder`), and none is lost (`NoneLost`), and `wait` says the mail follows only when it joined the running turn (`WaitHonest`); `main-mail-acp.cfg` is ACP, whose turns never take mail. `main-mail-today.cfg` and `main-mail-today-acp.cfg` are fx before it, and three planted bugs must break their rules. Where the host commits a finished turn in a step of its own (the app's main loop), `main-mail-commit.cfg` adds the commit gate (`enableCommitGate` and `acknowledgeFinishCommitted` in `src/core/agent/worker_runtime.zig`, `appendFinishedPrompt` in `src/core/app/app_session_runtime.zig`): mail that missed a finished turn does not start the next one before the loop commits it, unless the gate gave up (`CommitBeforeNextTurn`), and the gate never waits for a commit that is not coming (`GateNeverStuck`); a finish the loop drops unsaved is acknowledged as a commit is, and three more planted bugs, `no-gate`, `stuck-gate` and `drop-unacknowledged`, must break those rules. `drivers/subagent/main-mail.test.ts` runs `fx ask` walks against a local gateway, holds each subagent's model request until the walk finishes it, turns fx's worker trace lines (written under the worker's lock) into observations, and has TLC check every walk and its rules (`MainMailTrace.tla`); `FX_TLA_MAIL_RANDOM=N` adds random walks, and `FX_TLA_MAIL_STRESS=N` reports N subagents into one turn and logs main's capped list of them. `QuietRelay.tla` covers fx's note to a parent when its subagent's shell command crosses the quiet limit (`noteChildQuiet` in `src/core/subagent/tool_host.zig`, raised by `src/core/subagent/agent_adapter.zig` for fx ask and ACP and by `src/core/app/app_worker_runtime.zig` for the interactive app) and the parent's wait it wakes: one note per quiet spell, none for a later notice in the same spell or for a closed subagent, a note the full mailbox refuses dropped with a log line, and a wait that registers before it checks the mailbox never sleeps on mail. Five planted bugs must each break their rule. `drivers/subagent/quiet-relay.test.ts` runs fx ask walks against a local gateway with `FX_TEST_SHELL_QUIET_NOTICE_MS` and has TLC check every walk (`QuietRelayTrace.tla`); `FX_TLA_QUIET_RACE` and `FX_TLA_QUIET_STRESS` add its race and stress rounds. `bun tests/tla/drivers/subagent/quiet-relay-mutants.ts` plants eleven bugs in the relay's code, one at a time, and requires its unit, fx ask, and agent list tests to catch each. `WaitNudge.tla` covers main's `wait` against subagent works that end with nothing to post (`waitForMail`, `workEnded` and `nudgeWaiter` in `src/core/subagent/tool_host.zig`, `waitForPostOrNudge` in `src/core/agent/worker_runtime.zig`): `wait` registers before it reads whether a child works, and a work's end nudges only after it clears the child's busy flag, so `wait` always returns and TLC never reaches a blocked wait that nothing can wake (a deadlock). `wait-nudge-today.cfg` is fx before it, and the planted `wait-nudge-mutation-check-first.cfg` must also deadlock. No trace driver runs fx along it: the inline tests in `tool_host.zig` and `a wait that starts as a subagent's work ends with nothing to report still returns` in `tests/e2e/gateway-stream-lifecycle.test.ts` hold fx in the gap with `FX_TEST_SUBAGENT_SETTLE_HELD`. | +| `subagent/TuiParentApproval.tla` | A TUI subagent's approval request: it goes to the subagent's parent, which answers `approve` or `deny`, it is never lent to an instance's screen, and the prompt owns a copy of its review (design c). The trial, a, a2 and b are the designs not taken. | `check.sh` | | `terminal/` | The in-memory shell snapshot owner (`src/core/terminal/shell_snapshot.zig`) and the lifecycle of hosted terminals. | `terminal/check.sh` | | `toolbox/` | The toolbox (`src/core/tooling/toolbox.zig`, with the request building in `src/core/agent/runtime/orchestrator.zig`): fx sends its built-in tools and one `toolbox` tool, and a menu of skills, MCP servers, custom tools, and tools moved behind toolbox, both fixed for the session. Opening an entry adds its text at the end of the conversation, and a run, through toolbox or by a tool's own name, needs the permission check on the real tool. Through catalog changes, compaction, a crash mid-run, and resume, the tools and the menu never change, each request extends the one before it between compactions, no call runs twice, an allowed run of an available tool succeeds without being opened first, and every request tells the model what the catalog holds, after a compaction too. Eight planted mutations must each be caught by their named rule. | `toolbox/check.sh` | | `transcript_window/` | What the main screen holds of a long session and what Ctrl+O reads (`src/ui/transcript/transcript_window.zig`, a pure core the transcript runtime drives through `transcript_window_shell.zig` for every session). The current compaction cycle is held, plus the previous one until the first turn end at which the session log holds it; live blocks are never dropped; a resize reprints the held blocks in bounded slices; Ctrl+O opens from memory and reads older blocks from the log one window at a time, through crashes and lost, stale, duplicate, and garbage replies. `design/` holds the goal, vision, context, and design the checks trace to, and `mutations.json` the planted bugs. | `transcript_window/check.sh`, which runs `bun run verify`: TLC on every config, every edge of the sweep graphs replayed against the real core, code traces with real crashes checked by TLC, every planted bug in the spec and the core, `design/DESIGN.md` traceability, and the built binary through three compaction cycles, Ctrl+O, a resize, and a resume, its traced window steps replayed on the core and checked by TLC | diff --git a/tests/tla/subagent/ParentApproval.tla b/tests/tla/subagent/ParentApproval.tla index cdb9755f4a..dd530de593 100644 --- a/tests/tla/subagent/ParentApproval.tla +++ b/tests/tla/subagent/ParentApproval.tla @@ -261,8 +261,9 @@ Resume(k) == /\ wake' = TRUE /\ UNCHANGED <> -\* Main's stop of a waiting subagent, a tool call in its turn: it drops the -\* registered request and any note still waiting. +\* Main's stop of a waiting subagent, a tool call in its turn: it first refuses +\* the request the subagent waits on (the call is refused, nothing runs), then +\* drops it and any note still waiting. Stop(k) == /\ main = "turn" /\ kid[k] = "waiting" diff --git a/tests/tla/subagent/TuiParentApproval.tla b/tests/tla/subagent/TuiParentApproval.tla new file mode 100644 index 0000000000..4523db7a8e --- /dev/null +++ b/tests/tla/subagent/TuiParentApproval.tla @@ -0,0 +1,539 @@ +--------------------- MODULE TuiParentApproval --------------------------- +(***************************************************************************) +(* A TUI subagent's approval request, and who answers it. *) +(* *) +(* Design c is the code in this change: the prompt takes its copy of the *) +(* review under the worker's mutex, while the request still waits, so the *) +(* tool call that built it cannot free it first; a parent-routed request *) +(* is never lent, and a note that cannot be posted refuses. Designs a, a2 *) +(* and b, and the trial of step 3b, are the designs not taken; their rows *) +(* keep checking the traps they avoid. *) +(* *) +(* The person's spec: the request goes to main, which answers `approve` or *) +(* `deny` under its own permissions, as in Part 1 (PR #2198). It still *) +(* shows on the subagent's own screen, so the person can answer there; a *) +(* turn the person typed on that screen stays with the person; main's *) +(* screen no longer borrows the request; the footer and the agent list stop *) +(* saying the subagent needs the person for it. *) +(* *) +(* Design = "trial" is the reverted step 3b: the turn's prompter for a *) +(* parent-started run (app_agent_runtime.zig:452, with `run.turn` set at *) +(* :1652), the note, lending still on (app_agents_runtime.zig:1270-1274), *) +(* and main's answer resolved and submitted in one step on main's thread *) +(* (managed_owner.zig:1614-1634), which the loop learns of only at its next *) +(* sync. Design "a" keeps that ordering and stops lending a parent-routed *) +(* request. Design "a2" is "a" with one guard: the worker frees the review *) +(* memory only after no screen shows the request. Design "b" hands main's *) +(* answer to the loop (`MainPost`), and the loop clears the prompt and any *) +(* lent copy before it submits (`LoopApply`), all in one step. *) +(* *) +(* Two screens can hold a request: the child's own prompt (`shown`, synced *) +(* from the worker by the loop) and the copy an instance lent (`lent`). *) +(* Both carry the review pointer borrowed from the tool call, so `freed` *) +(* models the call ending and letting it go. `NoStalePrompt` is the rule *) +(* that no screen draws a prompt whose review memory is freed, and *) +(* `NoStaleLent` the rule that no screen holds a request that stopped *) +(* waiting (map M1.3a). `a` breaks the first and the trial the second. *) +(* *) +(* `Ask` is requestChildPermission and registerApproval *) +(* (src/core/subagent/execution.zig:495-537, :621-653): a run the parent *) +(* started registers and waits on the child's own worker *) +(* (worker_runtime.zig:3274); a turn the person typed has no `turn` *) +(* (app_agent_runtime.zig:1660-1676) and registers nothing. `PostNote` is *) +(* noteChildApproval (tool_host.zig:2587-2610) and `MarkNoted` is *) +(* markNoted (approval_registry.zig:373-378). `NoteFails` is a note that *) +(* cannot be posted: Part 1 refuses the request at once *) +(* (execution.zig:578-586), and FailedNote = "person" leaves it with the *) +(* person instead. `RegisterFailsFull` is registerTool at max_pending *) +(* (approval_registry.zig:247, execution.zig:530-534). *) +(* *) +(* `Lend` is lendPrompt and lendApproval (app_agents_runtime.zig:1197- *) +(* 1218, :1270-1274), `ReturnLend` is returnApproval and keepLentApproval *) +(* (app_agents_runtime.zig:1278-1307), and `PersonAnswerMain` is *) +(* submitPermissionChoice on a lent copy, whose prompt clears in the same *) +(* step (input_approval_runtime.zig:257-269). `PersonAnswerChild` is the *) +(* same call on the child's own screen. `MainAnswer` is answerApproval *) +(* (tool_host.zig:2175-2291): approve runs the exact call through main's *) +(* own check (tool_runtime.zig:2937-2974), which allows or refuses. *) +(* `Stop` is stopChild and closeNamed (tool_host.zig:404-408, *) +(* managed_owner.zig:795); `ChildTurnEnds` is the child's turn ending, its *) +(* request and review memory freed (worker_runtime.zig:978-995). *) +(* *) +(* The TUI has no fallback as fx ask has: the person can always answer on *) +(* the child's own screen, and a lend goes back before that screen shows *) +(* anything, so every request ends answered, stopped, or with its turn. *) +(***************************************************************************) +EXTENDS Naturals, FiniteSets + +CONSTANTS + Kids, \* one or two subagents whose tool calls need approval + Design, \* "trial" | "a" | "b" + FailedNote, \* "refuse" | "person": what a note that cannot post does + RegistryFull, \* whether the registry already holds max_pending requests + Mutant \* "none", or one defect planted in the design + +ASSUME Design \in {"trial", "a", "a2", "b", "c"} +ASSUME FailedNote \in {"refuse", "person"} +ASSUME RegistryFull \in BOOLEAN +ASSUME Mutant \in {"none", "lend_routed", "no_withdraw", "note_typed", + "free_anyway", "b_note_keeps_prompt"} + +VARIABLES + kid, \* each: "working", "waiting", "ran", "refused", "stopped", "cancelled" + req, \* the registry binding: "none", "registered", "noted" + decision, \* what the child's worker took: "none", "allow", "deny" + answers, \* answers that reached each worker: 0, 1, or 2 + shown, \* the child's own prompt: "none" or "prompt" + freed, \* whether the tool call freed the review memory its prompt borrowed + queued, \* design b: main's answer waiting in the loop: "none", "allow", "deny" + policy, \* main's own check for each call: "allow" or "refuse" + typed, \* kids whose turn the person typed on their own screen + mail, \* notes posted and not yet taken by main + posted, \* notes posted whose request is not yet marked noted + seen, \* notes main's turns took + main, \* "idle" or "turn" + lent, \* the kid whose request main's screen holds a copy of, or "none" + authorized, \* kids whose action main's check or the person allowed + noPending, \* kids a later answer told it no longer waits + lost \* kids whose main answer found no live request + +vars == <> + +\* A request the registry holds, which main's answer can find. It outlives the +\* run it belongs to unless an answer or the person took it away. +Requested(k) == req[k] \in {"registered", "noted"} + +\* The child's worker still waits for a decision on its request. +WaitingOnWorker(k) == kid[k] = "waiting" /\ decision[k] = "none" + +\* What the child's own prompt shows: the request while its worker waits, and +\* nothing while the lend holds it or the worker has its answer. `syncState` +\* (app_worker_runtime.zig:809-830) sets it from the worker every pass. +ShownFromWorker(k) == + IF WaitingOnWorker(k) /\ lent # k THEN "prompt" ELSE "none" + +\* Whether a child registers its request: a parent-started run does, a turn the +\* person typed does not. `note_typed` plants the defect of registering one. +RegistersChild(k) == k \notin typed \/ Mutant = "note_typed" + +\* Whether a person's answer takes the binding away. Design b does it in the +\* loop's own step; a and a2 do it a step later, and main's thread may resolve +\* in between. The trial did not, and `no_withdraw` plants that. +Withdraws == Design \in {"a", "a2", "b", "c"} /\ Mutant # "no_withdraw" + +\* Whether a waiting request may be lent to an instance's screen. The trial lent +\* any waiting request; a, a2 and b lend only a turn the person typed, and +\* `lend_routed` plants the defect of lending a parent-routed one. +Lendable(k) == Design = "trial" \/ Mutant = "lend_routed" \/ k \in typed + +\* Whether the worker may free the review memory before the loop has synced the +\* prompt. The trial and a free it as soon as the call goes on; a2 and b wait +\* until no screen shows the request. `free_anyway` plants the missing guard. +FreesWhenDone(k) == + \* c is the shipped design: the prompt owns a copy of its review, so the + \* worker frees the call's memory whenever the call ends. + \/ Design \in {"trial", "a", "c"} \/ Mutant = "free_anyway" + \/ /\ shown[k] = "none" + /\ lent # k + +TypeOK == + /\ kid \in [Kids -> {"working", "waiting", "ran", "refused", "stopped", + "cancelled"}] + /\ req \in [Kids -> {"none", "registered", "noted"}] + /\ decision \in [Kids -> {"none", "allow", "deny"}] + /\ answers \in [Kids -> 0..2] + /\ shown \in [Kids -> {"none", "prompt"}] + /\ freed \in [Kids -> BOOLEAN] + /\ queued \in [Kids -> {"none", "allow", "deny"}] + /\ policy \in [Kids -> {"allow", "refuse"}] + /\ typed \subseteq Kids + /\ mail \subseteq Kids + /\ posted \subseteq Kids + /\ seen \subseteq Kids + /\ main \in {"idle", "turn"} + /\ lent \in Kids \cup {"none"} + /\ authorized \subseteq Kids + /\ noPending \subseteq Kids + /\ lost \subseteq Kids + +Init == + /\ kid = [k \in Kids |-> "working"] + /\ req = [k \in Kids |-> "none"] + /\ decision = [k \in Kids |-> "none"] + /\ answers = [k \in Kids |-> 0] + /\ shown = [k \in Kids |-> "none"] + /\ freed = [k \in Kids |-> FALSE] + /\ queued = [k \in Kids |-> "none"] + /\ policy \in [Kids -> {"allow", "refuse"}] + /\ typed \in SUBSET Kids + /\ mail = {} + /\ posted = {} + /\ seen = {} + /\ main = "idle" + /\ lent = "none" + /\ authorized = {} + /\ noPending = {} + /\ lost = {} + +\* `requestChildPermission` and `registerApproval`: the subagent's call needs +\* approval. A run the parent started registers the exact call, and the request +\* waits on the child's own worker. A turn the person typed registers nothing, +\* so the request stays on the child's own screen. +Ask(k) == + /\ kid[k] = "working" + /\ req[k] = "none" + /\ answers[k] = 0 + /\ \/ ~RegistersChild(k) + \/ ~RegistryFull + /\ kid' = [kid EXCEPT ![k] = "waiting"] + /\ IF RegistersChild(k) + THEN req' = [req EXCEPT ![k] = "registered"] + ELSE req' = req + /\ UNCHANGED <> + +\* `registerTool` refuses at max_pending, so `requestChildPermission` answers +\* the child with a deny and the reason: the action does not run. +RegisterFailsFull(k) == + /\ RegistryFull + /\ RegistersChild(k) + /\ kid[k] = "working" + /\ req[k] = "none" + /\ kid' = [kid EXCEPT ![k] = "refused"] + /\ UNCHANGED <> + +\* `noteChildApproval`: one note to main, posted only after the request is +\* registered and while it still waits. A note for a request that already +\* ended is not posted. +PostNote(k) == + /\ WaitingOnWorker(k) + /\ req[k] = "registered" + /\ k \notin posted + /\ posted' = posted \cup {k} + /\ mail' = mail \cup {k} + /\ UNCHANGED <> + +\* `markNoted`: the note went out, so the binding counts as noted. It is marked +\* only while the request still waits, and a mark for a request that ended does +\* nothing. +MarkNoted(k) == + /\ WaitingOnWorker(k) + /\ req[k] = "registered" + /\ k \in posted + /\ req' = [req EXCEPT ![k] = "noted"] + /\ posted' = posted \ {k} + /\ UNCHANGED <> + +\* A note that cannot be posted. Part 1's rule refuses the request at once +\* (execution.zig:530-534): the worker takes a deny, and the loop clears the +\* prompt with it, except in the trial and in a, which apply it off the loop and +\* leave the prompt for their next sync. FailedNote = "person" takes the binding +\* away and leaves the request waiting, where the person answers it. +NoteFails(k) == + /\ WaitingOnWorker(k) + /\ req[k] = "registered" + /\ k \notin posted + /\ IF FailedNote = "refuse" + THEN /\ req' = [req EXCEPT ![k] = "none"] + /\ posted' = posted + /\ decision' = [decision EXCEPT ![k] = "deny"] + /\ answers' = [answers EXCEPT ![k] = 1] + /\ IF Design = "b" /\ Mutant # "b_note_keeps_prompt" + THEN /\ shown' = [shown EXCEPT ![k] = "none"] + /\ lent' = IF lent = k THEN "none" ELSE lent + ELSE /\ shown' = shown + /\ lent' = lent + ELSE /\ req' = [req EXCEPT ![k] = "none"] + /\ posted' = posted \ {k} + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* `lendPrompt` and `lendApproval`: the instance on screen borrows the child's +\* prompt, which swaps it away from the child's own screen +\* (app_agents_runtime.zig:1270-1274). The trial lent any waiting request; a, +\* a2 and b lend only a turn the person typed. +Lend(k) == + /\ lent = "none" + /\ shown[k] = "prompt" + /\ WaitingOnWorker(k) + /\ Lendable(k) + /\ lent' = k + /\ shown' = [shown EXCEPT ![k] = "none"] + /\ UNCHANGED <> + +\* `returnApproval` and `keepLentApproval` (app_agents_runtime.zig:1278-1307): +\* the copy goes back when its subagent stops waiting, or when the person opens +\* that subagent, and the child's prompt shows what its worker still waits on. +ReturnLend == + /\ lent # "none" + /\ lent' = "none" + /\ shown' = [k \in Kids |-> IF lent = k THEN ShownFromWorker(k) ELSE shown[k]] + /\ UNCHANGED <> + +\* `syncState` (app_worker_runtime.zig:809-830): the loop reads the child's +\* worker and shows or clears the child's own prompt. It runs a pass behind +\* main's answer in the trial and in a, which is what those designs leave open. +Sync(k) == + /\ shown[k] # ShownFromWorker(k) + /\ shown' = [shown EXCEPT ![k] = ShownFromWorker(k)] + /\ UNCHANGED <> + +\* Main takes the notes waiting as mail in its turn (postAgentMessage, +\* src/main.zig:2156). +TakeMail == + /\ main = "idle" + /\ mail # {} + /\ main' = "turn" + /\ seen' = seen \cup mail + /\ mail' = {} + /\ UNCHANGED <> + +\* `answerApproval` on main's thread: approve runs the subagent's exact call +\* through main's own check (tool_runtime.zig:2937-2974), which allows or +\* refuses; deny refuses without a check. The registry resolves the binding and +\* the worker takes the decision in one step, and the loop learns of it only at +\* its next `Sync`. An answer whose binding outlived its request is told it no +\* longer waits, and an answer that finds no binding while the child waits is +\* lost. +MainAnswer(k, d) == + /\ Design # "b" + /\ main = "turn" + /\ k \in seen + /\ \/ /\ Requested(k) + /\ WaitingOnWorker(k) + /\ IF d = "deny" \/ policy[k] = "refuse" + THEN /\ decision' = [decision EXCEPT ![k] = "deny"] + /\ authorized' = authorized + ELSE /\ decision' = [decision EXCEPT ![k] = "allow"] + /\ authorized' = authorized \cup {k} + /\ req' = [req EXCEPT ![k] = "none"] + /\ answers' = [answers EXCEPT ![k] = 1] + /\ noPending' = noPending + /\ lost' = lost + \/ /\ Requested(k) + /\ ~WaitingOnWorker(k) + /\ req' = [req EXCEPT ![k] = "none"] + /\ decision' = decision + /\ answers' = answers + /\ noPending' = noPending \cup {k} + /\ authorized' = authorized + /\ lost' = lost + \/ /\ req[k] = "none" + /\ WaitingOnWorker(k) + /\ lost' = lost \cup {k} + /\ UNCHANGED <> + /\ posted' = posted \ {k} + /\ UNCHANGED <> + +\* Design b: main's answer is handed to the loop, which is the one writer of +\* every prompt. Nothing changes for the child's worker here. +MainPost(k, d) == + /\ Design = "b" + /\ main = "turn" + /\ k \in seen + /\ Requested(k) + /\ kid[k] = "waiting" + /\ queued[k] = "none" + /\ queued' = [queued EXCEPT ![k] = d] + /\ UNCHANGED <> + +\* Design b: the loop takes that answer and clears the child's prompt and any +\* lent copy in the same step as the submit, so no screen is left showing a +\* request whose memory is freed. A request that already took an answer is told +\* it no longer waits. +LoopApply(k) == + /\ Design = "b" + /\ queued[k] # "none" + /\ queued' = [queued EXCEPT ![k] = "none"] + /\ req' = [req EXCEPT ![k] = "none"] + /\ IF WaitingOnWorker(k) + THEN /\ decision' = [decision EXCEPT ![k] = queued[k]] + /\ answers' = [answers EXCEPT ![k] = 1] + /\ authorized' = IF queued[k] = "allow" + THEN authorized \cup {k} ELSE authorized + /\ noPending' = noPending + ELSE /\ decision' = decision + /\ answers' = answers + /\ authorized' = authorized + /\ noPending' = noPending \cup {k} + /\ shown' = [shown EXCEPT ![k] = "none"] + /\ lent' = IF lent = k THEN "none" ELSE lent + /\ posted' = posted \ {k} + /\ UNCHANGED <> + +\* The person's answer in a and a2 takes the binding away a step later, so +\* main's thread may resolve it in between. In b the person's own step does it. +Withdraw(k) == + /\ Withdraws + /\ Design # "b" + /\ Requested(k) + /\ decision[k] # "none" + /\ req' = [req EXCEPT ![k] = "none"] + /\ posted' = posted \ {k} + /\ UNCHANGED <> + +\* `submitPermissionChoice` on the child's own screen: the loop clears that +\* prompt and the answer reaches the child's worker in one step, as +\* input_approval_runtime.zig:259-274 does. Design b also takes the binding +\* away here; a and a2 do it in `Withdraw`, a step later. +PersonAnswerChild(k, d) == + /\ lent = "none" + /\ shown[k] = "prompt" + /\ WaitingOnWorker(k) + /\ shown' = [shown EXCEPT ![k] = "none"] + /\ decision' = [decision EXCEPT ![k] = d] + /\ answers' = [answers EXCEPT ![k] = 1] + /\ authorized' = IF d = "allow" THEN authorized \cup {k} ELSE authorized + /\ IF Withdraws /\ Design = "b" + THEN /\ req' = [req EXCEPT ![k] = "none"] + /\ posted' = posted \ {k} + ELSE /\ req' = req + /\ posted' = posted + /\ UNCHANGED <> + +\* The person answers the copy lent to main's screen: the loop clears the copy +\* and the child's prompt and submits in one step, which is why this path never +\* left a stale copy behind (input_approval_runtime.zig:257-274). +PersonAnswerMain(k, d) == + /\ lent = k + /\ WaitingOnWorker(k) + /\ lent' = "none" + /\ shown' = [shown EXCEPT ![k] = "none"] + /\ decision' = [decision EXCEPT ![k] = d] + /\ answers' = [answers EXCEPT ![k] = 1] + /\ authorized' = IF d = "allow" THEN authorized \cup {k} ELSE authorized + /\ IF Withdraws /\ Design = "b" + THEN /\ req' = [req EXCEPT ![k] = "none"] + /\ posted' = posted \ {k} + ELSE /\ req' = req + /\ posted' = posted + /\ UNCHANGED <> + +\* The child's worker resumes: an allowed action runs, a denied one does not. +Resume(k) == + /\ kid[k] = "waiting" + /\ decision[k] # "none" + /\ kid' = [kid EXCEPT ![k] = IF decision[k] = "allow" THEN "ran" ELSE "refused"] + /\ decision' = [decision EXCEPT ![k] = "none"] + /\ UNCHANGED <> + +\* The tool call goes on and lets go of the review memory its prompt borrowed +\* (tool_admission.zig:1967-1980, approval_prompt.zig:53). The trial and a free +\* it as soon as the call has its answer, whether or not a screen still shows +\* the request; a2 and b wait until no screen does. +Free(k) == + /\ decision[k] # "none" + /\ ~freed[k] + /\ FreesWhenDone(k) + /\ freed' = [freed EXCEPT ![k] = TRUE] + /\ UNCHANGED <> + +\* `stopChild` and `closeNamed` end a waiting child and drop its request +\* (tool_host.zig:404-408, managed_owner.zig:795); the lend goes back first +\* (app_agents_runtime.zig:2254), and an answer still queued has nowhere to go. +Stop(k) == + /\ main = "turn" + /\ kid[k] = "waiting" + /\ kid' = [kid EXCEPT ![k] = "stopped"] + /\ req' = [req EXCEPT ![k] = "none"] + /\ mail' = mail \ {k} + /\ posted' = posted \ {k} + /\ lent' = IF lent = k THEN "none" ELSE lent + /\ queued' = [queued EXCEPT ![k] = "none"] + /\ noPending' = IF queued[k] = "none" THEN noPending ELSE noPending \cup {k} + /\ UNCHANGED <> + +\* The child's turn ends or is cancelled (RULES.md R2.4): its request is +\* withdrawn and its review memory freed (worker_runtime.zig:978-995). +ChildTurnEnds(k) == + /\ kid[k] = "waiting" + /\ kid' = [kid EXCEPT ![k] = "cancelled"] + /\ req' = [req EXCEPT ![k] = "none"] + /\ mail' = mail \ {k} + /\ posted' = posted \ {k} + /\ lent' = IF lent = k THEN "none" ELSE lent + /\ queued' = [queued EXCEPT ![k] = "none"] + /\ noPending' = IF queued[k] = "none" THEN noPending ELSE noPending \cup {k} + /\ UNCHANGED <> + +\* Main ends its turn. +EndTurn == + /\ main = "turn" + /\ main' = "idle" + /\ UNCHANGED <> + +\* Every subagent is settled and main has no mail: the behavior is over. +Finished == + /\ main = "idle" + /\ mail = {} + /\ \A k \in Kids : kid[k] \in {"ran", "refused", "stopped", "cancelled"} + /\ UNCHANGED vars + +Next == + \/ \E k \in Kids : + Ask(k) \/ RegisterFailsFull(k) \/ PostNote(k) \/ MarkNoted(k) + \/ NoteFails(k) \/ Resume(k) \/ Free(k) \/ Stop(k) \/ ChildTurnEnds(k) + \/ Lend(k) \/ ReturnLend \/ Sync(k) \/ LoopApply(k) \/ Withdraw(k) + \/ \E k \in Kids, d \in {"allow", "deny"} : + MainAnswer(k, d) \/ MainPost(k, d) \/ PersonAnswerChild(k, d) + \/ PersonAnswerMain(k, d) + \/ TakeMail + \/ EndTurn + \/ Finished + +Spec == Init /\ [][Next]_vars + +\* Main's screen never holds a copy of a request that is no longer waiting. The +\* trial breaks this as soon as main answers a lent request, because the copy +\* stayed in main's prompt until the child's next sync gave it back (map M1.3a). +NoStaleLent == \A k \in Kids : lent = k => WaitingOnWorker(k) + +\* No screen draws a prompt whose review memory is freed. Both copies of a +\* request borrow that memory from the child's tool call, so a free while either +\* still shows the request is a use-after-free (map M1.3a). +\* Under c a shown prompt reads its own copy, so freeing the call's memory +\* never makes it stale. +NoStalePrompt == \A k \in Kids : (shown[k] = "prompt" \/ lent = k) => (~freed[k] \/ Design = "c") + +\* At most one answer reaches a request's worker. A later answer is told the +\* request no longer waits (`noPending`) and is never applied. +AnswerOnce == \A k \in Kids : answers[k] <= 1 + +\* A request whose turn the person typed is never noted to main, and so never +\* answered by main. +TypedStaysWithPerson == + \A k \in typed : k \notin posted /\ k \notin mail /\ k \notin seen + +\* An action runs only when main's own check allowed it, or the person allowed +\* it (RULES.md R4.3, with the person added). +Authority == \A k \in Kids : kid[k] = "ran" => k \in authorized + +\* Main's answer always finds the request its note named, while that request +\* still waits. +NoLostApprove == lost = {} + +\* In designs a and b main's screen never shows a parent-routed request: only a +\* turn the person typed may be lent. The trial lent any waiting request. +NoPersonPromptForParentRouted == + Design = "trial" \/ (\A k \in Kids : lent = k => k \in typed) + +============================================================================= diff --git a/tests/tla/subagent/check.sh b/tests/tla/subagent/check.sh index 8d0fcf9b5c..fe88b9d3b6 100755 --- a/tests/tla/subagent/check.sh +++ b/tests/tla/subagent/check.sh @@ -242,4 +242,27 @@ ParentApproval parent-approval-mutation-early-stall FallbackOnlyAfterSeen ParentApproval parent-approval-mutation-no-fallback deadlock ParentApproval parent-approval-mutation-note-lost deadlock ParentApproval parent-approval-mutation-no-nudge deadlock +# The TuiParentApproval configs: +# The trial (step 3b) and a must break: the trial breaks NoStaleLent (a lent +# copy outliving its wait), a breaks NoStalePrompt (the call frees its review). +# a2, b and c must pass; c is the code in this change (the prompt owns its +# copy, so NoStalePrompt holds by construction). +# lend_routed, free_anyway and note_typed each break the rule named on its row. +# Two defects have no config because they cannot fail: no_withdraw (one request +# per kid) and b_note_keeps_prompt (b's free guard waits on the prompt). +# The simulate pair runs under ideal and non-ideal conditions. +# +TuiParentApproval tui-approval-current-trial NoStaleLent +TuiParentApproval tui-approval-design-a NoStalePrompt +TuiParentApproval tui-approval-design-a-person NoStalePrompt +TuiParentApproval tui-approval-design-a2 - +TuiParentApproval tui-approval-design-a2-person - +TuiParentApproval tui-approval-design-b - +TuiParentApproval tui-approval-design-c - +TuiParentApproval tui-approval-design-b-person - +TuiParentApproval tui-approval-mutant-lend-routed NoPersonPromptForParentRouted +TuiParentApproval tui-approval-mutant-free-anyway NoStalePrompt +TuiParentApproval tui-approval-mutant-note-typed TypedStaysWithPerson +TuiParentApproval tui-approval-simulate-ideal simulate -simulate num=20000 -depth 20 -seed 1 +TuiParentApproval tui-approval-simulate-nonideal simulate -simulate num=20000 -depth 20 -seed 1 VERDICTS diff --git a/tests/tla/subagent/tui-approval-current-trial.cfg b/tests/tla/subagent/tui-approval-current-trial.cfg new file mode 100644 index 0000000000..28b54cdb30 --- /dev/null +++ b/tests/tla/subagent/tui-approval-current-trial.cfg @@ -0,0 +1,15 @@ +\* The reverted step 3b: the turn's prompter for a parent-started run and the +\* note, with lending still on (app_agents_runtime.zig:1270-1274) and main's +\* answer resolved off the loop (managed_owner.zig:1614-1634). A lent copy +\* outlives the request it shows. TLC must violate NoStaleLent. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "trial" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-a-person.cfg b/tests/tla/subagent/tui-approval-design-a-person.cfg new file mode 100644 index 0000000000..3e61b851f5 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-a-person.cfg @@ -0,0 +1,15 @@ +\* Design a with FailedNote = "person": a note that cannot be posted leaves the +\* request with the person instead of refusing it. The ordering that breaks +\* NoStalePrompt in design a is untouched by that choice, so TLC must still +\* violate NoStalePrompt: the note's own deny is applied off the loop. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a" + FailedNote = "person" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStalePrompt +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-a.cfg b/tests/tla/subagent/tui-approval-design-a.cfg new file mode 100644 index 0000000000..3f130eab8b --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-a.cfg @@ -0,0 +1,16 @@ +\* Design a: no lend of a parent-routed request, and main's answer resolved and +\* submitted in one step on main's thread, which the loop learns of only at its +\* next sync (app_worker_runtime.zig:809-830). The worker frees the review memory +\* as soon as its call has the answer, so the child's prompt still shows a +\* request whose memory is gone. TLC must violate NoStalePrompt. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStalePrompt +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-a2-person.cfg b/tests/tla/subagent/tui-approval-design-a2-person.cfg new file mode 100644 index 0000000000..e7fe787e74 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-a2-person.cfg @@ -0,0 +1,20 @@ +\* Design a2 with FailedNote = "person": a note that cannot be posted leaves +\* the request with the person, and the prompt clears when the person answers. +\* Every rule must hold. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "person" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-a2.cfg b/tests/tla/subagent/tui-approval-design-a2.cfg new file mode 100644 index 0000000000..d1940ee855 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-a2.cfg @@ -0,0 +1,19 @@ +\* Design a2: design a with one guard, that the worker frees the review memory +\* only once no screen shows the request. Every rule must hold. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-b-person.cfg b/tests/tla/subagent/tui-approval-design-b-person.cfg new file mode 100644 index 0000000000..e622781f21 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-b-person.cfg @@ -0,0 +1,20 @@ +\* Design b with FailedNote = "person": a note that cannot be posted leaves the +\* request with the person, whose answer is the loop's own step. Every rule must +\* hold. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "b" + FailedNote = "person" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-b.cfg b/tests/tla/subagent/tui-approval-design-b.cfg new file mode 100644 index 0000000000..83b6d57e27 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-b.cfg @@ -0,0 +1,21 @@ +\* Design b: main's answer is handed to the loop, which clears the child's +\* prompt and any lent copy in the step that submits (input_approval_runtime.zig: +\* 257-274), so no screen holds a request whose memory is freed. Every rule +\* must hold. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "b" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-design-c.cfg b/tests/tla/subagent/tui-approval-design-c.cfg new file mode 100644 index 0000000000..8fd95bd515 --- /dev/null +++ b/tests/tla/subagent/tui-approval-design-c.cfg @@ -0,0 +1,23 @@ +\* Design c: the prompt takes its copy of the review under the worker's mutex, +\* while the request still waits, main's answer is resolved on main's thread, +\* the person's answer withdraws the binding, and a failed note refuses. Design +\* b: main's answer is handed to the loop, which clears the child's prompt and +\* any lent copy in the step that submits (input_approval_runtime.zig:257-274), +\* so no screen holds a request whose memory is freed. Every rule must hold. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "c" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-mutant-free-anyway.cfg b/tests/tla/subagent/tui-approval-mutant-free-anyway.cfg new file mode 100644 index 0000000000..d81498fbbf --- /dev/null +++ b/tests/tla/subagent/tui-approval-mutant-free-anyway.cfg @@ -0,0 +1,14 @@ +\* Planted defect free_anyway in design a2: the worker frees the review memory +\* without waiting for the loop to clear the prompt, so a2's guard is gone and +\* the prompt outlives its memory. TLC must violate NoStalePrompt. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "free_anyway" +INVARIANTS + TypeOK + NoStalePrompt +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-mutant-lend-routed.cfg b/tests/tla/subagent/tui-approval-mutant-lend-routed.cfg new file mode 100644 index 0000000000..4f69e2b5f8 --- /dev/null +++ b/tests/tla/subagent/tui-approval-mutant-lend-routed.cfg @@ -0,0 +1,14 @@ +\* Planted defect lend_routed in design a2: the instance's screen lends a +\* parent-routed request, which the person's spec says it must not show. TLC +\* must violate NoPersonPromptForParentRouted. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "lend_routed" +INVARIANTS + TypeOK + NoPersonPromptForParentRouted +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-mutant-note-typed.cfg b/tests/tla/subagent/tui-approval-mutant-note-typed.cfg new file mode 100644 index 0000000000..69e23301e9 --- /dev/null +++ b/tests/tla/subagent/tui-approval-mutant-note-typed.cfg @@ -0,0 +1,14 @@ +\* Planted defect note_typed in design a2: a turn the person typed registers its +\* request and is noted to main, so a request that must stay with the person +\* reaches main. TLC must violate TypedStaysWithPerson. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "note_typed" +INVARIANTS + TypeOK + TypedStaysWithPerson +CHECK_DEADLOCK TRUE diff --git a/tests/tla/subagent/tui-approval-simulate-ideal.cfg b/tests/tla/subagent/tui-approval-simulate-ideal.cfg new file mode 100644 index 0000000000..cfc53db485 --- /dev/null +++ b/tests/tla/subagent/tui-approval-simulate-ideal.cfg @@ -0,0 +1,18 @@ +\* Ideal conditions: design a2, notes post, the registry has room, and no defect +\* is planted. Random behaviors must find no error. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "a2" + FailedNote = "refuse" + RegistryFull = FALSE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted diff --git a/tests/tla/subagent/tui-approval-simulate-nonideal.cfg b/tests/tla/subagent/tui-approval-simulate-nonideal.cfg new file mode 100644 index 0000000000..1e0380f8b1 --- /dev/null +++ b/tests/tla/subagent/tui-approval-simulate-nonideal.cfg @@ -0,0 +1,19 @@ +\* Non-ideal conditions: design b, a note that cannot post leaves the request +\* with the person, and the registry is already full, so a parent-started child +\* is refused at once. Random behaviors must find no error. +SPECIFICATION Spec +CONSTANTS + Kids = {"k1", "k2"} + Design = "b" + FailedNote = "person" + RegistryFull = TRUE + Mutant = "none" +INVARIANTS + TypeOK + NoStaleLent + NoStalePrompt + AnswerOnce + TypedStaysWithPerson + Authority + NoLostApprove + NoPersonPromptForParentRouted