From 5fdf87508119ac82561981ed0eb388c2732df42e Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:31:09 -0300 Subject: [PATCH 1/6] refactor(global-chat): add seams for saves, provider choice and card typing --- MobileChat/CompanionWire.swift | 4 ++ Sources/GlobalChatCards.swift | 60 +++++++++++------ Sources/GlobalChatController.swift | 100 ++++++++++++++++++++--------- 3 files changed, 112 insertions(+), 52 deletions(-) diff --git a/MobileChat/CompanionWire.swift b/MobileChat/CompanionWire.swift index dc6915ae..b65c8ad4 100644 --- a/MobileChat/CompanionWire.swift +++ b/MobileChat/CompanionWire.swift @@ -56,6 +56,10 @@ nonisolated struct MobileChatSnapshot: Codable, Sendable { nonisolated enum GlobalChatProvider: String, CaseIterable, Codable, Sendable { case codex, claude + func canSelect(_ provider: Self, ownerChoice: Bool?) -> Bool { + provider != self + } + var title: String { switch self { case .codex: "Codex" diff --git a/Sources/GlobalChatCards.swift b/Sources/GlobalChatCards.swift index 56263539..0aa88375 100644 --- a/Sources/GlobalChatCards.swift +++ b/Sources/GlobalChatCards.swift @@ -14,10 +14,11 @@ final class GlobalChatCards { enum Choice { /// The option was typed into the agent's terminal. - case sent(text: String, workspaceID: UUID, surfaceID: UUID) + case sent /// The card settled without typing, with the reason on the card. case settled case stale + case storageFailed } enum AskResult { @@ -335,7 +336,10 @@ final class GlobalChatCards { /// at that commit with every check passed, the terminal still runs the same agent, /// `isAuthorized` still holds for whoever pressed it, and `allowsTyping` holds right before /// the keystrokes, with nothing awaited in between. - func ship(_ id: UUID, isAuthorized: GlobalChatAuthorization, allowsTyping: @MainActor () -> Bool) async -> Choice { + func ship( + _ id: UUID, isAuthorized: GlobalChatAuthorization, allowsTyping: @MainActor () -> Bool, + record: (String, UUID, UUID) -> Bool + ) async -> Choice { guard !shipsInFlight.contains(id), let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ship(ship) = entry.card.content else { return .stale } guard let binding = self.binding(for: entry, ship: ship), let repoSlug = entry.repoSlug else { @@ -371,10 +375,12 @@ final class GlobalChatCards { } let reply = String(localized: "global.ship.reply", defaultValue: "Pull request #\(number) passed its checks. Merge it now with: gh pr merge \(number) --repo \(repoSlug) --match-head-commit \(headSHA)") guard allowsTyping() else { return .stale } - guard let prepared = workspaces.prepare(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID, text: reply), - workspaces.deliver(prepared) else { return .stale } - settle(id, as: .answered(choice: Self.shipChoice)) - return .sent(text: reply, workspaceID: ship.workspaceID, surfaceID: ship.surfaceID) + guard let prepared = workspaces.prepare(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID, text: reply) else { return .stale } + return Self.submit(prepared, record: { _ in record(reply, ship.workspaceID, ship.surfaceID) }) { action in + guard workspaces.deliver(action) else { return false } + settle(id, as: .answered(choice: Self.shipChoice)) + return true + } } private static func isSameAgent(_ lhs: AgentSessionKey, _ rhs: AgentSessionKey) -> Bool { @@ -464,23 +470,37 @@ final class GlobalChatCards { /// The owner picked an option. It is typed only into the same terminal, to the same agent /// session, while that agent waits at its prompt; otherwise the card says why it was not sent. - func choose(_ id: UUID, option: Int) -> Choice { + func choose(_ id: UUID, option: Int, record: (String, UUID, UUID) -> Bool) -> Choice { guard let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ask(ask) = entry.card.content, ask.options.indices.contains(option) else { return .stale } let choice = ask.options[option] - let failure: GlobalChatCardFailure? = { - guard let target = workspaces.askTarget(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID) else { - return .terminalClosed - } - guard let current = target.session, let asked = entry.boundSession, Self.isSameAgent(current, asked) else { - return .agentChanged - } - guard let prepared = workspaces.prepare(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID, text: choice), - workspaces.deliver(prepared) else { return .notWaiting } - return nil - }() - settle(id, as: failure.map { .failed($0) } ?? .answered(choice: choice)) - return failure == nil ? .sent(text: choice, workspaceID: ask.workspaceID, surfaceID: ask.surfaceID) : .settled + func reject(_ failure: GlobalChatCardFailure) -> Choice { + settle(id, as: .failed(failure)) + return .settled + } + guard let target = workspaces.askTarget(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID) else { + return reject(.terminalClosed) + } + guard let current = target.session, let asked = entry.boundSession, Self.isSameAgent(current, asked) else { + return reject(.agentChanged) + } + guard let prepared = workspaces.prepare(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID, text: choice) else { + return reject(.notWaiting) + } + let result = Self.submit(prepared, record: { _ in record(choice, ask.workspaceID, ask.surfaceID) }) { action in + guard workspaces.deliver(action) else { return false } + settle(id, as: .answered(choice: choice)) + return true + } + if case .stale = result { return reject(.notWaiting) } + return result + } + + nonisolated static func submit( + _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool + ) -> Choice { + guard deliver(action) else { return .stale } + return record(action) ? .sent : .storageFailed } /// Drops the oldest settled cards past the count and size limits. Open cards are never dropped. diff --git a/Sources/GlobalChatController.swift b/Sources/GlobalChatController.swift index d76e5fed..1360d23c 100644 --- a/Sources/GlobalChatController.swift +++ b/Sources/GlobalChatController.swift @@ -121,7 +121,7 @@ final class GlobalChatController { if FileManager.default.fileExists(atPath: historyFile.path) { try Self.validateHistoryFile(historyFile) let data = try Data(contentsOf: historyFile) - history = try JSONDecoder().decode(History.self, from: data) + history = try Self.decodeHistory(data) turn = .idle(history.interruptedTurn == nil ? nil : .unavailable) } else { history = History() @@ -164,20 +164,37 @@ final class GlobalChatController { } /// Whether a turn may run the other provider when the stored one is signed out or missing. - static func canFallBack(_ history: History) -> Bool { + nonisolated static func canFallBack(_ history: History) -> Bool { // Codex is the default, so a history set to Claude without the flag was the user's choice. !(history.providerChosen ?? (history.provider != .codex)) } + nonisolated static func decodeHistory(_ data: Data) throws -> History { + try JSONDecoder().decode(History.self, from: data) + } + /// The history's provider fields once `used` answered a turn. A fallback is marked as not chosen, so a later turn /// may still fall back. - static func answered(_ history: History, by used: GlobalChatProvider) -> History { + nonisolated static func answered(_ history: History, by used: GlobalChatProvider) -> History { var updated = history if used != history.provider { updated.providerChosen = false } updated.provider = used return updated } + nonisolated static func selectingProvider( + _ provider: GlobalChatProvider, handoff: String, in history: History + ) -> History? { + guard history.provider.canSelect(provider, ownerChoice: history.providerChosen) else { return nil } + var updated = history + updated.providerChosen = true + updated.providerRevision = UUID() + updated.provider = provider + updated.sessionID = nil + updated.handoff = handoff.trimmingCharacters(in: .whitespacesAndNewlines) + return updated + } + /// Async only for Ship, which asks GitHub before typing; every other request answers at once. /// `isAuthorized` is asked again after Ship's GitHub check, and `allowsTyping` after that, on /// the main actor with nothing awaited before the keystrokes. A message's turn asks both again @@ -220,13 +237,7 @@ final class GlobalChatController { guard providerRevision == history.providerRevision else { return .failure(.stale) } guard case .idle = turn else { return .failure(.busy) } guard handoff.utf8.count <= 4_000 else { return .failure(.invalid) } - guard provider != history.provider else { return .snapshot(snapshot()) } - var updated = history - updated.provider = provider - updated.providerChosen = true - updated.providerRevision = UUID() - updated.sessionID = nil - updated.handoff = handoff.trimmingCharacters(in: .whitespacesAndNewlines) + guard var updated = Self.selectingProvider(provider, handoff: handoff, in: history) else { return .snapshot(snapshot()) } remember(id, in: &updated) guard store(updated) else { return .failure(.storage) } cards.supersedeProposals() @@ -259,7 +270,7 @@ final class GlobalChatController { turn = .stopping(id, saved: store(updated)) } case let .choose(cardID, option): - return respond(to: cards.choose(cardID, option: option)) + return respond(to: cards.choose(cardID, option: option, record: recordActivity)) case let .deliver(actionID): if let scheduled = GlobalChatUsageLimits.shared.resume(actionID) { return scheduled ? .snapshot(snapshot()) : .failure(.stale) } if let delivery = history.deliveries[actionID] { @@ -271,7 +282,10 @@ final class GlobalChatController { case let .task(task): guard case .granted = task.source else { return updateRequired(task) } return start(task) - case .ship: return respond(to: await cards.ship(actionID, isAuthorized: isAuthorized, allowsTyping: allowsTyping)) + case .ship: + return respond(to: await cards.ship( + actionID, isAuthorized: isAuthorized, allowsTyping: allowsTyping, record: recordActivity + )) case let .followUp(action): return deliver(action) case .ask, .unsupported: return .failure(.stale) } @@ -311,9 +325,8 @@ final class GlobalChatController { private func respond(to choice: GlobalChatCards.Choice) -> GlobalChatResponse { switch choice { case .stale: return .failure(.stale) - case .settled: return .snapshot(snapshot()) - case let .sent(text, workspaceID, surfaceID): - return recordActivity(text, workspaceID: workspaceID, surfaceID: surfaceID) ? .snapshot(snapshot()) : .failure(.storage) + case .settled, .sent: return .snapshot(snapshot()) + case .storageFailed: return .failure(.storage) } } @@ -1157,26 +1170,49 @@ final class GlobalChatController { updated.operations = Array(updated.operations.suffix(1_024)) let retained = Set(updated.operations) updated.deliveries = updated.deliveries.filter { retained.contains($0.key) } + guard let saved = Self.persist(updated, storage: &storage, write: writeHistory) else { return false } + history = saved + return true + } + + nonisolated static func persist( + _ history: History, retaining replies: [GlobalChatMessage] = [], storage: inout GlobalChatStorageHealth, + write: (History) throws -> Void + ) -> History? { do { - try Self.prepareStorage(directory) - let encoded = try JSONEncoder().encode(updated) - guard encoded.count <= Self.maximumHistoryBytes else { throw StorageError.archiveRequired } - let staged = directory.appendingPathComponent(UUID().uuidString) - defer { try? FileManager.default.removeItem(at: staged) } - guard FileManager.default.createFile(atPath: staged.path, contents: encoded, attributes: [.posixPermissions: 0o600]) else { - throw StorageError.unsafe - } - if FileManager.default.fileExists(atPath: historyFile.path) { - try Self.validateHistoryFile(historyFile) - _ = try FileManager.default.replaceItemAt(historyFile, withItemAt: staged) - } else { - try FileManager.default.moveItem(at: staged, to: historyFile) - } - history = updated + try write(history) storage.saveSucceeded() - return true + return history } catch { - return false + return nil + } + } + + private nonisolated static func mergingReplies(_ replies: [GlobalChatMessage], into history: History) -> History { + guard !replies.isEmpty else { return history } + var updated = history + var ids = Set(updated.messages.map(\.id)) + for reply in replies where ids.insert(reply.id).inserted { + let index = updated.messages.lastIndex { $0.date <= reply.date }.map { $0 + 1 } ?? 0 + updated.messages.insert(reply, at: index) + } + return updated + } + + private func writeHistory(_ updated: History) throws { + try Self.prepareStorage(directory) + let encoded = try JSONEncoder().encode(updated) + guard encoded.count <= Self.maximumHistoryBytes else { throw StorageError.archiveRequired } + let staged = directory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: staged) } + guard FileManager.default.createFile(atPath: staged.path, contents: encoded, attributes: [.posixPermissions: 0o600]) else { + throw StorageError.unsafe + } + if FileManager.default.fileExists(atPath: historyFile.path) { + try Self.validateHistoryFile(historyFile) + _ = try FileManager.default.replaceItemAt(historyFile, withItemAt: staged) + } else { + try FileManager.default.moveItem(at: staged, to: historyFile) } } From df0edcfa68ae5f766c707b2baba45375713db473 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:31:16 -0300 Subject: [PATCH 2/6] test(global-chat): cover unsaved replies, legacy provider history, fallback choice and card saves --- programaTests/GlobalChatDispatchTests.swift | 100 ++++++++++++++++++-- 1 file changed, 90 insertions(+), 10 deletions(-) diff --git a/programaTests/GlobalChatDispatchTests.swift b/programaTests/GlobalChatDispatchTests.swift index 94bef4c6..82a1719e 100644 --- a/programaTests/GlobalChatDispatchTests.swift +++ b/programaTests/GlobalChatDispatchTests.swift @@ -239,6 +239,38 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertFalse(storage.gatesRequests) } + func testAnUnsavedProviderReplySurvivesUntilItIsWrittenWithNewerMessages() throws { + let messages = conversation(4) + let owner = messages[0], newer = messages[3] + let reply = GlobalChatMessage(id: messages[1].id, role: .assistant, text: "Reply", date: messages[1].date) + let note = messages[2] + var storage = GlobalChatStorageHealth() + var completed = GlobalChatController.History() + completed.messages = [owner, reply, note] + XCTAssertNil(GlobalChatController.persist(completed, retaining: [reply, note], storage: &storage) { _ in + throw CocoaError(.fileWriteNoPermission) + }) + XCTAssertEqual(storage.issue, .storage) + + var latest = GlobalChatController.History() + let recorded = GlobalChatMessage(id: note.id, role: .assistant, text: "Recorded note", date: note.date) + latest.messages = [owner, recorded, newer] + latest.sessionID = "newer-session" + XCTAssertNil(GlobalChatController.persist(latest, storage: &storage) { candidate in + XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) + throw CocoaError(.fileWriteNoPermission) + }) + XCTAssertEqual(storage.issue, .storage) + + let saved = try XCTUnwrap(GlobalChatController.persist(latest, storage: &storage) { candidate in + XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) + XCTAssertEqual(candidate.messages.map(\.text), [owner.text, reply.text, recorded.text, newer.text]) + XCTAssertEqual(candidate.sessionID, latest.sessionID) + }) + XCTAssertEqual(saved.messages.map(\.id), messages.map(\.id)) + XCTAssertNil(storage.issue) + } + @MainActor func testAnAutomaticFallbackLeavesTheNextTurnFreeToFallBack() { let history = GlobalChatController.History() @@ -248,18 +280,66 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertTrue(GlobalChatController.canFallBack(answered), "a fallback is not the owner's choice") } - @MainActor - func testAClaudeHistorySavedWithoutTheFlagStaysTheOwnersChoice() throws { + func testAClaudeHistorySavedWithoutAnOwnerChoiceUsesTheDefaultProvider() throws { var old = GlobalChatController.History() old.provider = .claude - old.providerChosen = nil - let data = try JSONEncoder().encode(old) - XCTAssertFalse(String(decoding: data, as: UTF8.self).contains("providerChosen")) - let decoded = try JSONDecoder().decode(GlobalChatController.History.self, from: data) - XCTAssertFalse(GlobalChatController.canFallBack(decoded)) - let answered = GlobalChatController.answered(decoded, by: .claude) - XCTAssertNil(answered.providerChosen, "a turn the stored provider answered changes nothing") - XCTAssertFalse(GlobalChatController.canFallBack(answered)) + old.sessionID = "claude-session" + old.messages = conversation(1) + let legacy = try GlobalChatController.decodeHistory(JSONEncoder().encode(old)) + XCTAssertEqual(legacy.provider, .codex) + XCTAssertNil(legacy.providerChosen) + XCTAssertNil(legacy.sessionID) + XCTAssertEqual(legacy.messages.map(\.id), old.messages.map(\.id)) + XCTAssertTrue(GlobalChatController.canFallBack(legacy)) + + old.providerChosen = true + let chosen = try GlobalChatController.decodeHistory(JSONEncoder().encode(old)) + XCTAssertEqual(chosen.provider, .claude) + XCTAssertEqual(chosen.sessionID, old.sessionID) + XCTAssertFalse(GlobalChatController.canFallBack(chosen)) + } + + func testTheOwnerCanChooseTheCurrentFallbackProvider() throws { + var history = GlobalChatController.answered(.init(), by: .claude) + history.sessionID = "fallback-session" + XCTAssertTrue(history.provider.canSelect(.claude, ownerChoice: history.providerChosen)) + let chosen = try XCTUnwrap(GlobalChatController.selectingProvider(.claude, handoff: "", in: history)) + XCTAssertEqual(chosen.provider, .claude) + XCTAssertEqual(chosen.providerChosen, true) + XCTAssertEqual(chosen.sessionID, history.sessionID) + XCTAssertNotEqual(chosen.providerRevision, history.providerRevision) + XCTAssertFalse(GlobalChatController.canFallBack(chosen)) + XCTAssertFalse(chosen.provider.canSelect(.claude, ownerChoice: chosen.providerChosen)) + } + + func testChooseAndShipRequireARecordedTranscriptBeforeTyping() { + let action = GlobalChatAction( + id: UUID(), workspaceID: UUID(), surfaceID: UUID(), + workspaceTitle: "Workspace", surfaceTitle: "Agent", text: "Yes" + ) + var calls: [String] = [] + let failed = GlobalChatCards.submit(action, record: { _ in + calls.append("record") + return false + }, deliver: { _ in + calls.append("deliver") + return true + }) + guard case .storageFailed = failed else { return XCTFail("Expected a storage failure") } + XCTAssertEqual(calls, ["record"]) + + calls.removeAll() + let sent = GlobalChatCards.submit(action, record: { + XCTAssertEqual($0.id, action.id) + calls.append("record") + return true + }, deliver: { + XCTAssertEqual($0.id, action.id) + calls.append("deliver") + return true + }) + guard case .sent = sent else { return XCTFail("Expected delivery after the save") } + XCTAssertEqual(calls, ["record", "deliver"]) } private func conversation(_ count: Int) -> [GlobalChatMessage] { From e7ad4defc482f3aee1e6ffbf75c5262984dd6745 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:31:21 -0300 Subject: [PATCH 3/6] fix(global-chat): keep unsaved replies, stop legacy fallbacks reading as a choice, allow confirming a fallback, save before cards type --- MobileChat/CompanionWire.swift | 3 +- MobileChat/GlobalChatScreen.swift | 38 ++++++++++--------- Sources/GlobalChatCards.swift | 27 +++++++------- Sources/GlobalChatController.swift | 60 ++++++++++++++++++------------ Sources/GlobalChatDispatch.swift | 26 +++++++++---- 5 files changed, 91 insertions(+), 63 deletions(-) diff --git a/MobileChat/CompanionWire.swift b/MobileChat/CompanionWire.swift index b65c8ad4..50b6ba21 100644 --- a/MobileChat/CompanionWire.swift +++ b/MobileChat/CompanionWire.swift @@ -57,7 +57,7 @@ nonisolated enum GlobalChatProvider: String, CaseIterable, Codable, Sendable { case codex, claude func canSelect(_ provider: Self, ownerChoice: Bool?) -> Bool { - provider != self + provider != self || ownerChoice == false } var title: String { @@ -330,6 +330,7 @@ nonisolated struct GlobalChatSnapshot: Codable, Sendable { /// Events above `seenThrough` that are already seen. Nil from a host that only keeps the cursor. var seenIDs: [Int64]? = nil let provider: GlobalChatProvider + var providerChoice: Bool? = nil let providerRevision: UUID let persona: GlobalChatPersona? var identity: GlobalChatIdentity? = nil diff --git a/MobileChat/GlobalChatScreen.swift b/MobileChat/GlobalChatScreen.swift index b66ee35a..83f3c12c 100644 --- a/MobileChat/GlobalChatScreen.swift +++ b/MobileChat/GlobalChatScreen.swift @@ -296,15 +296,7 @@ struct GlobalChatScreen: View { } Spacer() Menu { - ForEach(GlobalChatProvider.allCases, id: \.self) { provider in - Button { - beginHandoff(to: provider, snapshot: snapshot) - } label: { - if snapshot.provider == provider { Label(provider.title, systemImage: "checkmark") } - else { Text(verbatim: provider.title) } - } - .disabled(snapshot.provider == provider) - } + providerOptions(snapshot) } label: { Label(snapshot.provider.title, systemImage: "cpu") } @@ -331,6 +323,18 @@ struct GlobalChatScreen: View { .padding(.vertical, 10) } + private func providerOptions(_ snapshot: GlobalChatSnapshot) -> some View { + ForEach(GlobalChatProvider.allCases, id: \.self) { provider in + Button { + beginHandoff(to: provider, snapshot: snapshot) + } label: { + if snapshot.provider == provider { Label(provider.title, systemImage: "checkmark") } + else { Text(verbatim: provider.title) } + } + .disabled(!snapshot.provider.canSelect(provider, ownerChoice: snapshot.providerChoice)) + } + } + /// Hides the conversation shown here; Ultra keeps its context and every stored message. private func clearButton(_ snapshot: GlobalChatSnapshot) -> some View { Button { confirmingClear = true } label: { @@ -353,15 +357,7 @@ struct GlobalChatScreen: View { private func titleMenu(_ snapshot: GlobalChatSnapshot) -> some View { let identity = identity(snapshot) return Menu { - Picker( - String(localized: "global.provider", defaultValue: "Chat Provider"), - selection: Binding( - get: { snapshot.provider }, - set: { if $0 != snapshot.provider { beginHandoff(to: $0, snapshot: snapshot) } } - ) - ) { - ForEach(GlobalChatProvider.allCases, id: \.self) { Text(verbatim: $0.title).tag($0) } - } + providerOptions(snapshot) } label: { HStack(spacing: 8) { GlobalChatAvatar(emoji: identity.emoji, size: 28, isActive: snapshot.busy) @@ -1537,6 +1533,12 @@ struct GlobalChatScreen: View { } private func beginHandoff(to provider: GlobalChatProvider, snapshot: GlobalChatSnapshot) { + if provider == snapshot.provider { + Task { + await mutate(.switchProvider(id: UUID(), provider: provider, handoff: "", providerRevision: snapshot.providerRevision)) + } + return + } issue = nil let recent = [ (GlobalChatMessage.Role.user, String(localized: "global.lastRequest", defaultValue: "Latest request")), diff --git a/Sources/GlobalChatCards.swift b/Sources/GlobalChatCards.swift index 0aa88375..dcac737d 100644 --- a/Sources/GlobalChatCards.swift +++ b/Sources/GlobalChatCards.swift @@ -338,7 +338,7 @@ final class GlobalChatCards { /// the keystrokes, with nothing awaited in between. func ship( _ id: UUID, isAuthorized: GlobalChatAuthorization, allowsTyping: @MainActor () -> Bool, - record: (String, UUID, UUID) -> Bool + record: (GlobalChatAction) -> Bool ) async -> Choice { guard !shipsInFlight.contains(id), let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ship(ship) = entry.card.content else { return .stale } @@ -376,11 +376,9 @@ final class GlobalChatCards { let reply = String(localized: "global.ship.reply", defaultValue: "Pull request #\(number) passed its checks. Merge it now with: gh pr merge \(number) --repo \(repoSlug) --match-head-commit \(headSHA)") guard allowsTyping() else { return .stale } guard let prepared = workspaces.prepare(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID, text: reply) else { return .stale } - return Self.submit(prepared, record: { _ in record(reply, ship.workspaceID, ship.surfaceID) }) { action in - guard workspaces.deliver(action) else { return false } - settle(id, as: .answered(choice: Self.shipChoice)) - return true - } + let result = Self.submit(prepared, record: record, deliver: workspaces.deliver) + if case .sent = result { settle(id, as: .answered(choice: Self.shipChoice)) } + return result } private static func isSameAgent(_ lhs: AgentSessionKey, _ rhs: AgentSessionKey) -> Bool { @@ -470,7 +468,7 @@ final class GlobalChatCards { /// The owner picked an option. It is typed only into the same terminal, to the same agent /// session, while that agent waits at its prompt; otherwise the card says why it was not sent. - func choose(_ id: UUID, option: Int, record: (String, UUID, UUID) -> Bool) -> Choice { + func choose(_ id: UUID, option: Int, record: (GlobalChatAction) -> Bool) -> Choice { guard let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ask(ask) = entry.card.content, ask.options.indices.contains(option) else { return .stale } let choice = ask.options[option] @@ -487,20 +485,21 @@ final class GlobalChatCards { guard let prepared = workspaces.prepare(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID, text: choice) else { return reject(.notWaiting) } - let result = Self.submit(prepared, record: { _ in record(choice, ask.workspaceID, ask.surfaceID) }) { action in - guard workspaces.deliver(action) else { return false } + switch Self.submit(prepared, record: record, deliver: workspaces.deliver) { + case .stale: return reject(.notWaiting) + case .sent: settle(id, as: .answered(choice: choice)) - return true + return .sent + case .storageFailed: return .storageFailed + case .settled: return .settled } - if case .stale = result { return reject(.notWaiting) } - return result } nonisolated static func submit( _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool ) -> Choice { - guard deliver(action) else { return .stale } - return record(action) ? .sent : .storageFailed + guard record(action) else { return .storageFailed } + return deliver(action) ? .sent : .stale } /// Drops the oldest settled cards past the count and size limits. Open cards are never dropped. diff --git a/Sources/GlobalChatController.swift b/Sources/GlobalChatController.swift index 1360d23c..01c3dcc5 100644 --- a/Sources/GlobalChatController.swift +++ b/Sources/GlobalChatController.swift @@ -7,7 +7,8 @@ final class GlobalChatController { static let shared = GlobalChatController() struct History: Codable { - var provider: GlobalChatProvider = .codex + static let defaultProvider: GlobalChatProvider = .codex + var provider = History.defaultProvider /// True once the user switches providers, false once a fallback answered, nil before either; until the user /// chooses, a turn falls back to whichever provider is installed and signed in. var providerChosen: Bool? @@ -165,12 +166,16 @@ final class GlobalChatController { /// Whether a turn may run the other provider when the stored one is signed out or missing. nonisolated static func canFallBack(_ history: History) -> Bool { - // Codex is the default, so a history set to Claude without the flag was the user's choice. - !(history.providerChosen ?? (history.provider != .codex)) + history.providerChosen != true } nonisolated static func decodeHistory(_ data: Data) throws -> History { - try JSONDecoder().decode(History.self, from: data) + var decoded = try JSONDecoder().decode(History.self, from: data) + if decoded.providerChosen == nil, decoded.provider != History.defaultProvider { + decoded.provider = History.defaultProvider + decoded.sessionID = nil + } + return decoded } /// The history's provider fields once `used` answered a turn. A fallback is marked as not chosen, so a later turn @@ -189,9 +194,11 @@ final class GlobalChatController { var updated = history updated.providerChosen = true updated.providerRevision = UUID() - updated.provider = provider - updated.sessionID = nil - updated.handoff = handoff.trimmingCharacters(in: .whitespacesAndNewlines) + if provider != history.provider { + updated.provider = provider + updated.sessionID = nil + updated.handoff = handoff.trimmingCharacters(in: .whitespacesAndNewlines) + } return updated } @@ -238,12 +245,14 @@ final class GlobalChatController { guard case .idle = turn else { return .failure(.busy) } guard handoff.utf8.count <= 4_000 else { return .failure(.invalid) } guard var updated = Self.selectingProvider(provider, handoff: handoff, in: history) else { return .snapshot(snapshot()) } + let previousProvider = history.provider remember(id, in: &updated) guard store(updated) else { return .failure(.storage) } - cards.supersedeProposals() + if provider != previousProvider { cards.supersedeProposals() } turn = .idle(nil) case let .clear(id): - guard let updated = Self.cleared(history, id: id, at: Date()) else { return .snapshot(snapshot()) } + let current = Self.mergingReplies(storage.pendingReplies, into: history) + guard let updated = Self.cleared(current, id: id, at: Date()) else { return .snapshot(snapshot()) } guard store(updated) else { return .failure(.storage) } case let .send(id, text, workspaceID, providerRevision, excerpt): return send( @@ -330,11 +339,14 @@ final class GlobalChatController { } } - /// Records text Ultra typed into a terminal, so the transcript keeps it after the card is gone. - private func recordActivity(_ text: String, workspaceID: UUID, surfaceID: UUID) -> Bool { + private func recordActivity(_ action: GlobalChatAction) -> Bool { var updated = history - updated.messages.append(Self.activity(text, workspaceID: workspaceID, surfaceID: surfaceID)) - return store(updated) + updated.messages.append(Self.activity(action.text, workspaceID: action.workspaceID, surfaceID: action.surfaceID)) + guard store(updated) else { + storage.saveFailed() + return false + } + return true } private static func activity(_ text: String, workspaceID: UUID, surfaceID: UUID) -> GlobalChatMessage { @@ -569,14 +581,13 @@ final class GlobalChatController { } let issue: GlobalChatIssue? = answer?.followUp != nil && routed?.note == nil ? .stale : answer?.task != nil && pendingTask == nil ? .invalid : nil - let stored = store(updated) + _ = store(updated, retaining: Array(updated.messages.dropFirst(history.messages.count))) // Added after the reply so the cards sort below the message that offers them. if let card = routed?.card { cards.add(.followUp(card), id: card.id) } if let pendingTask { cards.add(.task(pendingTask), id: pendingTask.id) } cloneIdentities = cloneIdentities.filter { cards.card($0.key)?.state.isPending == true } if let pendingTask, let github { cloneIdentities[pendingTask.id] = github } if let sent = routed?.sent { relay(sent.action, agent: sent.agent, after: sent.after) } - if !stored { storage.saveFailed() } turn = .idle(issue) } @@ -1145,16 +1156,17 @@ final class GlobalChatController { let runningTurn: UUID? switch turn { case .idle(let current): busy = false; issue = storage.issue ?? current; runningTurn = nil - case let .running(id, stop): busy = true; issue = nil; runningTurn = stop == nil ? nil : id - case .stopping: busy = true; issue = nil; runningTurn = nil + case let .running(id, stop): busy = true; issue = storage.issue; runningTurn = stop == nil ? nil : id + case .stopping: busy = true; issue = storage.issue; runningTurn = nil } let current = workspaces.snapshot() cards.reconcile(current) - let transcript = Self.transcript(history.messages, after: history.clearedThrough) + let transcript = Self.transcript(Self.mergingReplies(storage.pendingReplies, into: history).messages, after: history.clearedThrough) return GlobalChatSnapshot( messages: transcript.messages, hasEarlier: transcript.hasEarlier, workspaces: current, events: Array(history.events.suffix(Self.eventWindow)), - seenThrough: history.seenThrough, seenIDs: history.seenIDs ?? [], provider: history.provider, providerRevision: history.providerRevision, + seenThrough: history.seenThrough, seenIDs: history.seenIDs ?? [], provider: history.provider, + providerChoice: history.providerChosen, providerRevision: history.providerRevision, persona: persona, identity: .stored(), busy: busy, pendingAction: cards.pendingFollowUp, issue: issue, usageLimits: GlobalChatUsageLimits.shared.actions, pendingTask: cards.pendingTask, runningTurn: runningTurn, cards: Self.cards(cards.all, clearedAt: history.clearedAt), @@ -1162,7 +1174,7 @@ final class GlobalChatController { ) } - private func store(_ state: History) -> Bool { + private func store(_ state: History, retaining replies: [GlobalChatMessage] = []) -> Bool { // History unreadable at launch is still on disk; any save would replace it with an empty conversation. guard !storage.gatesRequests else { return false } var updated = state @@ -1170,7 +1182,7 @@ final class GlobalChatController { updated.operations = Array(updated.operations.suffix(1_024)) let retained = Set(updated.operations) updated.deliveries = updated.deliveries.filter { retained.contains($0.key) } - guard let saved = Self.persist(updated, storage: &storage, write: writeHistory) else { return false } + guard let saved = Self.persist(updated, retaining: replies, storage: &storage, write: writeHistory) else { return false } history = saved return true } @@ -1179,11 +1191,13 @@ final class GlobalChatController { _ history: History, retaining replies: [GlobalChatMessage] = [], storage: inout GlobalChatStorageHealth, write: (History) throws -> Void ) -> History? { + let updated = mergingReplies(storage.pendingReplies, into: history) do { - try write(history) + try write(updated) storage.saveSucceeded() - return history + return updated } catch { + if !replies.isEmpty { storage.saveFailed(retaining: replies) } return nil } } diff --git a/Sources/GlobalChatDispatch.swift b/Sources/GlobalChatDispatch.swift index 10ae4d45..23c923d5 100644 --- a/Sources/GlobalChatDispatch.swift +++ b/Sources/GlobalChatDispatch.swift @@ -166,25 +166,37 @@ nonisolated struct GlobalChatRelays { /// request until Programa restarts: answering from it would overwrite the stored conversation or resume a provider /// session started under older rules. A save that fails later is reported, without refusing anything, until a later /// save succeeds. -nonisolated struct GlobalChatStorageHealth: Equatable { - private enum State: Equatable { case healthy, failedAtLaunch, saveFailed } +nonisolated struct GlobalChatStorageHealth { + private enum State { case healthy, failedAtLaunch, saveFailed([GlobalChatMessage]) } private var state: State init(failedAtLaunch: Bool = false) { state = failedAtLaunch ? .failedAtLaunch : .healthy } - mutating func saveFailed() { - if state != .failedAtLaunch { state = .saveFailed } + mutating func saveFailed(retaining replies: [GlobalChatMessage] = []) { + guard !gatesRequests else { return } + state = .saveFailed(pendingReplies + replies) } mutating func saveSucceeded() { - if state == .saveFailed { state = .healthy } + if case .saveFailed = state { state = .healthy } } - var gatesRequests: Bool { state == .failedAtLaunch } + var pendingReplies: [GlobalChatMessage] { + if case let .saveFailed(replies) = state { return replies } + return [] + } - var issue: GlobalChatIssue? { state == .healthy ? nil : .storage } + var gatesRequests: Bool { + if case .failedAtLaunch = state { return true } + return false + } + + var issue: GlobalChatIssue? { + if case .healthy = state { return nil } + return .storage + } } /// Starts a task's agent in its new workspace's shell. From 1a7a96e856d2ccb746cbc7fe9fcd635c66f4cbc2 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:45:10 -0300 Subject: [PATCH 4/6] refactor(global-chat): expose completion and card rollback seams --- Sources/GlobalChatCards.swift | 3 ++- Sources/GlobalChatController.swift | 14 ++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Sources/GlobalChatCards.swift b/Sources/GlobalChatCards.swift index dcac737d..a984bc51 100644 --- a/Sources/GlobalChatCards.swift +++ b/Sources/GlobalChatCards.swift @@ -496,7 +496,8 @@ final class GlobalChatCards { } nonisolated static func submit( - _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool + _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool, + unrecord: (GlobalChatAction) -> Void = { _ in } ) -> Choice { guard record(action) else { return .storageFailed } return deliver(action) ? .sent : .stale diff --git a/Sources/GlobalChatController.swift b/Sources/GlobalChatController.swift index 01c3dcc5..17ca2084 100644 --- a/Sources/GlobalChatController.swift +++ b/Sources/GlobalChatController.swift @@ -35,7 +35,7 @@ final class GlobalChatController { enum Delivery: String, Codable { case started, sent, stale } /// Raise when the provider must not resume a session started under older rules. nonisolated static let dispatchVersion = 1 - private enum StorageError: Error { case unsafe, archiveRequired } + nonisolated enum StorageError: Error { case unsafe, archiveRequired } private enum TaskError: Error { case unavailable, reported } // SHORTCUT: one atomic history file. ceiling: 32 MiB. upgrade: rotate transcript pages before reaching the limit. private static let maximumHistoryBytes = 32 * 1024 * 1024 @@ -581,7 +581,7 @@ final class GlobalChatController { } let issue: GlobalChatIssue? = answer?.followUp != nil && routed?.note == nil ? .stale : answer?.task != nil && pendingTask == nil ? .invalid : nil - _ = store(updated, retaining: Array(updated.messages.dropFirst(history.messages.count))) + _ = store(updated, completing: history) // Added after the reply so the cards sort below the message that offers them. if let card = routed?.card { cards.add(.followUp(card), id: card.id) } if let pendingTask { cards.add(.task(pendingTask), id: pendingTask.id) } @@ -1174,7 +1174,7 @@ final class GlobalChatController { ) } - private func store(_ state: History, retaining replies: [GlobalChatMessage] = []) -> Bool { + private func store(_ state: History, completing previous: History? = nil) -> Bool { // History unreadable at launch is still on disk; any save would replace it with an empty conversation. guard !storage.gatesRequests else { return false } var updated = state @@ -1182,13 +1182,14 @@ final class GlobalChatController { updated.operations = Array(updated.operations.suffix(1_024)) let retained = Set(updated.operations) updated.deliveries = updated.deliveries.filter { retained.contains($0.key) } - guard let saved = Self.persist(updated, retaining: replies, storage: &storage, write: writeHistory) else { return false } + guard let saved = Self.persist(updated, completing: previous, storage: &storage, write: writeHistory) else { return false } history = saved return true } nonisolated static func persist( - _ history: History, retaining replies: [GlobalChatMessage] = [], storage: inout GlobalChatStorageHealth, + _ history: History, retaining replies: [GlobalChatMessage] = [], completing previous: History? = nil, + storage: inout GlobalChatStorageHealth, write: (History) throws -> Void ) -> History? { let updated = mergingReplies(storage.pendingReplies, into: history) @@ -1197,7 +1198,8 @@ final class GlobalChatController { storage.saveSucceeded() return updated } catch { - if !replies.isEmpty { storage.saveFailed(retaining: replies) } + let pending = previous.map { Array(history.messages.dropFirst($0.messages.count)) } ?? replies + if !pending.isEmpty { storage.saveFailed(retaining: pending) } return nil } } From 2ccc5a8dce2bcb0feb2f909c4a3a2be1a67216b0 Mon Sep 17 00:00:00 2001 From: arzafran Date: Fri, 4 Dec 2026 12:46:12 -0300 Subject: [PATCH 5/6] test(global-chat): cover provider recovery and card delivery failures --- programaTests/GlobalChatDispatchTests.swift | 129 ++++++++++++++++++-- 1 file changed, 122 insertions(+), 7 deletions(-) diff --git a/programaTests/GlobalChatDispatchTests.swift b/programaTests/GlobalChatDispatchTests.swift index 82a1719e..b44ccdd5 100644 --- a/programaTests/GlobalChatDispatchTests.swift +++ b/programaTests/GlobalChatDispatchTests.swift @@ -245,17 +245,24 @@ final class GlobalChatDispatchTests: XCTestCase { let reply = GlobalChatMessage(id: messages[1].id, role: .assistant, text: "Reply", date: messages[1].date) let note = messages[2] var storage = GlobalChatStorageHealth() - var completed = GlobalChatController.History() + var previous = GlobalChatController.History() + previous.messages = [owner] + previous.sessionID = "old-session" + previous.interruptedTurn = owner.id + var completed = previous completed.messages = [owner, reply, note] - XCTAssertNil(GlobalChatController.persist(completed, retaining: [reply, note], storage: &storage) { _ in + completed.sessionID = "completed-session" + completed.interruptedTurn = nil + XCTAssertNil(GlobalChatController.persist(completed, completing: previous, storage: &storage) { _ in throw CocoaError(.fileWriteNoPermission) }) XCTAssertEqual(storage.issue, .storage) - var latest = GlobalChatController.History() + var latest = previous let recorded = GlobalChatMessage(id: note.id, role: .assistant, text: "Recorded note", date: note.date) latest.messages = [owner, recorded, newer] latest.sessionID = "newer-session" + latest.interruptedTurn = newer.id XCTAssertNil(GlobalChatController.persist(latest, storage: &storage) { candidate in XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) throw CocoaError(.fileWriteNoPermission) @@ -266,31 +273,105 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) XCTAssertEqual(candidate.messages.map(\.text), [owner.text, reply.text, recorded.text, newer.text]) XCTAssertEqual(candidate.sessionID, latest.sessionID) + XCTAssertEqual(candidate.interruptedTurn, newer.id) }) XCTAssertEqual(saved.messages.map(\.id), messages.map(\.id)) XCTAssertNil(storage.issue) } - @MainActor + func testARetryRestoresCompletionOnlyWhileTheSameTurnOwnsTheSession() throws { + let messages = conversation(2) + var running = GlobalChatController.History() + running.messages = [messages[0]] + running.interruptedTurn = messages[0].id + running.sessionID = "old-session" + var completed = running + completed.messages = messages + completed.interruptedTurn = nil + completed.sessionID = "completed-session" + var storage = GlobalChatStorageHealth() + XCTAssertNil(GlobalChatController.persist(completed, completing: running, storage: &storage) { _ in + throw CocoaError(.fileWriteNoPermission) + }) + + var replacedSession = running + replacedSession.sessionID = "newer-session" + var replacedTurn = running + replacedTurn.interruptedTurn = UUID() + for latest in [running, replacedSession, replacedTurn] { + var retryStorage = storage + let stillOwnsSession = latest.interruptedTurn == running.interruptedTurn && latest.sessionID == running.sessionID + let saved = try XCTUnwrap(GlobalChatController.persist(latest, storage: &retryStorage) { candidate in + XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) + XCTAssertEqual(candidate.sessionID, stillOwnsSession ? completed.sessionID : latest.sessionID) + XCTAssertEqual(candidate.interruptedTurn, stillOwnsSession ? nil : latest.interruptedTurn) + }) + XCTAssertEqual(saved.messages.map(\.id), messages.map(\.id)) + XCTAssertNil(retryStorage.issue) + } + } + + func testAnOversizePendingReplyDoesNotBlockOtherHistoryWrites() throws { + let messages = conversation(2) + var running = GlobalChatController.History() + running.messages = [messages[0]] + running.interruptedTurn = messages[0].id + var completed = running + completed.messages = messages + completed.interruptedTurn = nil + completed.sessionID = "completed-session" + var storage = GlobalChatStorageHealth() + XCTAssertNil(GlobalChatController.persist(completed, completing: running, storage: &storage) { _ in + throw GlobalChatController.StorageError.archiveRequired + }) + + running.seenThrough = 12 + var attempts: [[UUID]] = [] + let saved = try XCTUnwrap(GlobalChatController.persist(running, storage: &storage) { candidate in + attempts.append(candidate.messages.map(\.id)) + XCTAssertEqual(candidate.seenThrough, 12) + if candidate.messages.count > 1 { throw GlobalChatController.StorageError.archiveRequired } + XCTAssertEqual(candidate.interruptedTurn, running.interruptedTurn) + XCTAssertEqual(candidate.sessionID, running.sessionID) + }) + XCTAssertEqual(attempts, [messages.map(\.id), [messages[0].id]]) + XCTAssertEqual(saved.seenThrough, 12) + XCTAssertEqual(storage.pendingReplies.map(\.id), [messages[1].id]) + XCTAssertEqual(storage.issue, .storage) + + XCTAssertNotNil(GlobalChatController.persist(saved, storage: &storage) { candidate in + XCTAssertEqual(candidate.messages.map(\.id), messages.map(\.id)) + XCTAssertEqual(candidate.sessionID, completed.sessionID) + XCTAssertNil(candidate.interruptedTurn) + }) + XCTAssertNil(storage.issue) + } + func testAnAutomaticFallbackLeavesTheNextTurnFreeToFallBack() { let history = GlobalChatController.History() XCTAssertTrue(GlobalChatController.canFallBack(history)) let answered = GlobalChatController.answered(history, by: .claude) XCTAssertEqual(answered.provider, .claude, "the history records the provider that answered") + XCTAssertNotEqual(answered.providerRevision, history.providerRevision) + XCTAssertEqual(GlobalChatController.answered(answered, by: .claude).providerRevision, answered.providerRevision) XCTAssertTrue(GlobalChatController.canFallBack(answered), "a fallback is not the owner's choice") } - func testAClaudeHistorySavedWithoutAnOwnerChoiceUsesTheDefaultProvider() throws { + func testAClaudeHistorySavedWithoutAnOwnerChoiceKeepsItsSessionAndCanBeConfirmed() throws { var old = GlobalChatController.History() old.provider = .claude old.sessionID = "claude-session" old.messages = conversation(1) let legacy = try GlobalChatController.decodeHistory(JSONEncoder().encode(old)) - XCTAssertEqual(legacy.provider, .codex) + XCTAssertEqual(legacy.provider, .claude) XCTAssertNil(legacy.providerChosen) - XCTAssertNil(legacy.sessionID) + XCTAssertEqual(legacy.sessionID, old.sessionID) XCTAssertEqual(legacy.messages.map(\.id), old.messages.map(\.id)) XCTAssertTrue(GlobalChatController.canFallBack(legacy)) + let confirmed = try XCTUnwrap(GlobalChatController.selectingProvider(.claude, handoff: "", in: legacy)) + XCTAssertEqual(confirmed.providerChosen, true) + XCTAssertEqual(confirmed.sessionID, old.sessionID) + XCTAssertFalse(GlobalChatController.canFallBack(confirmed)) old.providerChosen = true let chosen = try GlobalChatController.decodeHistory(JSONEncoder().encode(old)) @@ -324,6 +405,8 @@ final class GlobalChatDispatchTests: XCTestCase { }, deliver: { _ in calls.append("deliver") return true + }, unrecord: { _ in + calls.append("unrecord") }) guard case .storageFailed = failed else { return XCTFail("Expected a storage failure") } XCTAssertEqual(calls, ["record"]) @@ -337,11 +420,43 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertEqual($0.id, action.id) calls.append("deliver") return true + }, unrecord: { _ in + calls.append("unrecord") }) guard case .sent = sent else { return XCTFail("Expected delivery after the save") } XCTAssertEqual(calls, ["record", "deliver"]) } + func testAFailedCardDeliveryRollsBackTheActivityBeforeRetrying() { + let workspace = UUID(), surface = UUID() + let first = GlobalChatAction( + id: UUID(), workspaceID: workspace, surfaceID: surface, + workspaceTitle: "Workspace", surfaceTitle: "Agent", text: "Yes" + ) + let retry = GlobalChatAction( + id: UUID(), workspaceID: workspace, surfaceID: surface, + workspaceTitle: "Workspace", surfaceTitle: "Agent", text: first.text + ) + var transcript: [UUID] = [] + func record(_ action: GlobalChatAction) -> Bool { + transcript.append(action.id) + return true + } + func unrecord(_ action: GlobalChatAction) { + transcript.removeAll { $0 == action.id } + } + let failed = GlobalChatCards.submit(first, record: record, deliver: { action in + XCTAssertEqual(transcript, [action.id]) + return false + }, unrecord: unrecord) + guard case .stale = failed else { return XCTFail("Expected a failed delivery") } + XCTAssertTrue(transcript.isEmpty) + + let sent = GlobalChatCards.submit(retry, record: record, deliver: { _ in true }, unrecord: unrecord) + guard case .sent = sent else { return XCTFail("Expected the retry to deliver") } + XCTAssertEqual(transcript, [retry.id]) + } + private func conversation(_ count: Int) -> [GlobalChatMessage] { (0.. Date: Fri, 4 Dec 2026 12:48:00 -0300 Subject: [PATCH 6/6] fix(global-chat): recover pending turns and retract failed deliveries --- MobileChat/CompanionWire.swift | 2 +- Sources/GlobalChatCards.swift | 18 ++++--- Sources/GlobalChatController.swift | 78 +++++++++++++++++++++--------- Sources/GlobalChatDispatch.swift | 23 +++++++-- 4 files changed, 85 insertions(+), 36 deletions(-) diff --git a/MobileChat/CompanionWire.swift b/MobileChat/CompanionWire.swift index 50b6ba21..513cc8f6 100644 --- a/MobileChat/CompanionWire.swift +++ b/MobileChat/CompanionWire.swift @@ -57,7 +57,7 @@ nonisolated enum GlobalChatProvider: String, CaseIterable, Codable, Sendable { case codex, claude func canSelect(_ provider: Self, ownerChoice: Bool?) -> Bool { - provider != self || ownerChoice == false + provider != self || ownerChoice != true } var title: String { diff --git a/Sources/GlobalChatCards.swift b/Sources/GlobalChatCards.swift index a984bc51..0051abdb 100644 --- a/Sources/GlobalChatCards.swift +++ b/Sources/GlobalChatCards.swift @@ -338,7 +338,7 @@ final class GlobalChatCards { /// the keystrokes, with nothing awaited in between. func ship( _ id: UUID, isAuthorized: GlobalChatAuthorization, allowsTyping: @MainActor () -> Bool, - record: (GlobalChatAction) -> Bool + record: (GlobalChatAction) -> Bool, unrecord: (GlobalChatAction) -> Void ) async -> Choice { guard !shipsInFlight.contains(id), let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ship(ship) = entry.card.content else { return .stale } @@ -376,7 +376,7 @@ final class GlobalChatCards { let reply = String(localized: "global.ship.reply", defaultValue: "Pull request #\(number) passed its checks. Merge it now with: gh pr merge \(number) --repo \(repoSlug) --match-head-commit \(headSHA)") guard allowsTyping() else { return .stale } guard let prepared = workspaces.prepare(workspaceID: ship.workspaceID, surfaceID: ship.surfaceID, text: reply) else { return .stale } - let result = Self.submit(prepared, record: record, deliver: workspaces.deliver) + let result = Self.submit(prepared, record: record, deliver: workspaces.deliver, unrecord: unrecord) if case .sent = result { settle(id, as: .answered(choice: Self.shipChoice)) } return result } @@ -468,7 +468,9 @@ final class GlobalChatCards { /// The owner picked an option. It is typed only into the same terminal, to the same agent /// session, while that agent waits at its prompt; otherwise the card says why it was not sent. - func choose(_ id: UUID, option: Int, record: (GlobalChatAction) -> Bool) -> Choice { + func choose( + _ id: UUID, option: Int, record: (GlobalChatAction) -> Bool, unrecord: (GlobalChatAction) -> Void + ) -> Choice { guard let entry = entries.first(where: { $0.card.id == id }), entry.card.state.isPending, case let .ask(ask) = entry.card.content, ask.options.indices.contains(option) else { return .stale } let choice = ask.options[option] @@ -485,7 +487,7 @@ final class GlobalChatCards { guard let prepared = workspaces.prepare(workspaceID: ask.workspaceID, surfaceID: ask.surfaceID, text: choice) else { return reject(.notWaiting) } - switch Self.submit(prepared, record: record, deliver: workspaces.deliver) { + switch Self.submit(prepared, record: record, deliver: workspaces.deliver, unrecord: unrecord) { case .stale: return reject(.notWaiting) case .sent: settle(id, as: .answered(choice: choice)) @@ -497,10 +499,14 @@ final class GlobalChatCards { nonisolated static func submit( _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool, - unrecord: (GlobalChatAction) -> Void = { _ in } + unrecord: (GlobalChatAction) -> Void ) -> Choice { guard record(action) else { return .storageFailed } - return deliver(action) ? .sent : .stale + guard deliver(action) else { + unrecord(action) + return .stale + } + return .sent } /// Drops the oldest settled cards past the count and size limits. Open cards are never dropped. diff --git a/Sources/GlobalChatController.swift b/Sources/GlobalChatController.swift index 17ca2084..958d7c9b 100644 --- a/Sources/GlobalChatController.swift +++ b/Sources/GlobalChatController.swift @@ -7,8 +7,7 @@ final class GlobalChatController { static let shared = GlobalChatController() struct History: Codable { - static let defaultProvider: GlobalChatProvider = .codex - var provider = History.defaultProvider + var provider: GlobalChatProvider = .codex /// True once the user switches providers, false once a fallback answered, nil before either; until the user /// chooses, a turn falls back to whichever provider is installed and signed in. var providerChosen: Bool? @@ -170,20 +169,17 @@ final class GlobalChatController { } nonisolated static func decodeHistory(_ data: Data) throws -> History { - var decoded = try JSONDecoder().decode(History.self, from: data) - if decoded.providerChosen == nil, decoded.provider != History.defaultProvider { - decoded.provider = History.defaultProvider - decoded.sessionID = nil - } - return decoded + try JSONDecoder().decode(History.self, from: data) } /// The history's provider fields once `used` answered a turn. A fallback is marked as not chosen, so a later turn /// may still fall back. nonisolated static func answered(_ history: History, by used: GlobalChatProvider) -> History { + guard used != history.provider else { return history } var updated = history - if used != history.provider { updated.providerChosen = false } updated.provider = used + updated.providerChosen = false + updated.providerRevision = UUID() return updated } @@ -252,7 +248,8 @@ final class GlobalChatController { turn = .idle(nil) case let .clear(id): let current = Self.mergingReplies(storage.pendingReplies, into: history) - guard let updated = Self.cleared(current, id: id, at: Date()) else { return .snapshot(snapshot()) } + guard var updated = Self.cleared(current, id: id, at: Date()) else { return .snapshot(snapshot()) } + updated.messages = history.messages guard store(updated) else { return .failure(.storage) } case let .send(id, text, workspaceID, providerRevision, excerpt): return send( @@ -279,7 +276,7 @@ final class GlobalChatController { turn = .stopping(id, saved: store(updated)) } case let .choose(cardID, option): - return respond(to: cards.choose(cardID, option: option, record: recordActivity)) + return respond(to: cards.choose(cardID, option: option, record: recordActivity, unrecord: unrecordActivity)) case let .deliver(actionID): if let scheduled = GlobalChatUsageLimits.shared.resume(actionID) { return scheduled ? .snapshot(snapshot()) : .failure(.stale) } if let delivery = history.deliveries[actionID] { @@ -293,7 +290,8 @@ final class GlobalChatController { return start(task) case .ship: return respond(to: await cards.ship( - actionID, isAuthorized: isAuthorized, allowsTyping: allowsTyping, record: recordActivity + actionID, isAuthorized: isAuthorized, allowsTyping: allowsTyping, + record: recordActivity, unrecord: unrecordActivity )) case let .followUp(action): return deliver(action) case .ask, .unsupported: return .failure(.stale) @@ -341,7 +339,7 @@ final class GlobalChatController { private func recordActivity(_ action: GlobalChatAction) -> Bool { var updated = history - updated.messages.append(Self.activity(action.text, workspaceID: action.workspaceID, surfaceID: action.surfaceID)) + updated.messages.append(Self.activity(action.text, workspaceID: action.workspaceID, surfaceID: action.surfaceID, id: action.id)) guard store(updated) else { storage.saveFailed() return false @@ -349,8 +347,17 @@ final class GlobalChatController { return true } - private static func activity(_ text: String, workspaceID: UUID, surfaceID: UUID) -> GlobalChatMessage { - GlobalChatMessage(id: UUID(), role: .activity, text: text, date: Date(), workspaceID: workspaceID, surfaceID: surfaceID) + private func unrecordActivity(_ action: GlobalChatAction) { + var updated = history + updated.messages.removeAll { $0.id == action.id } + if !store(updated) { + history = updated + storage.saveFailed() + } + } + + private static func activity(_ text: String, workspaceID: UUID, surfaceID: UUID, id: UUID = UUID()) -> GlobalChatMessage { + GlobalChatMessage(id: id, role: .activity, text: text, date: Date(), workspaceID: workspaceID, surfaceID: surfaceID) } func importHistory() { @@ -1188,18 +1195,41 @@ final class GlobalChatController { } nonisolated static func persist( - _ history: History, retaining replies: [GlobalChatMessage] = [], completing previous: History? = nil, - storage: inout GlobalChatStorageHealth, - write: (History) throws -> Void + _ history: History, completing previous: History? = nil, + storage: inout GlobalChatStorageHealth, write: (History) throws -> Void ) -> History? { - let updated = mergingReplies(storage.pendingReplies, into: history) + let pending = storage.pendingTurns + var updated = mergingReplies(storage.pendingReplies, into: history) + if let completed = pending.first(where: { $0.id == history.interruptedTurn }), + history.sessionID == completed.previousSessionID, + history.providerRevision == completed.previousProviderRevision { + updated = answered(updated, by: completed.provider) + updated.sessionID = completed.sessionID + updated.interruptedTurn = nil + updated.handoff = "" + } do { - try write(updated) - storage.saveSucceeded() - return updated + do { + try write(updated) + storage.saveSucceeded() + return updated + } catch StorageError.archiveRequired where !pending.isEmpty { + var withoutPending = history + if let mark = history.clearedThrough, !history.messages.contains(where: { $0.id == mark }), + updated.messages.contains(where: { $0.id == mark }) { + withoutPending.clearedThrough = history.messages.last?.id + } + try write(withoutPending) + return withoutPending + } } catch { - let pending = previous.map { Array(history.messages.dropFirst($0.messages.count)) } ?? replies - if !pending.isEmpty { storage.saveFailed(retaining: pending) } + if let previous, let id = previous.interruptedTurn { + storage.saveFailed(retaining: .init( + id: id, messages: Array(history.messages.dropFirst(previous.messages.count)), + previousSessionID: previous.sessionID, previousProviderRevision: previous.providerRevision, + sessionID: history.sessionID, provider: history.provider + )) + } return nil } } diff --git a/Sources/GlobalChatDispatch.swift b/Sources/GlobalChatDispatch.swift index 23c923d5..66087bf7 100644 --- a/Sources/GlobalChatDispatch.swift +++ b/Sources/GlobalChatDispatch.swift @@ -167,27 +167,40 @@ nonisolated struct GlobalChatRelays { /// session started under older rules. A save that fails later is reported, without refusing anything, until a later /// save succeeds. nonisolated struct GlobalChatStorageHealth { - private enum State { case healthy, failedAtLaunch, saveFailed([GlobalChatMessage]) } + struct PendingTurn { + let id: UUID + let messages: [GlobalChatMessage] + let previousSessionID: String? + let previousProviderRevision: UUID + let sessionID: String? + let provider: GlobalChatProvider + } + + private enum State { case healthy, failedAtLaunch, saveFailed([PendingTurn]) } private var state: State init(failedAtLaunch: Bool = false) { state = failedAtLaunch ? .failedAtLaunch : .healthy } - mutating func saveFailed(retaining replies: [GlobalChatMessage] = []) { + mutating func saveFailed(retaining turn: PendingTurn? = nil) { guard !gatesRequests else { return } - state = .saveFailed(pendingReplies + replies) + var pending = pendingTurns + if let turn { pending.append(turn) } + state = .saveFailed(pending) } mutating func saveSucceeded() { if case .saveFailed = state { state = .healthy } } - var pendingReplies: [GlobalChatMessage] { - if case let .saveFailed(replies) = state { return replies } + var pendingTurns: [PendingTurn] { + if case let .saveFailed(turns) = state { return turns } return [] } + var pendingReplies: [GlobalChatMessage] { pendingTurns.flatMap(\.messages) } + var gatesRequests: Bool { if case .failedAtLaunch = state { return true } return false