diff --git a/MobileChat/CompanionWire.swift b/MobileChat/CompanionWire.swift index dc6915ae..513cc8f6 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 || ownerChoice != true + } + var title: String { switch self { case .codex: "Codex" @@ -326,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 56263539..0051abdb 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: (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 } guard let binding = self.binding(for: entry, ship: ship), let repoSlug = entry.repoSlug else { @@ -371,10 +375,10 @@ 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 } + 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 } private static func isSameAgent(_ lhs: AgentSessionKey, _ rhs: AgentSessionKey) -> Bool { @@ -464,23 +468,45 @@ 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: (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] - 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) + } + switch Self.submit(prepared, record: record, deliver: workspaces.deliver, unrecord: unrecord) { + case .stale: return reject(.notWaiting) + case .sent: + settle(id, as: .answered(choice: choice)) + return .sent + case .storageFailed: return .storageFailed + case .settled: return .settled + } + } + + nonisolated static func submit( + _ action: GlobalChatAction, record: (GlobalChatAction) -> Bool, deliver: (GlobalChatAction) -> Bool, + unrecord: (GlobalChatAction) -> Void + ) -> Choice { + guard record(action) else { return .storageFailed } + 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 d76e5fed..958d7c9b 100644 --- a/Sources/GlobalChatController.swift +++ b/Sources/GlobalChatController.swift @@ -34,7 +34,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 @@ -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,17 +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 { - // 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 canFallBack(_ history: History) -> Bool { + history.providerChosen != true + } + + 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 { + 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 + } + + 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() + if provider != history.provider { + updated.provider = provider + updated.sessionID = nil + updated.handoff = handoff.trimmingCharacters(in: .whitespacesAndNewlines) + } return updated } @@ -220,19 +240,16 @@ 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()) } + 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 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( @@ -259,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)) + 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] { @@ -271,7 +288,11 @@ 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, unrecord: unrecordActivity + )) case let .followUp(action): return deliver(action) case .ask, .unsupported: return .failure(.stale) } @@ -311,21 +332,32 @@ 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) + } + } + + private func recordActivity(_ action: GlobalChatAction) -> Bool { + var updated = history + updated.messages.append(Self.activity(action.text, workspaceID: action.workspaceID, surfaceID: action.surfaceID, id: action.id)) + guard store(updated) else { + storage.saveFailed() + return false } + return true } - /// 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 unrecordActivity(_ action: GlobalChatAction) { var updated = history - updated.messages.append(Self.activity(text, workspaceID: workspaceID, surfaceID: surfaceID)) - return store(updated) + updated.messages.removeAll { $0.id == action.id } + if !store(updated) { + history = updated + storage.saveFailed() + } } - 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 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() { @@ -556,14 +588,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, 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) } 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) } @@ -1132,16 +1163,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), @@ -1149,7 +1181,7 @@ final class GlobalChatController { ) } - private func store(_ state: History) -> 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 @@ -1157,26 +1189,76 @@ 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, completing: previous, storage: &storage, write: writeHistory) else { return false } + history = saved + return true + } + + nonisolated static func persist( + _ history: History, completing previous: History? = nil, + storage: inout GlobalChatStorageHealth, write: (History) throws -> Void + ) -> 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 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) + 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 } - history = updated - storage.saveSucceeded() - return true } catch { - return false + 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 + } + } + + 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) } } diff --git a/Sources/GlobalChatDispatch.swift b/Sources/GlobalChatDispatch.swift index 10ae4d45..66087bf7 100644 --- a/Sources/GlobalChatDispatch.swift +++ b/Sources/GlobalChatDispatch.swift @@ -166,25 +166,50 @@ 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 { + 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() { - if state != .failedAtLaunch { state = .saveFailed } + mutating func saveFailed(retaining turn: PendingTurn? = nil) { + guard !gatesRequests else { return } + var pending = pendingTurns + if let turn { pending.append(turn) } + state = .saveFailed(pending) } mutating func saveSucceeded() { - if state == .saveFailed { state = .healthy } + if case .saveFailed = state { state = .healthy } + } + + var pendingTurns: [PendingTurn] { + if case let .saveFailed(turns) = state { return turns } + return [] } - var gatesRequests: Bool { state == .failedAtLaunch } + var pendingReplies: [GlobalChatMessage] { pendingTurns.flatMap(\.messages) } - 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. diff --git a/programaTests/GlobalChatDispatchTests.swift b/programaTests/GlobalChatDispatchTests.swift index 94bef4c6..b44ccdd5 100644 --- a/programaTests/GlobalChatDispatchTests.swift +++ b/programaTests/GlobalChatDispatchTests.swift @@ -239,27 +239,222 @@ final class GlobalChatDispatchTests: XCTestCase { XCTAssertFalse(storage.gatesRequests) } - @MainActor + 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 previous = GlobalChatController.History() + previous.messages = [owner] + previous.sessionID = "old-session" + previous.interruptedTurn = owner.id + var completed = previous + completed.messages = [owner, reply, note] + 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 = 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) + }) + 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(candidate.interruptedTurn, newer.id) + }) + XCTAssertEqual(saved.messages.map(\.id), messages.map(\.id)) + XCTAssertNil(storage.issue) + } + + 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") } - @MainActor - func testAClaudeHistorySavedWithoutTheFlagStaysTheOwnersChoice() throws { + func testAClaudeHistorySavedWithoutAnOwnerChoiceKeepsItsSessionAndCanBeConfirmed() 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, .claude) + XCTAssertNil(legacy.providerChosen) + 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)) + 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 + }, unrecord: { _ in + calls.append("unrecord") + }) + 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 + }, 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] {