diff --git a/src/core/agent/worker_runtime.zig b/src/core/agent/worker_runtime.zig index 44ad9b89..23cf6f91 100644 --- a/src/core/agent/worker_runtime.zig +++ b/src/core/agent/worker_runtime.zig @@ -93,6 +93,7 @@ pub const ActivePromptSnapshotOwnership = struct { state: enum { active, handed_off, + preserved, discarded, } = .active, shared_ownership: ?types.SnapshotFileOwnership = null, @@ -122,6 +123,23 @@ pub const ActivePromptSnapshotOwnership = struct { return ownership; } + fn preserve(self: *ActivePromptSnapshotOwnership) bool { + if (self.images.len == 0) return false; + switch (self.state) { + .active => { + if (self.shared_ownership) |ownership| ownership.transfer(); + self.state = .preserved; + return true; + }, + .handed_off => { + if (self.shared_ownership) |ownership| ownership.transfer(); + return true; + }, + .preserved => return true, + .discarded => return false, + } + } + fn deinit(self: *ActivePromptSnapshotOwnership) void { if (self.state == .active) { if (self.shared_ownership) |ownership| { @@ -185,6 +203,36 @@ const SnapshotFileOwnershipState = struct { } }; +fn historyTurnImages(turn: types.HistoryTurn) []const types.ImageAttachment { + return switch (turn) { + .assistant => |value| value.user.images, + .background_command => |value| value.user.images, + .interrupted => |value| value.user.images, + .compacted_summary => &.{}, + }; +} + +fn sameImageSnapshots( + left: []const types.ImageAttachment, + right: []const types.ImageAttachment, +) bool { + if (left.len == 0 or left.len != right.len) return false; + for (left) |image| { + const other = image_attachments.findById(right, image.id) orelse return false; + if (!optionalBytesEqual(image.snapshot_path, other.snapshot_path) or + !optionalBytesEqual(image.snapshot_sha256, other.snapshot_sha256)) + { + return false; + } + } + return true; +} + +fn optionalBytesEqual(left: ?[]const u8, right: ?[]const u8) bool { + if (left == null or right == null) return left == null and right == null; + return std.mem.eql(u8, left.?, right.?); +} + pub const PermissionSnapshot = struct { mode: types.PermissionMode, }; @@ -1331,6 +1379,8 @@ pub const WorkerRuntime = struct { self: *WorkerRuntime, ownership: *ActivePromptSnapshotOwnership, ) void { + self.worker_mutex.lockUncancelable(io_mod.getIo()); + defer self.worker_mutex.unlock(io_mod.getIo()); std.debug.assert(self.active_prompt_snapshot_ownership == null); self.active_prompt_snapshot_ownership = ownership; } @@ -1339,6 +1389,8 @@ pub const WorkerRuntime = struct { self: *WorkerRuntime, alloc: std.mem.Allocator, ) !?types.SnapshotFileOwnership { + self.worker_mutex.lockUncancelable(io_mod.getIo()); + defer self.worker_mutex.unlock(io_mod.getIo()); const ownership = self.active_prompt_snapshot_ownership orelse return null; return ownership.handoff(alloc); } @@ -1347,11 +1399,43 @@ pub const WorkerRuntime = struct { self: *WorkerRuntime, ownership: *ActivePromptSnapshotOwnership, ) void { + self.worker_mutex.lockUncancelable(io_mod.getIo()); + defer self.worker_mutex.unlock(io_mod.getIo()); std.debug.assert(self.active_prompt_snapshot_ownership == ownership); self.active_prompt_snapshot_ownership = null; ownership.deinit(); } + /// Relinquishes deletion for the matching active or finished prompt. The + /// caller must already have established another owner for these files. + pub fn preservePromptSnapshots( + self: *WorkerRuntime, + turn_id: u64, + images: []const types.ImageAttachment, + ) bool { + if (turn_id == 0 or images.len == 0) return false; + self.worker_mutex.lockUncancelable(io_mod.getIo()); + defer self.worker_mutex.unlock(io_mod.getIo()); + + var preserved = false; + if (self.active_turn_id == turn_id) { + if (self.active_prompt_snapshot_ownership) |ownership| { + preserved = ownership.preserve(); + } + } + for (self.worker_events.items) |*event| { + if (event.* != .finish_prompt) continue; + const finished = &event.finish_prompt; + const finished_images = historyTurnImages(finished.turn); + if (!sameImageSnapshots(finished_images, images)) continue; + if (finished.snapshot_file_ownership) |ownership| { + ownership.transfer(); + preserved = true; + } + } + return preserved; + } + pub fn propagateGrant(self: *WorkerRuntime, alloc: std.mem.Allocator, tool_name: []const u8, target_path: []const u8) !void { self.worker_mutex.lockUncancelable(io_mod.getIo()); defer self.worker_mutex.unlock(io_mod.getIo()); @@ -2011,6 +2095,55 @@ test "active prompt snapshot ownership discards every pre-transfer boundary" { } } +test "session transfer preserves active and finished prompt snapshots" { + const alloc = std.testing.allocator; + for ([_]bool{ false, true }) |finished_before_transfer| { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const name = if (finished_before_transfer) "finished.bin" else "active.bin"; + { + var file = try tmp.dir.createFile(std.testing.io, name, .{}); + defer file.close(std.testing.io); + try file.writeStreamingAll(std.testing.io, "snapshot"); + } + const path = try io_mod.dirRealpathAlloc(alloc, tmp.dir, name); + defer alloc.free(path); + const images = [_]types.ImageAttachment{.{ + .id = 1, + .path = @constCast("/tmp/source.png"), + .media_type = @constCast("image/png"), + .snapshot_path = path, + .snapshot_sha256 = @constCast("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), + }}; + + var runtime = WorkerRuntime{}; + defer runtime.deinit(alloc); + runtime.active_turn_id = 41; + var active = ActivePromptSnapshotOwnership.init(&images); + runtime.beginActivePromptSnapshots(&active); + if (finished_before_transfer) { + const ownership = (try runtime.handoffActivePromptSnapshots(alloc)) orelse + return error.TestExpectedSnapshotOwnership; + try runtime.pushEvent(alloc, .{ .finish_prompt = .{ + .turn = .{ .assistant = .{ + .user = .{ .text = @constCast("prompt"), .images = @constCast(&images) }, + .assistant = @constCast("done"), + } }, + .snapshot_file_ownership = ownership, + } }); + ownership.release(); + runtime.endActivePromptSnapshots(&active); + runtime.active_turn_id = 0; + } + + try std.testing.expect(runtime.preservePromptSnapshots(41, &images)); + if (!finished_before_transfer) runtime.endActivePromptSnapshots(&active); + runtime.discardEvents(alloc); + try std.Io.Dir.accessAbsolute(std.testing.io, path, .{}); + try std.Io.Dir.deleteFileAbsolute(std.testing.io, path); + } +} + test "accepted active prompt ownership does not delete history files" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); diff --git a/src/core/app/app_input_runtime.zig b/src/core/app/app_input_runtime.zig index 72999391..c38e992a 100644 --- a/src/core/app/app_input_runtime.zig +++ b/src/core/app/app_input_runtime.zig @@ -10772,6 +10772,8 @@ const FakeSubmitApp = struct { hold_available: bool = false, held: bool = false, queued_turn_id: ?u64 = null, + queued_images: []types.ImageAttachment = &.{}, + queued_images_alloc: ?std.mem.Allocator = null, pub fn queuedPromptCount(_: *@This()) usize { return 0; @@ -10791,13 +10793,47 @@ const FakeSubmitApp = struct { self: *@This(), _: std.mem.Allocator, turn_id: u64, - _: []const types.ImageAttachment, + retained_images: []const types.ImageAttachment, ) bool { if (self.queued_turn_id != turn_id) return false; + image_attachments.deleteUnreferencedImageSnapshots( + self.queued_images, + retained_images, + ); + self.freeQueuedImageMetadata(); self.queued_turn_id = null; return true; } + pub fn clearQueuedPrompts( + self: *@This(), + _: std.mem.Allocator, + retained_images: []const types.ImageAttachment, + ) void { + image_attachments.deleteUnreferencedImageSnapshots( + self.queued_images, + retained_images, + ); + self.freeQueuedImageMetadata(); + self.queued_turn_id = null; + } + + fn freeQueuedImageMetadata(self: *@This()) void { + if (self.queued_images_alloc) |alloc| { + types.freeImageAttachmentSlice(alloc, self.queued_images); + } + self.queued_images = &.{}; + self.queued_images_alloc = null; + } + + pub fn preservePromptSnapshots( + _: *@This(), + _: u64, + _: []const types.ImageAttachment, + ) bool { + return false; + } + pub fn activeTurnId(_: *const @This()) u64 { return 0; } @@ -10867,6 +10903,7 @@ const FakeSubmitApp = struct { types.freeImageAttachmentSlice(self.alloc, self.last_images); self.clearLastSkillTokens(); self.last_skill_tokens.deinit(self.alloc); + self.worker.freeQueuedImageMetadata(); } pub fn writeDomainNotice(self: *FakeSubmitApp, notice: types.SemanticNotice, _: bool) !void { @@ -10941,6 +10978,12 @@ const FakeSubmitApp = struct { if (self.fail_pending_finalization) { return error.InjectedPendingFinalizationFailure; } + self.worker.freeQueuedImageMetadata(); + self.worker.queued_images = try types.dupeImageAttachmentSlice( + self.alloc, + draft.images, + ); + self.worker.queued_images_alloc = self.alloc; self.worker.queued_turn_id = draft.turn_id; } @@ -12377,9 +12420,8 @@ test "app_input_runtime terminal pending cleanup preserves image history" { } if (case.session_transition) { - PendingRuntime.clearPendingSubmission(&app, "session_transition"); + PendingRuntime.clearPendingSubmissionForSessionTransition(&app); app.input_runtime.inputResetState().resetForSession(alloc); - app.worker.queued_turn_id = null; } else { try std.testing.expect(PendingRuntime.cancelPendingSubmission(&app)); } diff --git a/src/core/app/app_session_runtime.zig b/src/core/app/app_session_runtime.zig index 0917d309..991a5fe5 100644 --- a/src/core/app/app_session_runtime.zig +++ b/src/core/app/app_session_runtime.zig @@ -1531,10 +1531,14 @@ pub fn Runtime(comptime App: type) type { if (comptime @hasField(App, "queued_prompt_review")) { input_queue_runtime.Runtime(App).reset(app); } - if (comptime @hasDecl(App, "clearPendingSubmission")) { - App.clearPendingSubmission(app, "session_transition"); + if (comptime @hasDecl(App, "clearPendingSubmissionForSessionTransition")) { + App.clearPendingSubmissionForSessionTransition(app); + } else { + if (comptime @hasDecl(App, "clearPendingSubmission")) { + App.clearPendingSubmission(app, "session_transition"); + } + app.worker.clearQueuedPrompts(std.heap.c_allocator, &.{}); } - app.worker.clearQueuedPrompts(std.heap.c_allocator, &.{}); } fn applyIdleLiveSessionTransition( diff --git a/src/core/app/input_submit_runtime.zig b/src/core/app/input_submit_runtime.zig index 2e70f9ec..88562c6f 100644 --- a/src/core/app/input_submit_runtime.zig +++ b/src/core/app/input_submit_runtime.zig @@ -281,6 +281,46 @@ pub fn SubmitRuntime(comptime App: type) type { clearPendingSubmissionWithSnapshots(app, reason, snapshot_cleanup); } + pub fn clearPendingSubmissionForSessionTransition(app: *App) void { + if (comptime !@hasField(App, "submission")) { + app.worker.clearQueuedPrompts(std.heap.c_allocator, &.{}); + return; + } + const pending = app.submission.pending orelse { + app.worker.clearQueuedPrompts(std.heap.c_allocator, &.{}); + return; + }; + const history_owns_snapshots = + transferPendingImageSnapshotsToComposerHistory(app); + if (pending.phase == .queued) { + if (history_owns_snapshots) { + if (comptime @hasDecl(@TypeOf(app.worker), "preservePromptSnapshots")) { + _ = app.worker.preservePromptSnapshots( + pending.draft.turn_id, + pending.draft.images, + ); + } + } + app.worker.clearQueuedPrompts( + std.heap.c_allocator, + if (history_owns_snapshots) pending.draft.images else &.{}, + ); + clearPendingSubmissionWithSnapshots( + app, + "session_transition", + .preserve, + ); + return; + } + + app.worker.clearQueuedPrompts(std.heap.c_allocator, &.{}); + clearPendingSubmissionWithSnapshots( + app, + "session_transition", + if (history_owns_snapshots) .preserve else .discard, + ); + } + fn clearPendingSubmissionWithSnapshots( app: *App, reason: []const u8, diff --git a/src/main.zig b/src/main.zig index 4c99f80a..0978b5a3 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1160,6 +1160,10 @@ const App = struct { InputSubmitRuntime.clearPendingSubmission(self, reason); } + pub fn clearPendingSubmissionForSessionTransition(self: *App) void { + InputSubmitRuntime.clearPendingSubmissionForSessionTransition(self); + } + pub fn writeUserPromptCard(self: *App, user: types.UserTurn) !void { try self.writeUserPromptCardWithSpacing(user, self.session.historyLen() > 0); }