diff --git a/.memory/inline-generative-ui.md b/.memory/inline-generative-ui.md index 512a677858..f59759f7af 100644 --- a/.memory/inline-generative-ui.md +++ b/.memory/inline-generative-ui.md @@ -112,6 +112,7 @@ Round 17 (2026-11-19): security (rev43) and correctness (rev44) reviews of 91ab5 ## Smarter artifacts Phase E2 (2026-11-19) - Item 32, visuals on `aiden serve` (b9cb9bec0, `packages/cli/src/server-visuals.ts`): `render_artifact` draws the visual once as a still PNG (2x, 720 or 1024 px wide) with an installed Chrome or Chromium found only at fixed paths (no `PATH` lookup, no override, no snap), headless, sandbox on, throwaway profile, offline with every request refused, bounded time and size; looked for only when a visual is drawn. The PNG goes out as the desktop's ordinary visual snapshot, so there is no Remote protocol change. `render_ui` sends its fallback text with each chart's data under its summary line (`compileAum(..., { fallback: { chartTables: true, plainTables: true } })` in `packages/cli/src/extensions/artifacts.ts`): since Phase E fix round 2, each table row is one plain line of labelled values (`Customer: Acme · Revenue: $1.2M`, cells clipped to 40 characters and stripped of control and bidi characters), not Markdown pipes or space-padded columns, because the phone's visual row shows the text as-is in a proportional font; sparklines list their values (all up to 32, else the first, `…`, the latest 30 and the count, so `…` always hides two or more; 2026-11-19), chart/sparkline/heatmap labels go through `cleanCell` (one line, max 120), plain rows are cut at 400 characters, heatmaps their cells as `row · column: value` lines, and scatter charts every numeric field when no `x` is named. Each tool result starts with what the person sees ("Shown as an image" / "Shown as text" / "Not shown" with the reason). Running as root or without a browser: not shown, said so. The server does not offer `chat-visual-viewer-v1`. A paired Mac never drew a server's native visual (Remote projects no markup); since Phase E fix round 2 `mapRemoteMessage` (`renderer/lib/hosts/remote-chat-mapper.ts`) turns each projected `ui` visual that has `fallbackText` and no `snapshotAttachmentId` into a text-only `ChatUiVisualV1` (`Visual` root, one `Text` per line, at most 400 lines, no data or state) placed by its `toolCallId`, so a paired Mac shows the same text as a phone; the tool result says "phones and Macs paired to this server show … as the text below". + - Test (2026-11-24): the real-Chrome test in `packages/cli/tests/server-visuals.test.mjs` draws one untimed warm-up first. A CI trace showed the first Chrome launch on a fresh hosted Linux runner takes 8-14 s to answer `Target.createTarget` (cold disk; nothing on stderr for ~7.5 s), against the 15 s render limit, while warm launches answer in ~170 ms and draw in ~1 s. Its D-Bus errors are noise: disabling D-Bus and running the file outside the parallel pool were both tried and changed nothing. This had been failing `renderer-other` on many branches (#906 runs 45337184177, 45352616175, 45356021801). - Idea 4, the visual's Actions menu: with extra actions, a visual caption's Copy (native) or Export (HTML) button becomes one `MoreHorizontal` "Actions for {title}" menu (`renderer/components/visual-actions-menu.tsx`, `VisualCaptionActions`) that lists the visual's own action first, so no new always-visible control. With no extras it is still the plain button. The expanded HTML view keeps a plain Export: a portalled Radix menu sits behind the top-layer popover and light-dismisses it. - Native visuals get **Keep in Artifacts** (settled messages only; `KeepVisualChatContext` from `chat-pane.tsx`, set only for a local non-Bot, non-routine chat in a non-Assistant workspace; the remote chat view never provides it). IPC `workspaces:artifacts:keepVisual(chatId, messageId, visualId)`; main re-checks every case and reads the visual from the stored chat, never from the renderer. - HTML visuals get **Send to canvas** only when `useDesignModeControls(chatId)` is non-null. IPC `designCanvas:placeArtifact(chatId, mediaId)` places it as an artifact frame (sized to the open canvas's viewSize) through the existing placement path (unsafe-HTML scan, size limits, frame cap); placed or already turns design mode on, an error result (`missing`, `unsafe`, `full`) toasts and leaves design mode alone. Messages live in `renderer/lib/visual-menu-actions.ts`. diff --git a/ios/AidenOnTheGo.xcodeproj/project.pbxproj b/ios/AidenOnTheGo.xcodeproj/project.pbxproj index ac867ce798..14c9e1d15c 100644 --- a/ios/AidenOnTheGo.xcodeproj/project.pbxproj +++ b/ios/AidenOnTheGo.xcodeproj/project.pbxproj @@ -7,6 +7,14 @@ objects = { /* Begin PBXBuildFile section */ + F6A100000000000000000001 /* AidenHostConnectionLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000101 /* AidenHostConnectionLifecycle.swift */; }; + F6A100000000000000000002 /* AidenForeignRunObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000102 /* AidenForeignRunObserver.swift */; }; + F6A100000000000000000003 /* AidenPendingSendCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000103 /* AidenPendingSendCoordinator.swift */; }; + F6A100000000000000000004 /* AidenChatMutationSubMachines.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000104 /* AidenChatMutationSubMachines.swift */; }; + F6A100000000000000000005 /* AidenForeignRunObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000105 /* AidenForeignRunObserverTests.swift */; }; + F6A100000000000000000006 /* AidenPendingSendCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000106 /* AidenPendingSendCoordinatorTests.swift */; }; + F6A100000000000000000007 /* AidenChatMutationSubMachinesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000107 /* AidenChatMutationSubMachinesTests.swift */; }; + F6A100000000000000000008 /* ComposerVoiceInputControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A100000000000000000108 /* ComposerVoiceInputControllerTests.swift */; }; F5A100000000000000000001 /* AidenRemoteFailureClassification.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A100000000000000000101 /* AidenRemoteFailureClassification.swift */; }; F5A100000000000000000002 /* AidenDurablePendingMutation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A100000000000000000102 /* AidenDurablePendingMutation.swift */; }; F5A100000000000000000003 /* AidenRemoteFailureClassificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5A100000000000000000103 /* AidenRemoteFailureClassificationTests.swift */; }; @@ -313,6 +321,14 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + F6A100000000000000000101 /* AidenHostConnectionLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenHostConnectionLifecycle.swift; sourceTree = ""; }; + F6A100000000000000000102 /* AidenForeignRunObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenForeignRunObserver.swift; sourceTree = ""; }; + F6A100000000000000000103 /* AidenPendingSendCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenPendingSendCoordinator.swift; sourceTree = ""; }; + F6A100000000000000000104 /* AidenChatMutationSubMachines.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatMutationSubMachines.swift; sourceTree = ""; }; + F6A100000000000000000105 /* AidenForeignRunObserverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenForeignRunObserverTests.swift; sourceTree = ""; }; + F6A100000000000000000106 /* AidenPendingSendCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenPendingSendCoordinatorTests.swift; sourceTree = ""; }; + F6A100000000000000000107 /* AidenChatMutationSubMachinesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatMutationSubMachinesTests.swift; sourceTree = ""; }; + F6A100000000000000000108 /* ComposerVoiceInputControllerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposerVoiceInputControllerTests.swift; sourceTree = ""; }; F5A100000000000000000101 /* AidenRemoteFailureClassification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenRemoteFailureClassification.swift; sourceTree = ""; }; F5A100000000000000000102 /* AidenDurablePendingMutation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenDurablePendingMutation.swift; sourceTree = ""; }; F5A100000000000000000103 /* AidenRemoteFailureClassificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenRemoteFailureClassificationTests.swift; sourceTree = ""; }; @@ -714,6 +730,10 @@ F5A100000000000000000105 /* AidenBotResumeModelTests.swift */, F5A100000000000000000104 /* AidenDurablePendingMutationTests.swift */, F5A100000000000000000103 /* AidenRemoteFailureClassificationTests.swift */, + F6A100000000000000000105 /* AidenForeignRunObserverTests.swift */, + F6A100000000000000000106 /* AidenPendingSendCoordinatorTests.swift */, + F6A100000000000000000107 /* AidenChatMutationSubMachinesTests.swift */, + F6A100000000000000000108 /* ComposerVoiceInputControllerTests.swift */, D0A100000000000000000017 /* AidenBotOpenWorkTests.swift */, B0E700000000000000000011 /* AidenRemoteContractFixture.swift */, B07C00000000000000000012 /* AidenBotGeneratedAvatarTests.swift */, @@ -893,6 +913,7 @@ children = ( A0E200000000000000000017 /* AidenHostConnectScheduler.swift */, A0E200000000000000000011 /* AidenHostConnection.swift */, + F6A100000000000000000101 /* AidenHostConnectionLifecycle.swift */, A0E200000000000000000014 /* AidenHostRegistry.swift */, ); path = Hosts; @@ -1010,6 +1031,9 @@ A7C100000000000000000009 /* AidenChatViewModel+Recordings.swift */, A7C10000000000000000000A /* AidenChatViewModel+ComposerPower.swift */, A7C10000000000000000000B /* AidenChatViewModel+ForeignRuns.swift */, + F6A100000000000000000102 /* AidenForeignRunObserver.swift */, + F6A100000000000000000103 /* AidenPendingSendCoordinator.swift */, + F6A100000000000000000104 /* AidenChatMutationSubMachines.swift */, A7C10000000000000000000D /* AidenChatCards.swift */, B6B100000000000000000002 /* AidenTypedApprovalCard.swift */, A7C10000000000000000000E /* AidenChronologicalTranscript.swift */, @@ -1402,6 +1426,9 @@ A7C200000000000000000009 /* AidenChatViewModel+Recordings.swift in Sources */, A7C20000000000000000000A /* AidenChatViewModel+ComposerPower.swift in Sources */, A7C20000000000000000000B /* AidenChatViewModel+ForeignRuns.swift in Sources */, + F6A100000000000000000002 /* AidenForeignRunObserver.swift in Sources */, + F6A100000000000000000003 /* AidenPendingSendCoordinator.swift in Sources */, + F6A100000000000000000004 /* AidenChatMutationSubMachines.swift in Sources */, A7C20000000000000000000D /* AidenChatCards.swift in Sources */, B6B000000000000000000002 /* AidenTypedApprovalCard.swift in Sources */, A7C20000000000000000000E /* AidenChronologicalTranscript.swift in Sources */, @@ -1493,6 +1520,7 @@ A2E000000000000000000005 /* AidenWorkspacesTabView.swift in Sources */, A4B240000000000000000002 /* AidenSearchTabView.swift in Sources */, A0E200000000000000000001 /* AidenHostConnection.swift in Sources */, + F6A100000000000000000001 /* AidenHostConnectionLifecycle.swift in Sources */, A0E200000000000000000004 /* AidenHostRegistry.swift in Sources */, 1A2B3C4D5E6F700000000001 /* AidenOnTheGoApp.swift in Sources */, 1A2B3C4D5E6F700000000002 /* ContentView.swift in Sources */, @@ -1550,6 +1578,10 @@ F5A100000000000000000005 /* AidenBotResumeModelTests.swift in Sources */, F5A100000000000000000004 /* AidenDurablePendingMutationTests.swift in Sources */, F5A100000000000000000003 /* AidenRemoteFailureClassificationTests.swift in Sources */, + F6A100000000000000000005 /* AidenForeignRunObserverTests.swift in Sources */, + F6A100000000000000000006 /* AidenPendingSendCoordinatorTests.swift in Sources */, + F6A100000000000000000007 /* AidenChatMutationSubMachinesTests.swift in Sources */, + F6A100000000000000000008 /* ComposerVoiceInputControllerTests.swift in Sources */, D0A100000000000000000007 /* AidenBotOpenWorkTests.swift in Sources */, B0E700000000000000000001 /* AidenRemoteContractFixture.swift in Sources */, A0DB00000000000000000002 /* AidenNativeIntegrationTests.swift in Sources */, diff --git a/ios/AidenOnTheGo/Features/Chat/AidenChatMutationSubMachines.swift b/ios/AidenOnTheGo/Features/Chat/AidenChatMutationSubMachines.swift new file mode 100644 index 0000000000..c16ea4a5e6 --- /dev/null +++ b/ios/AidenOnTheGo/Features/Chat/AidenChatMutationSubMachines.swift @@ -0,0 +1,334 @@ +import Foundation +import Observation + +/// Explicit sub-machines extracted from `AidenChatViewModel` for chat-level +/// mutations and authority snapshot reads: +/// - `AidenWorktreeSetupMachine`: revision-53 worktree setup + cancel-after-finish guard +/// - `AidenChatForkAttemptMachine`: idempotent chat fork key retention +/// - `AidenContinueInNewChatAttemptMachine`: idempotent continue-in-new-chat key retention +/// - `AidenApprovalSnapshotFence` / `AidenQuestionSnapshotFence`: monotonic snapshot read fences +@MainActor +struct AidenChatMutationSubMachines { + let worktreeSetup = AidenWorktreeSetupMachine() + var forkAttempt = AidenChatForkAttemptMachine() + var continueInNewChatAttempt = AidenContinueInNewChatAttemptMachine() + var approvalSnapshots = AidenApprovalSnapshotFence() + var questionSnapshots = AidenQuestionSnapshotFence() +} + +// MARK: - Worktree Setup (contract revision 53) + +/// Owns the first-message worktree setup task, its per-text idempotency key, +/// and the `worktreeSetupCanceled` cancel-after-finish guard. +@MainActor +@Observable +final class AidenWorktreeSetupMachine { + struct Attempt: Equatable, Sendable { + let text: String + let idempotencyKey: UUID + } + + enum Phase: Equatable, Sendable { + case idle + case settingUp(attempt: Attempt, canceled: Bool) + } + + private(set) var phase: Phase = .idle + @ObservationIgnored private(set) var retainedAttempt: Attempt? + @ObservationIgnored private var setupTask: Task? + + deinit { + setupTask?.cancel() + } + + var isSettingUp: Bool { + if case .settingUp = phase { return true } + return false + } + + /// True if Cancel was pressed during the active setup. A task that already + /// finished ignores `Task.cancel()`, so the press is preserved here. + var isCanceled: Bool { + if case .settingUp(_, let canceled) = phase { return canceled } + return false + } + + /// Reuses the retained key when retrying the exact same prompt text, or + /// mints a fresh key otherwise. + @discardableResult + func begin(for text: String, makeKey: () -> UUID = UUID.init) -> Attempt { + let attempt: Attempt + if let existing = retainedAttempt, existing.text == text { + attempt = existing + } else { + attempt = Attempt(text: text, idempotencyKey: makeKey()) + retainedAttempt = attempt + } + phase = .settingUp(attempt: attempt, canceled: false) + return attempt + } + + /// Stops waiting for the worktree. Preserves the cancel signal even if the + /// underlying task already resolved before cancellation propagated. + func cancel() { + guard case .settingUp(let attempt, _) = phase else { return } + phase = .settingUp(attempt: attempt, canceled: true) + setupTask?.cancel() + } + + /// Evaluates the cancel-after-finish guard once setup completes. + func shouldThrowCancellationAfterFinish(taskWasCancelled: Bool) -> Bool { + taskWasCancelled || isCanceled + } + + /// Records a failed worktree request, spending the retained key only when + /// `AidenNewWorktreeRetry.spendsKey(_:)` proves the failure is terminal. + func recordFailure(_ error: Error) { + if AidenNewWorktreeRetry.spendsKey(error) { + retainedAttempt = nil + } + } + + /// Clears the retained key after the chat has moved into the new worktree. + func recordMoved() { + retainedAttempt = nil + } + + /// Ends the active setup phase without disturbing `retainedAttempt`. + func endPhase() { + phase = .idle + setupTask = nil + } + + /// Runs a worktree setup operation under this machine's lifecycle, applying + /// `onMoved` before enforcing the cancel-after-finish guard so a worktree + /// created just as Cancel was pressed is still adopted while the message + /// stays unsent. + /// + /// Returns `false` if `onMoved` reported that the chat was removed or its + /// owner context is no longer live (caller should stop immediately). + func execute( + text: String, + makeKey: () -> UUID = UUID.init, + operation: @escaping @MainActor (UUID) async throws -> AidenChatNewWorktree, + onMoved: @MainActor (AidenChatNewWorktree) async -> Bool + ) async throws -> Bool { + let attempt = begin(for: text, makeKey: makeKey) + let setup = Task { try await operation(attempt.idempotencyKey) } + setupTask = setup + defer { endPhase() } + let moved: AidenChatNewWorktree + do { + moved = try await withTaskCancellationHandler { + try await setup.value + } onCancel: { + setup.cancel() + } + } catch { + recordFailure(error) + throw error + } + let shouldContinue = await onMoved(moved) + guard shouldContinue else { return false } + recordMoved() + if shouldThrowCancellationAfterFinish(taskWasCancelled: setup.isCancelled) { + throw CancellationError() + } + return true + } +} + +// MARK: - Fork & Continue-in-New-Chat Attempt Retention + +/// Explicit idempotency-key retention sub-machine for `fork(messageId:action:summaryFocus:)`. +struct AidenChatForkAttemptMachine: Equatable { + var retained: AidenChatForkAttempt? + + mutating func begin( + context: AidenRemoteRequestContext, + request: AidenChatForkAttempt.Request, + makeKey: () -> UUID = UUID.init + ) -> AidenChatForkAttempt { + let attempt = AidenChatForkAttempt.retaining( + retained, + context: context, + request: request, + makeKey: makeKey + ) + retained = attempt + return attempt + } + + mutating func recordSuccess(_ attempt: AidenChatForkAttempt) { + if retained == attempt { + retained = nil + } + } + + mutating func recordFailure(_ error: Error, for attempt: AidenChatForkAttempt) { + if aidenIsCancellation(error) { + // A cancelled request may already have reached the Mac; keep the key. + return + } + if retained == attempt, !AidenChatForkAttempt.outcomeIsUnknown(after: error) { + retained = nil + } + } +} + +/// Explicit idempotency-key retention sub-machine for `continueInNewChat(workspaceId:)`. +struct AidenContinueInNewChatAttemptMachine: Equatable { + var retained: AidenContinueInNewChatAttempt? + + mutating func begin( + context: AidenRemoteRequestContext, + chatId: String, + revision: String, + workspaceId: String, + makeKey: () -> UUID = UUID.init + ) -> AidenContinueInNewChatAttempt { + if let existing = retained, + existing.context == context, + existing.chatId == chatId, + existing.revision == revision, + existing.workspaceId == workspaceId { + return existing + } + let attempt = AidenContinueInNewChatAttempt( + context: context, + chatId: chatId, + revision: revision, + workspaceId: workspaceId, + idempotencyKey: makeKey() + ) + retained = attempt + return attempt + } + + mutating func recordSuccess(_ attempt: AidenContinueInNewChatAttempt) { + if retained == attempt { + retained = nil + } + } + + mutating func recordFailure(_ error: Error, for attempt: AidenContinueInNewChatAttempt) { + if aidenIsCancellation(error) { + // A cancelled request may already have reached the computer; keep the key. + return + } + if retained == attempt, !AidenChatForkAttempt.outcomeIsUnknown(after: error) { + retained = nil + } + } +} + +// MARK: - Approval & Question Snapshot Generation Fences + +/// Monotonic fence for `restorePendingApproval` reads, including fallback +/// coalescing so a fallback read never duplicates an identical in-flight read. +struct AidenApprovalSnapshotFence: Equatable { + struct Token: Equatable { + let generation: UInt64 + let streamID: String + let context: AidenRemoteRequestContext + let expectedApproval: AidenPendingApproval? + let expectedState: AidenStreamState? + } + + private(set) var generation: UInt64 = 0 + private(set) var inFlight: Token? + + /// Starts a fenced approval snapshot read. Returns `nil` when `isFallback` + /// is true and an identical live read is already in flight. + mutating func begin( + streamID: String, + context: AidenRemoteRequestContext, + pendingApproval: AidenPendingApproval?, + streamState: AidenStreamState?, + isFallback: Bool, + isInFlightContextLive: Bool + ) -> Token? { + if isFallback, + let read = inFlight, + read.streamID == streamID, + isInFlightContextLive, + read.expectedApproval == pendingApproval, + read.expectedState == streamState { + return nil + } + generation &+= 1 + let token = Token( + generation: generation, + streamID: streamID, + context: context, + expectedApproval: pendingApproval, + expectedState: streamState + ) + inFlight = token + return token + } + + /// True only when the snapshot response still matches the current + /// generation, active stream, expected approval/state, and live context. + func accepts( + _ token: Token, + activeStreamID: String?, + pendingApproval: AidenPendingApproval?, + streamState: AidenStreamState?, + isRemoved: Bool, + isContextLive: Bool + ) -> Bool { + !isRemoved + && isContextLive + && activeStreamID == token.streamID + && token.generation == generation + && pendingApproval == token.expectedApproval + && streamState == token.expectedState + } + + mutating func finish(_ token: Token) { + if token.generation == generation { + inFlight = nil + } + } +} + +/// Monotonic fence for `restorePendingQuestion` reads. +struct AidenQuestionSnapshotFence: Equatable { + struct Token: Equatable { + let generation: UInt64 + let streamID: String + let expectedQuestion: AidenPendingQuestion? + let expectedState: AidenStreamState? + } + + private(set) var generation: UInt64 = 0 + + mutating func begin( + streamID: String, + pendingQuestion: AidenPendingQuestion?, + streamState: AidenStreamState? + ) -> Token { + generation &+= 1 + return Token( + generation: generation, + streamID: streamID, + expectedQuestion: pendingQuestion, + expectedState: streamState + ) + } + + func accepts( + _ token: Token, + activeStreamID: String?, + pendingQuestion: AidenPendingQuestion?, + streamState: AidenStreamState?, + isContextLive: Bool + ) -> Bool { + isContextLive + && activeStreamID == token.streamID + && token.generation == generation + && pendingQuestion == token.expectedQuestion + && streamState == token.expectedState + } +} diff --git a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift index 3571002ad7..9f4cb36c88 100644 --- a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift +++ b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift @@ -3,51 +3,36 @@ import Foundation // MARK: - Contract revision 24: foreign runs /// Observation and control of a run this phone did not start (on the Mac, in -/// Telegram or from the scheduler). The phone attaches when the chat loads and -/// the Mac advertises `phone-run-control-v1`. Events are reduced by the pure -/// `AidenForeignRunProjection` and mirrored into the same published state an -/// owned stream uses, so the transcript, approval card, question card, Stop -/// control and Live Activity render unchanged. +/// Telegram or from the scheduler). Lifecycle, probing, attach/reconnect, and +/// recovery live in `AidenForeignRunObserver`; this extension binds them to +/// `AidenChatViewModel`'s published transcript, Live Activities, and control +/// actions. extension AidenChatViewModel { - /// Frames retained from an already finished run arrive back to back. - /// Publishing waits for this quiet period so opening a chat never replays - /// a finished run as if it were live. - static let foreignRunSettleInterval: Duration = .milliseconds(400) - static let foreignRunMaxReconnects = 3 - static let foreignRunMaxReconcileAttempts = 6 - /// A run the roster announced may not be registered on the Mac yet when - /// the phone first asks for it; one retry after this long covers that. - static let announcedRunRetryDelay: Duration = .milliseconds(400) + static let foreignRunSettleInterval: Duration = AidenForeignRunObserver.settleInterval + static let foreignRunMaxReconnects = AidenForeignRunObserver.maxReconnects + static let foreignRunMaxReconcileAttempts = AidenForeignRunObserver.maxReconcileAttempts + static let announcedRunRetryDelay: Duration = AidenForeignRunObserver.announcedRunRetryDelay - /// Why the phone is looking for a run it did not start. - enum ForeignRunAttachReason: Sendable { - /// The chat opened or reloaded; its transcript was just read. - case load - /// The agent roster reported a new turn. - case announcedTurn - /// The first roster this chat received named a turn. It is usually the - /// last finished one, so a missing run is not looked for again. - case firstRosterTurn - /// A foreground check on a device that cannot read the agent roster. - case probe - } + typealias ForeignRunAttachReason = AidenForeignRunObserver.AttachReason /// Delay before the foreground probe's next check, after `idleProbes` /// consecutive checks that found nothing live: 5s, 10s, 20s, then 30s. static func foreignRunProbeDelay(afterIdleProbes idleProbes: Int) -> Duration { - .seconds(min(30, 5 << min(max(idleProbes, 0), 3))) + AidenForeignRunObserver.probeDelay(afterIdleProbes: idleProbes) } - var isObservingForeignRun: Bool { foreignRun != nil && foreignRunIsLive } + var isObservingForeignRun: Bool { foreignRunObserver.isObservingLive } /// Whether a lookup for, or observation of, a foreign run is in flight. - var isLookingForForeignRun: Bool { foreignRunTask != nil } + var isLookingForForeignRun: Bool { foreignRunObserver.isLookingForRun } + + var isProbingForForeignRuns: Bool { foreignRunObserver.isProbing } func startForeignRunObservationIfNeeded( context: AidenRemoteRequestContext, reason: ForeignRunAttachReason = .load ) { - guard !isReadOnlyFixture, !isRemoved, foreignRunTask == nil, + guard !isReadOnlyFixture, !isRemoved, !foreignRunObserver.isLookingForRun, activeStreamID == nil, !isStarting, coordinator.isLive(context), ownerServer?.canObserveForeignRuns == true, let installation = ownerInstallation, @@ -55,36 +40,32 @@ extension AidenChatViewModel { installation.hasNegotiatedAccess(to: .runsObserve), installation.deviceCapabilities.contains(.chatRead), chat.botId == nil || installation.hasNegotiatedAccess(to: .botRead) else { return } - foreignRunGeneration &+= 1 - let generation = foreignRunGeneration - foreignRunLookupIsProbes = reason == .probe - foreignRunTask = Task { [weak self] in - await self?.observeForeignRun(context: context, generation: generation, reason: reason) - self?.attachToTurnAnnouncedDuringObservation() - } + foreignRunObserver.startObservation( + context: context, + reason: reason, + host: makeForeignRunObserverHost() + ) } /// The roster reported a new turn: attach to its run unless a reply is /// already live here. A lookup still in flight may have been answered /// before this turn's run registered, so the turn waits for it to end and /// is looked up then. A run that lookup already showed or read is - /// recognised by `foreignRunAccountedRunId` and not replayed or read again. - /// The turn also waits while this phone restores its own stream, which - /// may be the announced turn's run. + /// recognised by `foreignRunObserver.accountedRunId` and not replayed or + /// read again. The turn also waits while this phone restores its own + /// stream, which may be the announced turn's run. func attachToAnnouncedTurn(reason: ForeignRunAttachReason) { guard !isReadOnlyFixture, !isRemoved, activeStreamID == nil, !isStarting, let context = liveOwner else { return } - if foreignRunTask != nil || isRestoringStream { - // A newer announced turn keeps the not-found retry. - if turnAwaitingLookup != .announcedTurn { turnAwaitingLookup = reason } + if foreignRunObserver.isLookingForRun || isRestoringStream { + foreignRunObserver.queueAnnouncedTurn(reason: reason) return } startForeignRunObservationIfNeeded(context: context, reason: reason) } func attachToTurnAnnouncedDuringObservation() { - guard let reason = turnAwaitingLookup, foreignRunTask == nil, !Task.isCancelled else { return } - turnAwaitingLookup = nil + guard let reason = foreignRunObserver.consumeQueuedAnnouncedTurn() else { return } attachToAnnouncedTurn(reason: reason) } @@ -92,253 +73,127 @@ extension AidenChatViewModel { /// that cannot read the agent roster. It stops with progress observation, /// which the chat ends when it leaves the screen or the app the foreground. func startForeignRunProbeIfNeeded() { - guard !isReadOnlyFixture, !isRemoved, foreignRunProbeTask == nil, !canReadAgentRoster, - ownerServer?.canObserveForeignRuns == true else { return } - foreignRunProbeGeneration &+= 1 - let generation = foreignRunProbeGeneration - foreignRunProbeTask = Task { [weak self] in - await self?.probeForForeignRuns(generation: generation) - guard let self, generation == self.foreignRunProbeGeneration else { return } - self.foreignRunProbeTask = nil - } + let canStart = !isReadOnlyFixture && !isRemoved && !canReadAgentRoster + && ownerServer?.canObserveForeignRuns == true + foreignRunObserver.startProbeIfNeeded( + canStart: canStart, + nextStep: { [weak self] in + guard let self, !self.isRemoved, !self.canReadAgentRoster, + let context = self.liveOwner else { return .stop } + if self.activeStreamID != nil || self.isStarting || self.isRestoringStream + || self.foreignRunObserver.isLookingForRun { + return .deferWhileBusy + } + return .attach(context) + }, + startAttach: { [weak self] context, reason in + guard let self else { return nil } + self.startForeignRunObservationIfNeeded(context: context, reason: reason) + return self.foreignRunObserver.attachTask + } + ) } func stopForeignRunProbe() { - foreignRunProbeGeneration &+= 1 - foreignRunProbeTask?.cancel() - foreignRunProbeTask = nil - // Its lookup goes too, or it asks the machine again after the chat has - // left. A run it found stays on, as any live run does. - guard foreignRunLookupIsProbes, foreignRunTask != nil, foreignRun == nil else { return } - foreignRunTask?.cancel() - endForeignRunObservation(preservingRecovery: true) - } - - var isProbingForForeignRuns: Bool { foreignRunProbeTask != nil } - - private func probeForForeignRuns(generation: UInt64) async { - var idleProbes = 0 - while generation == foreignRunProbeGeneration, !Task.isCancelled { - do { - try await foreignRunProbeSleep(Self.foreignRunProbeDelay(afterIdleProbes: idleProbes)) - } catch { - return - } - guard generation == foreignRunProbeGeneration, !Task.isCancelled, - !isRemoved, !canReadAgentRoster, - let context = liveOwner else { return } - if activeStreamID != nil || isStarting || isRestoringStream || foreignRunTask != nil { - // A reply is already live here; check again soon after it ends. - idleProbes = 0 - continue - } - let shownLive = foreignRunsShownLive - startForeignRunObservationIfNeeded(context: context, reason: .probe) - // The device or Mac no longer allows observing runs. - guard let attach = foreignRunTask else { return } - await attach.value - idleProbes = foreignRunsShownLive == shownLive ? idleProbes + 1 : 0 + foreignRunObserver.stopProbe(hasActiveStream: activeStreamID != nil) { [weak self] in + self?.clearForeignLiveOutputAndPrompts() } } /// Stops observing, and drops a turn announced during the stopped lookup. func stopForeignRunObservation() { - turnAwaitingLookup = nil - foreignRunTask?.cancel() - endForeignRunObservation(preservingRecovery: false) - } - - /// Ends observation from within the lookup itself, so a turn announced - /// while it ran is still looked up once it returns. `preservingRecovery` - /// keeps a finished run's response, still awaiting its transcript, on - /// screen while a later attach finds nothing live. - private func endForeignRunObservation(preservingRecovery: Bool) { - foreignRunGeneration &+= 1 - foreignRunTask = nil - foreignRunSettleTask?.cancel() - foreignRunSettleTask = nil - // An ended run still awaiting its transcript is presented too. - var wasLive = foreignRunIsLive - if !preservingRecovery, let recovery = foreignRunReconcileTask { - recovery.cancel() - foreignRunReconcileTask = nil - wasLive = true - } - foreignRun = nil - foreignRunIsLive = false - if wasLive, activeStreamID == nil { - replaceLiveText("") - reasoning = "" - tools = [] - activityTimeline = nil - pendingApproval = nil - pendingQuestion = nil + foreignRunObserver.stopObservation(hasActiveStream: activeStreamID != nil) { [weak self] in + self?.clearForeignLiveOutputAndPrompts() } } - private func isCurrentForeignRun(_ generation: UInt64, context: AidenRemoteRequestContext) -> Bool { - !Task.isCancelled && !isRemoved && generation == foreignRunGeneration - && coordinator.isLive(context) && activeStreamID == nil && !isStarting - } - - private func observeForeignRun( - context: AidenRemoteRequestContext, - generation: UInt64, - reason: ForeignRunAttachReason - ) async { - defer { - if generation == foreignRunGeneration { foreignRunTask = nil } - } - var reconnects = 0 - var retriedAnnouncedRun = false - /// Waits once for an announced run the Mac has not registered yet. - func retryAnnouncedRun() async -> Bool { - guard reason == .announcedTurn, !retriedAnnouncedRun else { return false } - retriedAnnouncedRun = true - try? await announcedRunRetrySleep(Self.announcedRunRetryDelay) - return true - } - attach: while isCurrentForeignRun(generation, context: context) { - let client: AidenRemoteClient - do { - client = try coordinator.remoteClient(for: context) - } catch { - return - } - let events = foreignRun.map { client.runEvents(runId: $0.runId, after: $0.lastSequence) } - ?? client.currentRunEvents(chatId: chat.id) - do { - for try await event in events { - guard isCurrentForeignRun(generation, context: context) else { return } - reconnects = 0 - switch await applyForeignRunEvent(event, context: context, generation: generation) { - case .keepObserving: - continue - case .stop: - return - case let .endedBeforeAttach(runId): - let isNewRun = runId != foreignRunAccountedRunId - if !isNewRun { - // The newest retained run is one already accounted - // for: an announced run may not be registered yet. - discardUnsettledForeignRun() - if await retryAnnouncedRun() { continue attach } - } - // The load may have read the transcript before the Mac - // committed the reply. Terminal replay settles that read - // even though historical activity stays off screen. - guard isCurrentForeignRun(generation, context: context) else { return } - foreignRunAccountedRunId = runId - await endForeignRunQuietly(context: context, reconcile: isNewRun) - return - } - } - } catch let error where aidenIsCancellation(error) { - return - } catch { - if await coordinator.handleCredentialRevocation(error, context: context) { - stopForeignRunObservation() - return + private func makeForeignRunObserverHost() -> AidenForeignRunObserver.Host { + AidenForeignRunObserver.Host( + currencyInputs: { [weak self] context in + guard let self else { + return AidenForeignRunObserver.CurrencyInputs( + isTaskCancelled: true, + isRemoved: true, + isContextLive: false, + hasActiveStream: false, + isStarting: false + ) } - guard isCurrentForeignRun(generation, context: context) else { return } - if case let .server(statusCode, _)? = error as? AidenRemoteClientError, - statusCode < 500 { - // No retained run (run_gone), or this device may not see it. - let neverFound = foreignRun == nil - if statusCode == 404, neverFound, await retryAnnouncedRun() { continue attach } - if statusCode == 404, neverFound, reason == .announcedTurn { - // The announced run cannot be observed; its outcome - // still reaches the transcript. - await reconcileChat(context: context) - guard generation == foreignRunGeneration else { return } - } - await endForeignRunQuietly(context: context, reconcile: foreignRunIsLive) - return + return AidenForeignRunObserver.CurrencyInputs( + isTaskCancelled: Task.isCancelled, + isRemoved: self.isRemoved, + isContextLive: self.coordinator.isLive(context), + hasActiveStream: self.activeStreamID != nil, + isStarting: self.isStarting + ) + }, + isRemoved: { [weak self] in self?.isRemoved ?? true }, + hasActiveStream: { [weak self] in self?.activeStreamID != nil }, + openEventStream: { [weak self] context, currentProjection in + guard let self else { throw CancellationError() } + let client = try self.coordinator.remoteClient(for: context) + return currentProjection.map { client.runEvents(runId: $0.runId, after: $0.lastSequence) } + ?? client.currentRunEvents(chatId: self.chat.id) + }, + handleCredentialRevocation: { [weak self] error, context in + guard let self else { return false } + return await self.coordinator.handleCredentialRevocation(error, context: context) + }, + reconcileChat: { [weak self] context in + guard let self else { return false } + return await self.reconcileChat(context: context) + }, + bumpTranscriptGeneration: { [weak self] in + self?.transcriptGeneration &+= 1 + }, + onGoLive: { [weak self] projection, context in + await self?.handleForeignRunWentLive(projection, context: context) + }, + onPublishUpdate: { [weak self] projection, flushingText, context in + self?.publishForeignRun(projection, context: context, flushingText: flushingText) + }, + onPerformEffect: { [weak self] effect, runId, context in + guard let self else { return true } + return await self.performForeignRunEffect(effect, runId: runId, context: context) + }, + onReconnectExhaustedLive: { [weak self] runId, _ in + guard let self else { return } + self.streamState = .reconciling + await self.liveActivities.markStale(instanceID: self.instanceId, streamID: runId) + }, + onFlushBeforeQuietEnd: { [weak self] in + self?.flushPendingStreamingContent() + }, + onEndedQuietlyLive: { [weak self] finalState, reconciled in + guard let self else { return } + self.pendingApproval = nil + self.pendingQuestion = nil + if finalState == nil, self.streamState?.isTerminal != true { self.streamState = nil } + if reconciled { + self.clearForeignLiveOutput() } + }, + onClearLiveOutput: { [weak self] in + self?.clearForeignLiveOutput() + }, + onClearLiveOutputAndPrompts: { [weak self] in + self?.clearForeignLiveOutputAndPrompts() + }, + onObservationFinished: { [weak self] in + self?.attachToTurnAnnouncedDuringObservation() } - reconnects += 1 - guard reconnects <= Self.foreignRunMaxReconnects, - isCurrentForeignRun(generation, context: context) else { break } - try? await Task.sleep(for: .seconds(reconnects)) - } - guard generation == foreignRunGeneration, !isRemoved else { return } - if foreignRunIsLive, let runId = foreignRun?.runId { - streamState = .reconciling - await liveActivities.markStale(instanceID: instanceId, streamID: runId) - await endForeignRunQuietly(context: context, reconcile: true) - } else { - endForeignRunObservation(preservingRecovery: true) - } - } - - private enum ForeignRunStep { - case keepObserving - case stop - /// A finished run replayed on attach: nothing to show live. - case endedBeforeAttach(runId: String) - } - - private func applyForeignRunEvent( - _ event: AidenRemoteRunEvent, - context: AidenRemoteRequestContext, - generation: UInt64 - ) async -> ForeignRunStep { - if foreignRun == nil { - foreignRun = AidenForeignRunProjection(runId: event.runId) - scheduleForeignRunSettle(context: context, generation: generation) - } - guard var projection = foreignRun else { return .stop } - let effects = projection.apply(event) - foreignRun = projection - guard foreignRunIsLive else { - return projection.isEnded ? .endedBeforeAttach(runId: projection.runId) : .keepObserving - } - var flushesText = true - if case let .content(content) = event.kind { - flushesText = content.type != .textDelta && content.type != .heartbeat - } - publishForeignRun(context: context, flushingText: flushesText) - for effect in effects { - guard isCurrentForeignRun(generation, context: context) else { return .stop } - if await performForeignRunEffect(effect, runId: projection.runId, context: context) { return .stop } - } - return .keepObserving - } - - /// Drops a replay that never went live so the next attach starts afresh. - private func discardUnsettledForeignRun() { - guard !foreignRunIsLive else { return } - foreignRunSettleTask?.cancel() - foreignRunSettleTask = nil - foreignRun = nil - } - - private func scheduleForeignRunSettle(context: AidenRemoteRequestContext, generation: UInt64) { - foreignRunSettleTask?.cancel() - foreignRunSettleTask = Task { [weak self] in - try? await Task.sleep(for: Self.foreignRunSettleInterval) - guard !Task.isCancelled, let self, - self.isCurrentForeignRun(generation, context: context), - let projection = self.foreignRun, !projection.isEnded else { return } - await self.goLiveWithForeignRun(projection, context: context) - } + ) } - private func goLiveWithForeignRun( + private func handleForeignRunWentLive( _ projection: AidenForeignRunProjection, context: AidenRemoteRequestContext ) async { - // A newly live run owns the live output from here on. - foreignRunReconcileTask?.cancel() - foreignRunReconcileTask = nil - foreignRunIsLive = true - foreignRunAccountedRunId = projection.runId - foreignRunsShownLive += 1 // The retained replay lands at once: text it holds before a tool, // approval or other structural state shows before that state. let carriesStructure = !projection.tools.isEmpty || !projection.reasoning.isEmpty || projection.pendingApproval != nil || projection.pendingQuestion != nil || projection.timeline != nil - publishForeignRun(context: context, flushingText: carriesStructure) + publishForeignRun(projection, context: context, flushingText: carriesStructure) await liveActivities.start( instanceID: instanceId, deviceID: context.deviceId, @@ -353,8 +208,12 @@ extension AidenChatViewModel { } } - private func publishForeignRun(context: AidenRemoteRequestContext, flushingText: Bool = false) { - guard let projection = foreignRun, foreignRunIsLive, activeStreamID == nil else { return } + private func publishForeignRun( + _ projection: AidenForeignRunProjection? = nil, + context: AidenRemoteRequestContext, + flushingText: Bool = false + ) { + guard let projection = projection ?? foreignRun, foreignRunIsLive, activeStreamID == nil else { return } receiveCumulativeLiveText(projection.liveText) // As on an owned stream, text received before a tool, approval or // other structural event shows before it lands. @@ -439,7 +298,7 @@ extension AidenChatViewModel { && installation.hasNegotiatedAccess(to: .botWrite)) } - /// Returns true when observation should stop. + /// Returns true when observation should stop (the observer then ends quietly). private func performForeignRunEffect( _ effect: AidenForeignRunProjection.Effect, runId: String, @@ -485,45 +344,11 @@ extension AidenChatViewModel { message: String(localized: "Response cancelled") ) } - await endForeignRunQuietly(context: context, reconcile: true) return true } return false } - private func endForeignRunQuietly(context: AidenRemoteRequestContext, reconcile: Bool) async { - if foreignRunIsLive, activeStreamID == nil { flushPendingStreamingContent() } - let generation = foreignRunGeneration - var reconciled = true - if reconcile { - reconciled = await reconcileChat(context: context) - } - guard isCurrentForeignRun(generation, context: context) else { return } - foreignRunGeneration &+= 1 - foreignRunSettleTask?.cancel() - foreignRunSettleTask = nil - foreignRunTask = nil - let wasLive = foreignRunIsLive - let finalState = foreignRun?.endState - foreignRun = nil - foreignRunIsLive = false - guard activeStreamID == nil else { return } - if !wasLive { - if !reconciled { scheduleForeignRunReconciliation(context: context) } - return - } - pendingApproval = nil - pendingQuestion = nil - if finalState == nil, streamState?.isTerminal != true { streamState = nil } - if reconciled { - clearForeignLiveOutput() - } else { - // Keep the response the user was watching until the transcript that - // holds it is accepted. Only the chat is re-read; nothing is resent. - scheduleForeignRunReconciliation(context: context) - } - } - private func clearForeignLiveOutput() { replaceLiveText("") reasoning = "" @@ -531,34 +356,10 @@ extension AidenChatViewModel { activityTimeline = nil } - private func scheduleForeignRunReconciliation(context: AidenRemoteRequestContext) { - guard foreignRunReconcileTask == nil else { return } - foreignRunReconcileTask = Task { [weak self] in - for attempt in 0.. Bool { - Task.isCancelled || isRemoved || !coordinator.isLive(context) || activeStreamID != nil - || isStarting || foreignRunIsLive + private func clearForeignLiveOutputAndPrompts() { + clearForeignLiveOutput() + pendingApproval = nil + pendingQuestion = nil } func stopForeignRun() async -> Bool { @@ -615,7 +416,7 @@ extension AidenChatViewModel { && approval.scopes.contains(scope) ? scope : nil isRespondingToApproval = true defer { isRespondingToApproval = false } - foreignRun?.markAnsweredLocally(approval.id) + foreignRunObserver.markAnsweredLocally(approval.id) publishForeignRun(context: context) onSend?() do { @@ -638,7 +439,7 @@ extension AidenChatViewModel { if await coordinator.handleCredentialRevocation(error, context: context) { return } guard coordinator.isLive(context) else { return } retractApprovalAnsweredLine() - foreignRun?.answerUnconfirmed(approval.id) + foreignRunObserver.answerUnconfirmed(approval.id) if let loser = AidenForeignRunResolution.loser(from: error) { showForeignRunNotice(loser.notice) return @@ -658,7 +459,7 @@ extension AidenChatViewModel { canRespondToForeignQuestions(context: context) else { return } isRespondingToQuestion = true defer { isRespondingToQuestion = false } - foreignRun?.markAnsweredLocally(question.id) + foreignRunObserver.markAnsweredLocally(question.id) publishForeignRun(context: context) do { _ = try await coordinator.remoteClient(for: context).respondToRunQuestion( @@ -674,7 +475,7 @@ extension AidenChatViewModel { } catch { if await coordinator.handleCredentialRevocation(error, context: context) { return } guard coordinator.isLive(context) else { return } - foreignRun?.answerUnconfirmed(question.id) + foreignRunObserver.answerUnconfirmed(question.id) if let loser = AidenForeignRunResolution.loser(from: error) { showForeignRunNotice(loser.notice) return diff --git a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+Fork.swift b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+Fork.swift index 761117afad..9a84e5dabf 100644 --- a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+Fork.swift +++ b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel+Fork.swift @@ -37,8 +37,7 @@ extension AidenChatViewModel { isForking = true defer { isForking = false } let source = chat - let attempt = AidenChatForkAttempt.retaining( - forkAttempt, + let attempt = mutationSubMachines.forkAttempt.begin( context: context, request: .init( chatId: source.id, @@ -48,7 +47,6 @@ extension AidenChatViewModel { summaryFocus: action == .forkWithSummary ? summaryFocus : nil ) ) - forkAttempt = attempt do { let result = try await coordinator.remoteClient(for: context).forkChat( chatId: attempt.request.chatId, @@ -59,7 +57,7 @@ extension AidenChatViewModel { idempotencyKey: attempt.idempotencyKey ) // The Mac answered: the next fork is a new request. - if forkAttempt == attempt { forkAttempt = nil } + mutationSubMachines.forkAttempt.recordSuccess(attempt) guard !isRemoved, coordinator.isLive(context) else { return nil } let forked = result.chat guard !forked.isBotChat, @@ -87,11 +85,10 @@ extension AidenChatViewModel { return forked } catch let error where aidenIsCancellation(error) { // A cancelled request may already have reached the Mac; keep the key. + mutationSubMachines.forkAttempt.recordFailure(error, for: attempt) return nil } catch { - if forkAttempt == attempt, !AidenChatForkAttempt.outcomeIsUnknown(after: error) { - forkAttempt = nil - } + mutationSubMachines.forkAttempt.recordFailure(error, for: attempt) if await coordinator.handleCredentialRevocation(error, context: context) { return nil } guard !isRemoved, coordinator.isLive(context) else { return nil } if case AidenRemoteClientError.server(_, let body) = error, body.code.rawValue == "revision_conflict" { diff --git a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel.swift b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel.swift index e79a60900f..638c0a05dc 100644 --- a/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel.swift +++ b/ios/AidenOnTheGo/Features/Chat/AidenChatViewModel.swift @@ -89,11 +89,11 @@ final class AidenChatViewModel { guard let activeStreamID else { return } // This device's own run is accounted for, so the roster announcing // its turn later never re-reads the transcript for it. - foreignRunAccountedRunId = activeStreamID + foreignRunObserver.accountedRunId = activeStreamID // An owned stream supersedes observation of a foreign run. Its // replay rebuilds the reply, so a live run's copy is dropped. - if foreignRunTask != nil || foreignRun != nil { - let replacesLiveRun = foreignRunIsLive + if foreignRunObserver.isLookingForRun || foreignRunObserver.projection != nil { + let replacesLiveRun = foreignRunObserver.isLive stopForeignRunObservation() if replacesLiveRun { replaceLiveText("") @@ -104,38 +104,24 @@ final class AidenChatViewModel { } } } - @ObservationIgnored var foreignRun: AidenForeignRunProjection? - @ObservationIgnored var foreignRunIsLive = false - @ObservationIgnored var foreignRunTask: Task? - @ObservationIgnored var foreignRunLookupIsProbes = false - @ObservationIgnored var foreignRunSettleTask: Task? - @ObservationIgnored var foreignRunGeneration: UInt64 = 0 - /// Bounded transcript recovery after a foreign run ended but its re-read failed. - @ObservationIgnored var foreignRunReconcileTask: Task? - /// The last run this chat showed live or found already finished, so a - /// later attach can tell a new run from one the transcript already holds. - @ObservationIgnored var foreignRunAccountedRunId: String? - /// How many foreign runs went live; the probe resets its backoff on one. - @ObservationIgnored var foreignRunsShownLive = 0 + @ObservationIgnored let foreignRunObserver = AidenForeignRunObserver() + var foreignRun: AidenForeignRunProjection? { foreignRunObserver.projection } + var foreignRunIsLive: Bool { foreignRunObserver.isLive } + var foreignRunTask: Task? { foreignRunObserver.attachTask } /// The newest turn the agent roster has reported for this chat. @ObservationIgnored private var lastRosterTurnId: String? - /// A turn the roster announced while another lookup was in flight, or - /// while this phone restored its own stream. That lookup may have been - /// answered before the turn's run registered, so the turn is looked up - /// once it, or the restoration, ends. - @ObservationIgnored var turnAwaitingLookup: ForeignRunAttachReason? /// The turn this phone last streamed itself. The roster announcing it, /// even after its stream finished, is not another device's run. @ObservationIgnored private var lastLocalTurnId: String? - @ObservationIgnored var foreignRunProbeTask: Task? - @ObservationIgnored var foreignRunProbeGeneration: UInt64 = 0 /// Waits between foreground probes for a foreign run; tests shorten it. - @ObservationIgnored var foreignRunProbeSleep: @Sendable (Duration) async throws -> Void = { - try await Task.sleep(for: $0) + var foreignRunProbeSleep: @Sendable (Duration) async throws -> Void { + get { foreignRunObserver.probeSleep } + set { foreignRunObserver.probeSleep = newValue } } /// Waits before looking again for an announced run; tests shorten it. - @ObservationIgnored var announcedRunRetrySleep: @Sendable (Duration) async throws -> Void = { - try await Task.sleep(for: $0) + var announcedRunRetrySleep: @Sendable (Duration) async throws -> Void { + get { foreignRunObserver.announcedRunRetrySleep } + set { foreignRunObserver.announcedRunRetrySleep = newValue } } var isRestoringStream = false { didSet { @@ -147,112 +133,57 @@ final class AidenChatViewModel { @ObservationIgnored var transcriptGeneration: UInt64 = 0 @ObservationIgnored private var recoveryWarning: String? @ObservationIgnored private let networkPath: AidenNetworkPathSource? - @ObservationIgnored private var turnAttempts = AidenTurnAttemptTracker() - private(set) var pendingSend: AidenChatDraftStore.PendingSend? - private(set) var sendRecoveryError: String? + let pendingSendCoordinator: AidenPendingSendCoordinator + var pendingSend: AidenChatDraftStore.PendingSend? { pendingSendCoordinator.pendingSend } + var sendRecoveryError: String? { pendingSendCoordinator.sendRecoveryError } /// A send the Mac refused with a retryable 429 is sent again on its own /// after the server's delay, this many times in a row before Retry is /// left to the person. - static let maxRateLimitedSendRetries = 3 - @ObservationIgnored private var rateLimitedSendRetries = 0 - @ObservationIgnored private var rateLimitedSendRetryTask: Task? + static let maxRateLimitedSendRetries = AidenPendingSendCoordinator.maxRateLimitedSendRetries /// Waits out a retryable 429 before sending again; tests shorten it. - @ObservationIgnored var rateLimitedSendRetrySleep: @Sendable (Duration) async throws -> Void = { - try await Task.sleep(for: $0) + var rateLimitedSendRetrySleep: @Sendable (Duration) async throws -> Void { + get { pendingSendCoordinator.rateLimitedSendRetrySleep } + set { pendingSendCoordinator.rateLimitedSendRetrySleep = newValue } } /// The Mac was busy and the saved send will go out again on its own. - private(set) var isWaitingToRetryRateLimitedSend = false + var isWaitingToRetryRateLimitedSend: Bool { pendingSendCoordinator.isWaitingToRetryRateLimitedSend } /// The Mac kept refusing the saved send with a retryable 429 until the /// automatic resends ran out. Nothing was appended, so Retry is safe. - private(set) var isPendingSendRefusedBecauseBusy = false + var isPendingSendRefusedBecauseBusy: Bool { pendingSendCoordinator.isPendingSendRefusedBecauseBusy } var canRetrySend: Bool { - pendingSend?.canRetry() == true && isConnected && coordinator.isLive(owner) && !isStarting && !isSubmittingRunInput && !isRestoringStream && (pendingSend?.streamId != nil || (activeStreamID == nil && !isStreaming)) + pendingSendCoordinator.canRetry( + inputs: AidenPendingSendCoordinator.RetryEligibilityInputs( + isConnected: isConnected, + isOwnerLive: coordinator.isLive(owner), + isStarting: isStarting, + isSubmittingRunInput: isSubmittingRunInput, + isRestoringStream: isRestoringStream, + hasActiveStream: activeStreamID != nil, + isStreaming: isStreaming + ) + ) } var sendRecoveryMessage: String? { - if let sendRecoveryError { return sendRecoveryError } - guard let pendingSend, !isStarting, !isSubmittingRunInput else { return nil } - if isWaitingToRetryRateLimitedSend { - return "Aiden Agent is busy. Your message will be sent again in a moment." - } - if isPendingSendRefusedBecauseBusy, pendingSend.canRetry() { - return "Aiden Agent is still busy. Your message wasn’t sent; try again in a moment." - } - return pendingSend.canRetry() - ? "Couldn’t confirm delivery. Retry uses the same saved request within its safe retry window." - : "Couldn’t confirm delivery. The retry window has ended. Check the conversation on your computer before sending another message." + pendingSendCoordinator.recoveryMessage( + isStarting: isStarting, + isSubmittingRunInput: isSubmittingRunInput + ) } func discardPendingSend() async { guard !isStarting, !isSubmittingRunInput, let session = draftSession else { return } - cancelRateLimitedSendRetry() - rateLimitedSendRetries = 0 - do { - try await draftStore.savePendingSend(nil, session: session) - pendingSend = nil - sendRecoveryError = nil - turnAttempts.reset() - } catch { presentedError = error.localizedDescription } - } - - private func cancelRateLimitedSendRetry() { - rateLimitedSendRetryTask?.cancel() - rateLimitedSendRetryTask = nil - isWaitingToRetryRateLimitedSend = false - isPendingSendRefusedBecauseBusy = false - } - - /// The Mac refused `attempt` with a retryable 429 before running it, and - /// settled its Idempotency-Key as rejected, so that key cannot be sent - /// again. The same request is saved again under a fresh key - /// and sent once the server's delay has passed. Returns `false` when the - /// fresh attempt could not be saved, leaving the failure terminal. - private func scheduleRateLimitedSendRetry( - replacing attempt: AidenChatDraftStore.PendingSend, - error: AidenRemoteClientError, - session: AidenChatDraftStore.Session, - context: AidenRemoteRequestContext - ) async -> Bool { - await draftStore.settlePendingSend(key: attempt.key, session: session) - turnAttempts.reset() - let fresh = AidenChatDraftStore.PendingSend( - deviceId: attempt.deviceId, - request: attempt.request, - key: turnAttempts.key(for: attempt.request), - createdAt: Date(), - attachments: attempt.attachments - ) do { - try await draftStore.savePendingSend(fresh, session: session) + try await pendingSendCoordinator.discard(session: session) } catch { - turnAttempts.reset() - return false - } - pendingSend = fresh - // The resend belongs to the pairing that authorized this message; a - // re-pair while the record was being saved leaves Retry to the person. - guard coordinator.isLive(context), rateLimitedSendRetries < Self.maxRateLimitedSendRetries else { - isPendingSendRefusedBecauseBusy = true - return true - } - let delay: Duration = error.serverRetryAfterSeconds.map { .seconds($0) } - ?? .milliseconds(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: rateLimitedSendRetries)) - rateLimitedSendRetries += 1 - rateLimitedSendRetryTask?.cancel() - isWaitingToRetryRateLimitedSend = true - let sleep = rateLimitedSendRetrySleep - let key = fresh.key - rateLimitedSendRetryTask = Task { [weak self] in - do { try await sleep(delay) } catch { return } - guard let self, !Task.isCancelled, self.pendingSend?.key == key else { return } - self.rateLimitedSendRetryTask = nil - self.isWaitingToRetryRateLimitedSend = false - await self.send(retry: true, automatic: true, authority: context) + presentedError = error.localizedDescription } - return true } + @ObservationIgnored var mutationSubMachines = AidenChatMutationSubMachines() /// The fork request whose outcome is still unknown, replayed with the /// same Idempotency-Key so a lost response never yields a second fork. - @ObservationIgnored var forkAttempt: AidenChatForkAttempt? - @ObservationIgnored private var continueInNewChatAttempt: AidenContinueInNewChatAttempt? + var forkAttempt: AidenChatForkAttempt? { + get { mutationSubMachines.forkAttempt.retained } + set { mutationSubMachines.forkAttempt.retained = newValue } + } @ObservationIgnored private var draftSession: AidenChatDraftStore.Session? @ObservationIgnored private var draftPersistenceTask: Task? @ObservationIgnored private var suppressesDraftPersistence = false @@ -283,16 +214,9 @@ final class AidenChatViewModel { /// the Mac. Shown only while `offersNewWorktree`. var startsInNewWorktree = false /// The Mac is making the worktree; the message waits above a Cancel. - private(set) var isSettingUpWorktree = false + var isSettingUpWorktree: Bool { mutationSubMachines.worktreeSetup.isSettingUp } /// What a `git:read` branch list showed for this chat's workspace, if read. private(set) var workspaceHasCommits: Bool? - @ObservationIgnored private var worktreeSetupTask: Task? - /// Cancel was pressed during this setup. A task that already finished - /// ignores `cancel()`, so the press is kept here too. - @ObservationIgnored private var worktreeSetupCanceled = false - /// One key per chat and message, so a retry after a lost reply finds the - /// worktree the Mac already made instead of failing on the moved chat. - @ObservationIgnored private var worktreeAttempt: (text: String, key: UUID)? /// The busy send pill's mode. Resets to Queue when the run ends. private(set) var runInputMode: AidenStreamInputMode = .queue var streamState: AidenStreamState? { @@ -361,8 +285,6 @@ final class AidenChatViewModel { func renderID(forMessageID id: String) -> String { messageRenderIDs[id] ?? id } - private var approvalSnapshotGeneration: UInt64 = 0 - private var approvalSnapshotInFlight: (streamID: String, context: AidenRemoteRequestContext, approval: AidenPendingApproval?, state: AidenStreamState?)? private(set) var isRenaming = false var pendingApproval: AidenPendingApproval? { // A card back on screen (a refusal, or the next request) replaces the answered line. @@ -371,7 +293,6 @@ final class AidenChatViewModel { /// Revision 61: the tapped button, whose `answered` line shows at once in /// the card's place until the Mac confirms or the answer fails. private(set) var approvalAnsweredButton: AidenApprovalCardButton? - private var questionSnapshotGeneration: UInt64 = 0 var pendingQuestion: AidenPendingQuestion? var isRespondingToQuestion = false var isRespondingToApproval = false @@ -535,6 +456,7 @@ final class AidenChatViewModel { self.chat = chat self.allowsMutations = allowsMutations self.draftStore = draftStore + self.pendingSendCoordinator = AidenPendingSendCoordinator(draftStore: draftStore) self.visualDocumentCache = visualDocumentCache self.modelPreferenceStore = modelPreferenceStore self.hapticScope = hapticScope @@ -566,6 +488,7 @@ final class AidenChatViewModel { self.chat = chat allowsMutations = false draftStore = .shared + pendingSendCoordinator = AidenPendingSendCoordinator(draftStore: .shared) visualDocumentCache = .shared modelPreferenceStore = .shared hapticScope = UUID() @@ -589,12 +512,6 @@ final class AidenChatViewModel { attachmentPreparationTask?.cancel() runInputReceiptTask?.cancel() uploadTask?.cancel() - foreignRunTask?.cancel() - foreignRunSettleTask?.cancel() - foreignRunReconcileTask?.cancel() - foreignRunProbeTask?.cancel() - rateLimitedSendRetryTask?.cancel() - worktreeSetupTask?.cancel() skillCatalogTask?.cancel() mentionAgentsTask?.cancel() mentionFilesTask?.cancel() @@ -852,9 +769,7 @@ final class AidenChatViewModel { /// If the Mac finishes anyway, the chat is in the worktree next time it /// loads, still empty. func cancelWorktreeSetup() { - guard worktreeSetupTask != nil else { return } - worktreeSetupCanceled = true - worktreeSetupTask?.cancel() + mutationSubMachines.worktreeSetup.cancel() } var canSend: Bool { @@ -1060,9 +975,7 @@ final class AidenChatViewModel { let session = await draftStore.beginSession(instanceId: instanceId, chatId: chat.id) guard !isRemoved, coordinator.isLive(context) else { return } draftSession = session - isPendingSendRefusedBecauseBusy = false - do { pendingSend = try await draftStore.loadPendingSend(session: session, deviceId: context.deviceId) } - catch { sendRecoveryError = "The saved send could not be read. Check the conversation on your computer before dismissing it and sending again." } + await pendingSendCoordinator.load(session: session, deviceId: context.deviceId) if draft.isEmpty, pendingAttachments.isEmpty, !isPreparingAttachments, !isUploadingAttachment, !isStarting, let savedDraft = await draftStore.load(session: session) { guard !isRemoved, coordinator.isLive(context), draftSession == session else { return } @@ -1758,8 +1671,7 @@ final class AidenChatViewModel { private func send(retry: Bool, automatic: Bool, authority: AidenRemoteRequestContext?) async { if !automatic { // A person's own send or Retry replaces a scheduled resend. - cancelRateLimitedSendRetry() - rateLimitedSendRetries = 0 + pendingSendCoordinator.cancelAutomaticRetryForManualAction() } if retry, let mode = pendingSend?.inputMode { await submitRunInput(mode, retry: true); return } guard !isReadOnlyPresentation else { return } @@ -1845,8 +1757,11 @@ final class AidenChatViewModel { chat.messages.append(optimisticMessage) chat.updatedAt = now streamState = .queued - let attempt = retryAttempt ?? AidenChatDraftStore.PendingSend(deviceId: context.deviceId, request: request, - key: turnAttempts.key(for: request), createdAt: Date(), attachments: submittedAttachments) + let attempt = retryAttempt ?? pendingSendCoordinator.makeTurnAttempt( + deviceId: context.deviceId, + request: request, + attachments: submittedAttachments + ) let idempotencyKey = attempt.key /// Takes the message back out of the chat. A Cancel can come long after /// the send (New worktree waits on a fetch), so anything typed meanwhile @@ -1868,9 +1783,7 @@ final class AidenChatViewModel { func returnToRevokedChat(told: Bool = false) async -> Bool { guard !isRemoved, coordinator.isRetained(context), told || isOwnerRevoked else { return false } restoreFailedSend() - if let session = draftSession { await draftStore.settlePendingSend(key: attempt.key, session: session) } - pendingSend = nil - isPendingSendRefusedBecauseBusy = false + await pendingSendCoordinator.clearAfterRevocation(key: attempt.key, session: draftSession) presentedError = AidenDockCopy.machineRevoked coordinator.haptics.play(.error, scope: hapticScope) return true @@ -1879,47 +1792,31 @@ final class AidenChatViewModel { if makesWorktree { // Revision 53: the Mac makes the worktree and moves this empty // chat into it before the message is sent there. - let key = worktreeAttempt?.text == text ? worktreeAttempt!.key : UUID() - worktreeAttempt = (text, key) let client = try coordinator.remoteClient(for: context) let chatId = chat.id let revision = chat.revision - let setup = Task { - try await client.moveChatToNewWorktree(id: chatId, revision: revision, text: text, idempotencyKey: key) - } - worktreeSetupTask = setup - worktreeSetupCanceled = false - isSettingUpWorktree = true - defer { - isSettingUpWorktree = false - worktreeSetupTask = nil - } - let moved: AidenChatNewWorktree - do { - moved = try await withTaskCancellationHandler { - try await setup.value - } onCancel: { - setup.cancel() + let shouldContinue = try await mutationSubMachines.worktreeSetup.execute( + text: text, + operation: { key in + try await client.moveChatToNewWorktree(id: chatId, revision: revision, text: text, idempotencyKey: key) + }, + onMoved: { moved in + guard !self.isRemoved, self.coordinator.isLive(context) else { + _ = await returnToRevokedChat() + return false + } + self.chat.workspaceId = moved.chat.workspaceId + self.chat.revision = moved.chat.revision + self.startsInNewWorktree = false + // Only the selected machine's list can refresh. Another machine's + // catches up the next time it is selected. + if self.coordinator.defaultInstanceId == self.instanceId { + Task { [weak self] in await self?.coordinator.refreshWorkspaces() } + } + return true } - } catch { - if AidenNewWorktreeRetry.spendsKey(error) { worktreeAttempt = nil } - throw error - } - guard !isRemoved, coordinator.isLive(context) else { - _ = await returnToRevokedChat() - return - } - chat.workspaceId = moved.chat.workspaceId - chat.revision = moved.chat.revision - startsInNewWorktree = false - worktreeAttempt = nil - // Only the selected machine's list can refresh. Another machine's - // catches up the next time it is selected. - if coordinator.defaultInstanceId == instanceId { - Task { await coordinator.refreshWorkspaces() } - } - // Canceled as the worktree arrived: the chat stays there, unsent. - if setup.isCancelled || worktreeSetupCanceled { throw CancellationError() } + ) + guard shouldContinue else { return } } let session: AidenChatDraftStore.Session if let existing = draftSession { session = existing } @@ -1927,13 +1824,12 @@ final class AidenChatViewModel { session = await draftStore.beginSession(instanceId: instanceId, chatId: chat.id) draftSession = session } - try await draftStore.savePendingSend(attempt, session: session) + try await pendingSendCoordinator.persistBeforeSend(attempt, session: session) guard !isRemoved, coordinator.isLive(context) else { _ = await returnToRevokedChat() return } - pendingSend = attempt - isPendingSendRefusedBecauseBusy = false + pendingSendCoordinator.adoptPersistedAttempt(attempt) guard attempt.canRetry(), coordinator.isLive(context) else { throw AidenRemoteClientError.invalidResponse } let response = try await coordinator.remoteClient(for: context).startTurn( chatId: chat.id, @@ -2025,10 +1921,7 @@ final class AidenChatViewModel { return } guard !isRemoved, coordinator.isLive(context) else { return } - pendingSend = nil - isPendingSendRefusedBecauseBusy = false - turnAttempts.reset() - rateLimitedSendRetries = 0 + pendingSendCoordinator.markAccepted(resetTurnAttempts: true) continueInNewChatRefusal = nil if chat.messages.contains(where: { $0.id == optimisticID }) { messageRenderIDs[response.message.id] = optimisticID @@ -2061,18 +1954,22 @@ final class AidenChatViewModel { restoreFailedSend() if let rateLimit = error as? AidenRemoteClientError, rateLimit.isRetryableRateLimit, let session = draftSession, - await scheduleRateLimitedSendRetry(replacing: attempt, error: rateLimit, session: session, context: context) { + await pendingSendCoordinator.scheduleRateLimitedSendRetry( + replacing: attempt, + error: rateLimit, + session: session, + isContextLive: { self.coordinator.isLive(context) }, + onRetry: { [weak self] in + await self?.send(retry: true, automatic: true, authority: context) + } + ) { // The Mac was only busy: keep the send and try it again. return } if case AidenRemoteClientError.server(let status, let body) = error, AidenDraftSendReconciliation.refusalSettlesSend(status: status, code: body.code), let session = draftSession { - await draftStore.settlePendingSend(key: attempt.key, session: session) - pendingSend = nil - isPendingSendRefusedBecauseBusy = false - turnAttempts.reset() - rateLimitedSendRetries = 0 + await pendingSendCoordinator.settleDefinitiveRefusal(key: attempt.key, session: session) } continueInNewChatRefusal = AidenContinueInNewChatRefusal(error: error) if pendingSend == nil { presentedError = error.localizedDescription } @@ -2579,9 +2476,8 @@ final class AidenChatViewModel { else { session = await draftStore.beginSession(instanceId: instanceId, chatId: chat.id); draftSession = session } let pending = saved ?? AidenChatDraftStore.PendingSend(deviceId: context.deviceId, request: AidenTurnStart(text: text), key: key, createdAt: Date(), attachments: [], streamId: streamID, inputMode: mode) - try await draftStore.savePendingSend(pending, session: session) - pendingSend = pending - isPendingSendRefusedBecauseBusy = false + try await pendingSendCoordinator.persistBeforeSend(pending, session: session) + pendingSendCoordinator.adoptPersistedAttempt(pending) guard pending.canRetry(), coordinator.isLive(context) else { throw AidenRemoteClientError.invalidResponse } let result = try await coordinator.remoteClient(for: context).submitStreamInput( id: streamID, @@ -2608,8 +2504,7 @@ final class AidenChatViewModel { } } guard retained, !isRemoved, coordinator.isLive(context) else { return } - pendingSend = nil - isPendingSendRefusedBecauseBusy = false + pendingSendCoordinator.markAccepted(resetTurnAttempts: false) if lastRunInputAttempt == attempt { lastRunInputAttempt = nil } if AidenRunInputPresentation.consumesDraft(result) { if retry { consumeRunInputDraft(text) } else { persistDraftNow() } @@ -2638,9 +2533,7 @@ final class AidenChatViewModel { } else { restoreDraft() } - if let session = draftSession { await draftStore.settlePendingSend(key: key, session: session) } - pendingSend = nil - isPendingSendRefusedBecauseBusy = false + await pendingSendCoordinator.clearAfterRevocation(key: key, session: draftSession) if lastRunInputAttempt == attempt { lastRunInputAttempt = nil } presentedError = AidenDockCopy.machineRevoked coordinator.haptics.play(.error, scope: hapticScope) @@ -3510,22 +3403,30 @@ final class AidenChatViewModel { ) async { guard !isRemoved, coordinator.isLive(context), activeStreamID == streamID, streamState?.isTerminal != true else { return } - if isFallback, let read = approvalSnapshotInFlight, - read.streamID == streamID, coordinator.isLive(read.context), - read.approval == pendingApproval, read.state == streamState { return } - approvalSnapshotGeneration &+= 1 - let snapshotGeneration = approvalSnapshotGeneration - approvalSnapshotInFlight = (streamID, context, pendingApproval, streamState) + let isInFlightContextLive = mutationSubMachines.approvalSnapshots.inFlight.map { + coordinator.isLive($0.context) + } ?? false + guard let token = mutationSubMachines.approvalSnapshots.begin( + streamID: streamID, + context: context, + pendingApproval: pendingApproval, + streamState: streamState, + isFallback: isFallback, + isInFlightContextLive: isInFlightContextLive + ) else { return } defer { - if snapshotGeneration == approvalSnapshotGeneration { approvalSnapshotInFlight = nil } + mutationSubMachines.approvalSnapshots.finish(token) } - let expectedApproval = pendingApproval - let expectedState = streamState do { let snapshot = try await coordinator.remoteClient(for: context).streamApproval(id: streamID) - guard !isRemoved, coordinator.isLive(context), activeStreamID == streamID, - snapshotGeneration == approvalSnapshotGeneration, - pendingApproval == expectedApproval, streamState == expectedState else { return } + guard mutationSubMachines.approvalSnapshots.accepts( + token, + activeStreamID: activeStreamID, + pendingApproval: pendingApproval, + streamState: streamState, + isRemoved: isRemoved, + isContextLive: coordinator.isLive(context) + ) else { return } guard let approval = AidenPendingApprovalResolution.resolve( snapshot.approval, streamId: streamID, @@ -3562,9 +3463,14 @@ final class AidenChatViewModel { ) } catch { if await coordinator.handleCredentialRevocation(error, context: context) { return } - guard !isRemoved, coordinator.isLive(context), activeStreamID == streamID, - snapshotGeneration == approvalSnapshotGeneration, - pendingApproval == expectedApproval, streamState == expectedState else { return } + guard mutationSubMachines.approvalSnapshots.accepts( + token, + activeStreamID: activeStreamID, + pendingApproval: pendingApproval, + streamState: streamState, + isRemoved: isRemoved, + isContextLive: coordinator.isLive(context) + ) else { return } pendingApproval = nil await restorePendingQuestion( streamID: streamID, @@ -3595,15 +3501,20 @@ final class AidenChatViewModel { } return } - questionSnapshotGeneration &+= 1 - let snapshotGeneration = questionSnapshotGeneration - let expectedQuestion = pendingQuestion - let expectedState = streamState + let token = mutationSubMachines.questionSnapshots.begin( + streamID: streamID, + pendingQuestion: pendingQuestion, + streamState: streamState + ) do { let snapshot = try await coordinator.remoteClient(for: context).streamQuestion(id: streamID) - guard coordinator.isLive(context), activeStreamID == streamID, - snapshotGeneration == questionSnapshotGeneration, - pendingQuestion == expectedQuestion, streamState == expectedState else { return } + guard mutationSubMachines.questionSnapshots.accepts( + token, + activeStreamID: activeStreamID, + pendingQuestion: pendingQuestion, + streamState: streamState, + isContextLive: coordinator.isLive(context) + ) else { return } guard let question = AidenPendingQuestionResolution.resolve( snapshot.question, streamId: streamID, @@ -3638,9 +3549,13 @@ final class AidenChatViewModel { } } catch { if await coordinator.handleCredentialRevocation(error, context: context) { return } - guard coordinator.isLive(context), activeStreamID == streamID, - snapshotGeneration == questionSnapshotGeneration, - pendingQuestion == expectedQuestion, streamState == expectedState else { return } + guard mutationSubMachines.questionSnapshots.accepts( + token, + activeStreamID: activeStreamID, + pendingQuestion: pendingQuestion, + streamState: streamState, + isContextLive: coordinator.isLive(context) + ) else { return } pendingQuestion = nil if reconcilesOnNil && pendingApproval == nil { streamState = .reconciling @@ -4197,20 +4112,12 @@ extension AidenChatViewModel { defer { isContinuingInNewChat = false } continueInNewChatError = nil let source = chat - let attempt: AidenContinueInNewChatAttempt - if let existing = continueInNewChatAttempt, existing.context == context, existing.chatId == source.id, - existing.revision == source.revision, existing.workspaceId == workspaceId { - attempt = existing - } else { - attempt = AidenContinueInNewChatAttempt( - context: context, - chatId: source.id, - revision: source.revision, - workspaceId: workspaceId, - idempotencyKey: UUID() - ) - } - continueInNewChatAttempt = attempt + let attempt = mutationSubMachines.continueInNewChatAttempt.begin( + context: context, + chatId: source.id, + revision: source.revision, + workspaceId: workspaceId + ) do { let result = try await coordinator.remoteClient(for: context).continueChatInNewChat( chatId: attempt.chatId, @@ -4218,7 +4125,7 @@ extension AidenChatViewModel { workspaceId: attempt.workspaceId, idempotencyKey: attempt.idempotencyKey ) - if continueInNewChatAttempt == attempt { continueInNewChatAttempt = nil } + mutationSubMachines.continueInNewChatAttempt.recordSuccess(attempt) guard !isRemoved, coordinator.isLive(context) else { return nil } let continued = result.chat guard !continued.isBotChat else { @@ -4240,11 +4147,10 @@ extension AidenChatViewModel { return continued } catch let error where aidenIsCancellation(error) { // A cancelled request may already have reached the computer; keep the key. + mutationSubMachines.continueInNewChatAttempt.recordFailure(error, for: attempt) return nil } catch { - if continueInNewChatAttempt == attempt, !AidenChatForkAttempt.outcomeIsUnknown(after: error) { - continueInNewChatAttempt = nil - } + mutationSubMachines.continueInNewChatAttempt.recordFailure(error, for: attempt) if await coordinator.handleCredentialRevocation(error, context: context) { return nil } guard !isRemoved, coordinator.isLive(context) else { return nil } if case AidenRemoteClientError.server(_, let body) = error, body.code.rawValue == "revision_conflict" { diff --git a/ios/AidenOnTheGo/Features/Chat/AidenForeignRunObserver.swift b/ios/AidenOnTheGo/Features/Chat/AidenForeignRunObserver.swift new file mode 100644 index 0000000000..1b1f149a7d --- /dev/null +++ b/ios/AidenOnTheGo/Features/Chat/AidenForeignRunObserver.swift @@ -0,0 +1,572 @@ +import Foundation + +/// Owns foreign-run discovery, foreground probing, attach/reconnect looping, +/// settle debouncing, and bounded transcript recovery for a chat. +/// +/// Extracted from `AidenChatViewModel+ForeignRuns.swift` so the 6-condition +/// currency fence, generation counters, probe backoff, and attach loop can be +/// reasoned about and unit-tested independently of the full chat screen model. +@MainActor +final class AidenForeignRunObserver { + /// Frames retained from an already finished run arrive back to back. + /// Publishing waits for this quiet period so opening a chat never replays + /// a finished run as if it were live. + static let settleInterval: Duration = .milliseconds(400) + static let maxReconnects = 3 + static let maxReconcileAttempts = 6 + /// A run the roster announced may not be registered on the Mac yet when + /// the phone first asks for it; one retry after this long covers that. + static let announcedRunRetryDelay: Duration = .milliseconds(400) + + /// Why the phone is looking for a run it did not start. + enum AttachReason: Equatable, Sendable { + /// The chat opened or reloaded; its transcript was just read. + case load + /// The agent roster reported a new turn. + case announcedTurn + /// The first roster this chat received named a turn. It is usually the + /// last finished one, so a missing run is not looked for again. + case firstRosterTurn + /// A foreground check on a device that cannot read the agent roster. + case probe + } + + /// The five external inputs combined with `generation` to form the + /// 6-condition `isCurrentForeignRun` invariant. + struct CurrencyInputs: Equatable, Sendable { + let isTaskCancelled: Bool + let isRemoved: Bool + let isContextLive: Bool + let hasActiveStream: Bool + let isStarting: Bool + } + + enum ProbeStep: Equatable, Sendable { + case stop + case deferWhileBusy + case attach(AidenRemoteRequestContext) + } + + enum Phase: Equatable, Sendable { + case idle + case attaching(generation: UInt64, isProbeLookup: Bool) + case settling(generation: UInt64, runId: String, isProbeLookup: Bool) + case live(generation: UInt64, runId: String) + } + + /// Host callbacks connecting the observer to the chat model (or a test harness). + struct Host { + var currencyInputs: @MainActor (AidenRemoteRequestContext) -> CurrencyInputs + var isRemoved: @MainActor () -> Bool + var hasActiveStream: @MainActor () -> Bool + var openEventStream: @MainActor (AidenRemoteRequestContext, AidenForeignRunProjection?) throws -> AsyncThrowingStream + var handleCredentialRevocation: @MainActor (Error, AidenRemoteRequestContext) async -> Bool + var reconcileChat: @MainActor (AidenRemoteRequestContext) async -> Bool + var bumpTranscriptGeneration: @MainActor () -> Void + var onGoLive: @MainActor (AidenForeignRunProjection, AidenRemoteRequestContext) async -> Void + var onPublishUpdate: @MainActor (AidenForeignRunProjection, Bool, AidenRemoteRequestContext) -> Void + var onPerformEffect: @MainActor (AidenForeignRunProjection.Effect, String, AidenRemoteRequestContext) async -> Bool + var onReconnectExhaustedLive: @MainActor (String, AidenRemoteRequestContext) async -> Void + var onFlushBeforeQuietEnd: @MainActor () -> Void + var onEndedQuietlyLive: @MainActor (AidenRemoteRunEndState?, Bool) -> Void + var onClearLiveOutput: @MainActor () -> Void + var onClearLiveOutputAndPrompts: @MainActor () -> Void + var onObservationFinished: @MainActor () -> Void + } + + /// Delay before the foreground probe's next check, after `idleProbes` + /// consecutive checks that found nothing live: 5s, 10s, 20s, then 30s. + static func probeDelay(afterIdleProbes idleProbes: Int) -> Duration { + .seconds(min(30, 5 << min(max(idleProbes, 0), 3))) + } + + private(set) var projection: AidenForeignRunProjection? + private(set) var isLive = false + private(set) var attachTask: Task? + private(set) var lookupIsProbes = false + private(set) var settleTask: Task? + private(set) var generation: UInt64 = 0 + /// Bounded transcript recovery after a foreign run ended but its re-read failed. + private(set) var reconcileTask: Task? + /// The last run this chat showed live or found already finished, so a + /// later attach can tell a new run from one the transcript already holds. + var accountedRunId: String? + /// How many foreign runs went live; the probe resets its backoff on one. + private(set) var shownLiveCount = 0 + /// A turn the roster announced while another lookup was in flight, or + /// while this phone restored its own stream. + private(set) var turnAwaitingLookup: AttachReason? + private(set) var probeTask: Task? + private(set) var probeGeneration: UInt64 = 0 + + /// Waits between foreground probes for a foreign run; tests shorten it. + var probeSleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + /// Waits before looking again for an announced run; tests shorten it. + var announcedRunRetrySleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + /// Waits before reconnecting an interrupted attach; tests shorten it. + var reconnectSleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + /// Quiet period before promoting a replay to live; tests shorten it. + var settleSleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + /// Waits between bounded recovery transcript re-reads; tests shorten it. + var reconcileSleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + + deinit { + attachTask?.cancel() + settleTask?.cancel() + reconcileTask?.cancel() + probeTask?.cancel() + } + + var isObservingLive: Bool { projection != nil && isLive } + var isLookingForRun: Bool { attachTask != nil } + var isProbing: Bool { probeTask != nil } + + var phase: Phase { + if let projection, isLive { + return .live(generation: generation, runId: projection.runId) + } + if let projection { + return .settling(generation: generation, runId: projection.runId, isProbeLookup: lookupIsProbes) + } + if attachTask != nil { + return .attaching(generation: generation, isProbeLookup: lookupIsProbes) + } + return .idle + } + + /// The 6-condition currency fence: task active, chat not removed, generation + /// matches, owner context live, no owned active stream, and not starting a send. + func isCurrent(generation: UInt64, inputs: CurrencyInputs) -> Bool { + !inputs.isTaskCancelled + && !inputs.isRemoved + && generation == self.generation + && inputs.isContextLive + && !inputs.hasActiveStream + && !inputs.isStarting + } + + /// A send, this phone's own stream, a newly live foreign run or a removed + /// pairing owns the live state from then on. + func isRecoveryFenced(inputs: CurrencyInputs) -> Bool { + inputs.isTaskCancelled + || inputs.isRemoved + || !inputs.isContextLive + || inputs.hasActiveStream + || inputs.isStarting + || isLive + } + + /// Queues an announced turn while an attach or stream restoration is in flight. + /// A newer `.announcedTurn` keeps precedence over `.firstRosterTurn`. + func queueAnnouncedTurn(reason: AttachReason) { + if turnAwaitingLookup != .announcedTurn { + turnAwaitingLookup = reason + } + } + + /// Consumes a queued announced turn when no lookup is in flight. + func consumeQueuedAnnouncedTurn() -> AttachReason? { + guard let reason = turnAwaitingLookup, attachTask == nil, !Task.isCancelled else { return nil } + turnAwaitingLookup = nil + return reason + } + + func markAnsweredLocally(_ promptId: String) { + projection?.markAnsweredLocally(promptId) + } + + func answerUnconfirmed(_ promptId: String) { + projection?.answerUnconfirmed(promptId) + } + + /// Starts one observation task if none is in flight. Returns the task so a + /// probe loop or test can await it. + @discardableResult + func startObservation( + context: AidenRemoteRequestContext, + reason: AttachReason, + host: Host + ) -> Task? { + guard attachTask == nil else { return nil } + generation &+= 1 + let activeGeneration = generation + lookupIsProbes = reason == .probe + let task = Task { [weak self] in + guard let self else { return } + await self.observe( + context: context, + generation: activeGeneration, + reason: reason, + host: host + ) + host.onObservationFinished() + } + attachTask = task + return task + } + + /// Starts the foreground check for runs started elsewhere on a device that + /// cannot read the agent roster. + func startProbeIfNeeded( + canStart: Bool, + nextStep: @escaping @MainActor () -> ProbeStep, + startAttach: @escaping @MainActor (AidenRemoteRequestContext, AttachReason) -> Task? + ) { + guard canStart, probeTask == nil else { return } + probeGeneration &+= 1 + let activeGeneration = probeGeneration + probeTask = Task { [weak self] in + guard let self else { return } + await self.probeForForeignRuns( + generation: activeGeneration, + nextStep: nextStep, + startAttach: startAttach + ) + guard activeGeneration == self.probeGeneration else { return } + self.probeTask = nil + } + } + + /// Stops foreground probing and cancels a still-unsettled probe lookup. + /// Returns true if live output should be cleared. + func stopProbe(hasActiveStream: Bool, onClearLiveOutputAndPrompts: () -> Void) { + probeGeneration &+= 1 + probeTask?.cancel() + probeTask = nil + // Its lookup goes too, or it asks the machine again after the chat has + // left. A run it found stays on, as any live run does. + guard lookupIsProbes, attachTask != nil, projection == nil else { return } + attachTask?.cancel() + endObservation( + preservingRecovery: true, + hasActiveStream: hasActiveStream, + onClearLiveOutputAndPrompts: onClearLiveOutputAndPrompts + ) + } + + /// Stops observing, and drops a turn announced during the stopped lookup. + func stopObservation(hasActiveStream: Bool, onClearLiveOutputAndPrompts: () -> Void) { + turnAwaitingLookup = nil + attachTask?.cancel() + endObservation( + preservingRecovery: false, + hasActiveStream: hasActiveStream, + onClearLiveOutputAndPrompts: onClearLiveOutputAndPrompts + ) + } + + /// Ends observation from within the lookup itself, so a turn announced + /// while it ran is still looked up once it returns. `preservingRecovery` + /// keeps a finished run's response, still awaiting its transcript, on + /// screen while a later attach finds nothing live. + func endObservation( + preservingRecovery: Bool, + hasActiveStream: Bool, + onClearLiveOutputAndPrompts: () -> Void + ) { + generation &+= 1 + attachTask = nil + settleTask?.cancel() + settleTask = nil + // An ended run still awaiting its transcript is presented too. + var wasLive = isLive + if !preservingRecovery, let recovery = reconcileTask { + recovery.cancel() + reconcileTask = nil + wasLive = true + } + projection = nil + isLive = false + if wasLive, !hasActiveStream { + onClearLiveOutputAndPrompts() + } + } + + // MARK: - Probe loop + + private func probeForForeignRuns( + generation activeGeneration: UInt64, + nextStep: @MainActor () -> ProbeStep, + startAttach: @MainActor (AidenRemoteRequestContext, AttachReason) -> Task? + ) async { + var idleProbes = 0 + while activeGeneration == probeGeneration, !Task.isCancelled { + do { + try await probeSleep(Self.probeDelay(afterIdleProbes: idleProbes)) + } catch { + return + } + guard activeGeneration == probeGeneration, !Task.isCancelled else { return } + switch nextStep() { + case .stop: + return + case .deferWhileBusy: + // A reply is already live here; check again soon after it ends. + idleProbes = 0 + continue + case let .attach(context): + if attachTask != nil { + idleProbes = 0 + continue + } + let shownLive = shownLiveCount + guard let attach = startAttach(context, .probe) else { return } + await attach.value + idleProbes = shownLiveCount == shownLive ? idleProbes + 1 : 0 + } + } + } + + // MARK: - Attach loop + + private enum ForeignRunStep { + case keepObserving + case stop + /// A finished run replayed on attach: nothing to show live. + case endedBeforeAttach(runId: String) + } + + private func isCurrent( + generation activeGeneration: UInt64, + context: AidenRemoteRequestContext, + host: Host + ) -> Bool { + isCurrent(generation: activeGeneration, inputs: host.currencyInputs(context)) + } + + private func observe( + context: AidenRemoteRequestContext, + generation activeGeneration: UInt64, + reason: AttachReason, + host: Host + ) async { + defer { + if activeGeneration == generation { attachTask = nil } + } + var reconnects = 0 + var retriedAnnouncedRun = false + let announcedRetrySleep = announcedRunRetrySleep + func retryAnnouncedRun() async -> Bool { + guard reason == .announcedTurn, !retriedAnnouncedRun else { return false } + retriedAnnouncedRun = true + try? await announcedRetrySleep(Self.announcedRunRetryDelay) + return true + } + attach: while isCurrent(generation: activeGeneration, context: context, host: host) { + let events: AsyncThrowingStream + do { + events = try host.openEventStream(context, projection) + } catch { + return + } + do { + for try await event in events { + guard isCurrent(generation: activeGeneration, context: context, host: host) else { return } + reconnects = 0 + switch await applyEvent(event, context: context, generation: activeGeneration, host: host) { + case .keepObserving: + continue + case .stop: + return + case let .endedBeforeAttach(runId): + let isNewRun = runId != accountedRunId + if !isNewRun { + // The newest retained run is one already accounted + // for: an announced run may not be registered yet. + discardUnsettledProjection() + if await retryAnnouncedRun() { continue attach } + } + // The load may have read the transcript before the Mac + // committed the reply. Terminal replay settles that read + // even though historical activity stays off screen. + guard isCurrent(generation: activeGeneration, context: context, host: host) else { return } + accountedRunId = runId + await endQuietly(context: context, reconcile: isNewRun, host: host) + return + } + } + } catch let error where aidenIsCancellation(error) { + return + } catch { + if await host.handleCredentialRevocation(error, context) { + stopObservation( + hasActiveStream: host.hasActiveStream(), + onClearLiveOutputAndPrompts: host.onClearLiveOutputAndPrompts + ) + return + } + guard isCurrent(generation: activeGeneration, context: context, host: host) else { return } + if case let .server(statusCode, _)? = error as? AidenRemoteClientError, + statusCode < 500 { + // No retained run (run_gone), or this device may not see it. + let neverFound = projection == nil + if statusCode == 404, neverFound, await retryAnnouncedRun() { continue attach } + if statusCode == 404, neverFound, reason == .announcedTurn { + // The announced run cannot be observed; its outcome + // still reaches the transcript. + _ = await host.reconcileChat(context) + guard activeGeneration == generation else { return } + } + await endQuietly(context: context, reconcile: isLive, host: host) + return + } + } + reconnects += 1 + guard reconnects <= Self.maxReconnects, + isCurrent(generation: activeGeneration, context: context, host: host) else { break } + try? await reconnectSleep(.seconds(reconnects)) + } + guard activeGeneration == generation, !host.isRemoved() else { return } + if isLive, let runId = projection?.runId { + await host.onReconnectExhaustedLive(runId, context) + await endQuietly(context: context, reconcile: true, host: host) + } else { + endObservation( + preservingRecovery: true, + hasActiveStream: host.hasActiveStream(), + onClearLiveOutputAndPrompts: host.onClearLiveOutputAndPrompts + ) + } + } + + private func applyEvent( + _ event: AidenRemoteRunEvent, + context: AidenRemoteRequestContext, + generation activeGeneration: UInt64, + host: Host + ) async -> ForeignRunStep { + if projection == nil { + projection = AidenForeignRunProjection(runId: event.runId) + scheduleSettle(context: context, generation: activeGeneration, host: host) + } + guard var current = projection else { return .stop } + let effects = current.apply(event) + projection = current + guard isLive else { + return current.isEnded ? .endedBeforeAttach(runId: current.runId) : .keepObserving + } + var flushesText = true + if case let .content(content) = event.kind { + flushesText = content.type != .textDelta && content.type != .heartbeat + } + host.onPublishUpdate(current, flushesText, context) + for effect in effects { + guard isCurrent(generation: activeGeneration, context: context, host: host) else { return .stop } + if await host.onPerformEffect(effect, current.runId, context) { + await endQuietly(context: context, reconcile: true, host: host) + return .stop + } + } + return .keepObserving + } + + private func discardUnsettledProjection() { + guard !isLive else { return } + settleTask?.cancel() + settleTask = nil + projection = nil + } + + private func scheduleSettle( + context: AidenRemoteRequestContext, + generation activeGeneration: UInt64, + host: Host + ) { + settleTask?.cancel() + let sleep = settleSleep + settleTask = Task { [weak self] in + try? await sleep(Self.settleInterval) + guard !Task.isCancelled, let self, + self.isCurrent(generation: activeGeneration, context: context, host: host), + let current = self.projection, !current.isEnded else { return } + await self.goLive(current, context: context, host: host) + } + } + + private func goLive( + _ current: AidenForeignRunProjection, + context: AidenRemoteRequestContext, + host: Host + ) async { + // A newly live run owns the live output from here on. + reconcileTask?.cancel() + reconcileTask = nil + isLive = true + accountedRunId = current.runId + shownLiveCount += 1 + await host.onGoLive(current, context) + } + + private func endQuietly( + context: AidenRemoteRequestContext, + reconcile: Bool, + host: Host + ) async { + if isLive, !host.hasActiveStream() { + host.onFlushBeforeQuietEnd() + } + let activeGeneration = generation + var reconciled = true + if reconcile { + reconciled = await host.reconcileChat(context) + } + guard isCurrent(generation: activeGeneration, context: context, host: host) else { return } + generation &+= 1 + settleTask?.cancel() + settleTask = nil + attachTask = nil + let wasLive = isLive + let finalState = projection?.endState + projection = nil + isLive = false + guard !host.hasActiveStream() else { return } + if !wasLive { + if !reconciled { + scheduleReconciliation(context: context, host: host) + } + return + } + host.onEndedQuietlyLive(finalState, reconciled) + if !reconciled { + scheduleReconciliation(context: context, host: host) + } + } + + private func scheduleReconciliation( + context: AidenRemoteRequestContext, + host: Host + ) { + guard reconcileTask == nil else { return } + let sleep = reconcileSleep + reconcileTask = Task { [weak self] in + for attempt in 0..? + + /// Waits out a retryable 429 before sending again; tests shorten it. + @ObservationIgnored var rateLimitedSendRetrySleep: @Sendable (Duration) async throws -> Void = { + try await Task.sleep(for: $0) + } + + init(draftStore: AidenChatDraftStore) { + self.draftStore = draftStore + } + + deinit { + rateLimitedSendRetryTask?.cancel() + } + + /// The Mac was busy and the saved send will go out again on its own. + var isWaitingToRetryRateLimitedSend: Bool { + rateLimitRetryState == .waitingAutomatic + } + + /// The Mac kept refusing the saved send with a retryable 429 until the + /// automatic resends ran out. Nothing was appended, so Retry is safe. + var isPendingSendRefusedBecauseBusy: Bool { + rateLimitRetryState == .refusedBecauseBusy + } + + /// The 9-term retry eligibility predicate: + /// 1. `pendingSend != nil` + /// 2. `pendingSend.canRetry(at: now)` + /// 3. `isConnected` + /// 4. `isOwnerLive` + /// 5. `!isStarting` + /// 6. `!isSubmittingRunInput` + /// 7. `!isRestoringStream` + /// 8. `pendingSend.streamId != nil || !hasActiveStream` + /// 9. `pendingSend.streamId != nil || !isStreaming` + func canRetry(inputs: RetryEligibilityInputs, now: Date = Date()) -> Bool { + guard let pendingSend, pendingSend.canRetry(at: now) else { return false } + return inputs.isConnected + && inputs.isOwnerLive + && !inputs.isStarting + && !inputs.isSubmittingRunInput + && !inputs.isRestoringStream + && (pendingSend.streamId != nil || (!inputs.hasActiveStream && !inputs.isStreaming)) + } + + func recoveryMessage( + isStarting: Bool, + isSubmittingRunInput: Bool, + now: Date = Date() + ) -> String? { + if let sendRecoveryError { return sendRecoveryError } + guard let pendingSend, !isStarting, !isSubmittingRunInput else { return nil } + if isWaitingToRetryRateLimitedSend { + return "Aiden Agent is busy. Your message will be sent again in a moment." + } + if isPendingSendRefusedBecauseBusy, pendingSend.canRetry(at: now) { + return "Aiden Agent is still busy. Your message wasn’t sent; try again in a moment." + } + return pendingSend.canRetry(at: now) + ? "Couldn’t confirm delivery. Retry uses the same saved request within its safe retry window." + : "Couldn’t confirm delivery. The retry window has ended. Check the conversation on your computer before sending another message." + } + + /// Restores any persisted pending send for `session` and `deviceId`. + func load(session: AidenChatDraftStore.Session, deviceId: String) async { + if rateLimitRetryState == .refusedBecauseBusy { + rateLimitRetryState = .none + } + do { + pendingSend = try await draftStore.loadPendingSend(session: session, deviceId: deviceId) + } catch { + sendRecoveryError = "The saved send could not be read. Check the conversation on your computer before dismissing it and sending again." + } + } + + /// Mints or reuses a stable `Idempotency-Key` for a fresh turn send. + func makeTurnAttempt( + deviceId: String, + request: AidenTurnStart, + attachments: [AidenAttachmentReference], + now: Date = Date() + ) -> AidenChatDraftStore.PendingSend { + AidenChatDraftStore.PendingSend( + deviceId: deviceId, + request: request, + key: turnAttempts.key(for: request), + createdAt: now, + attachments: attachments + ) + } + + /// Persists `attempt` before transmission. Does not adopt `attempt` into + /// `pendingSend` until the caller verifies the owner is still live. + func persistBeforeSend( + _ attempt: AidenChatDraftStore.PendingSend, + session: AidenChatDraftStore.Session + ) async throws { + try await draftStore.savePendingSend(attempt, session: session) + } + + /// Adopts a persisted attempt as the active pending send and clears any + /// prior busy-exhausted banner. + func adoptPersistedAttempt(_ attempt: AidenChatDraftStore.PendingSend) { + pendingSend = attempt + if rateLimitRetryState == .refusedBecauseBusy { + rateLimitRetryState = .none + } + } + + /// Called when a person manually starts a send or Retry, superseding any + /// scheduled automatic resend. + func cancelAutomaticRetryForManualAction() { + cancelRateLimitedSendRetry() + rateLimitedSendRetries = 0 + } + + func cancelRateLimitedSendRetry() { + rateLimitedSendRetryTask?.cancel() + rateLimitedSendRetryTask = nil + rateLimitRetryState = .none + } + + /// Clears pending state once the Mac accepted the turn or run input. + func markAccepted(resetTurnAttempts: Bool = true) { + pendingSend = nil + if rateLimitRetryState == .refusedBecauseBusy { + rateLimitRetryState = .none + } + if resetTurnAttempts { + turnAttempts.reset() + rateLimitedSendRetries = 0 + } + } + + /// Settles and clears a pending send after a definitive server refusal. + func settleDefinitiveRefusal( + key: UUID, + session: AidenChatDraftStore.Session + ) async { + await draftStore.settlePendingSend(key: key, session: session) + pendingSend = nil + if rateLimitRetryState == .refusedBecauseBusy { + rateLimitRetryState = .none + } + turnAttempts.reset() + rateLimitedSendRetries = 0 + } + + /// Settles and clears a pending send after the machine's credential was revoked. + func clearAfterRevocation( + key: UUID, + session: AidenChatDraftStore.Session? + ) async { + if let session { + await draftStore.settlePendingSend(key: key, session: session) + } + pendingSend = nil + if rateLimitRetryState == .refusedBecauseBusy { + rateLimitRetryState = .none + } + } + + /// Discards the saved pending send from disk and clears recovery state. + func discard(session: AidenChatDraftStore.Session) async throws { + cancelRateLimitedSendRetry() + rateLimitedSendRetries = 0 + try await draftStore.savePendingSend(nil, session: session) + pendingSend = nil + sendRecoveryError = nil + turnAttempts.reset() + } + + /// The Mac refused `attempt` with a retryable 429 before running it, and + /// settled its Idempotency-Key as rejected, so that key cannot be sent + /// again. The same request is saved again under a fresh key and sent once + /// the server's delay has passed. Returns `false` when the fresh attempt + /// could not be saved, leaving the failure terminal. + func scheduleRateLimitedSendRetry( + replacing attempt: AidenChatDraftStore.PendingSend, + error: AidenRemoteClientError, + session: AidenChatDraftStore.Session, + isContextLive: @MainActor () -> Bool, + now: Date = Date(), + onRetry: @escaping @MainActor () async -> Void + ) async -> Bool { + await draftStore.settlePendingSend(key: attempt.key, session: session) + turnAttempts.reset() + let fresh = AidenChatDraftStore.PendingSend( + deviceId: attempt.deviceId, + request: attempt.request, + key: turnAttempts.key(for: attempt.request), + createdAt: now, + attachments: attempt.attachments + ) + do { + try await draftStore.savePendingSend(fresh, session: session) + } catch { + turnAttempts.reset() + return false + } + pendingSend = fresh + // The resend belongs to the pairing that authorized this message; a + // re-pair while the record was being saved leaves Retry to the person. + guard isContextLive(), rateLimitedSendRetries < Self.maxRateLimitedSendRetries else { + rateLimitRetryState = .refusedBecauseBusy + return true + } + let delay: Duration = error.serverRetryAfterSeconds.map { .seconds($0) } + ?? .milliseconds(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: rateLimitedSendRetries)) + rateLimitedSendRetries += 1 + rateLimitedSendRetryTask?.cancel() + rateLimitRetryState = .waitingAutomatic + let sleep = rateLimitedSendRetrySleep + let key = fresh.key + rateLimitedSendRetryTask = Task { [weak self] in + do { try await sleep(delay) } catch { return } + guard let self, !Task.isCancelled, self.pendingSend?.key == key else { return } + self.rateLimitedSendRetryTask = nil + self.rateLimitRetryState = .none + await onRetry() + } + return true + } +} diff --git a/ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift b/ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift index 261250439a..d4b98541e6 100644 --- a/ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift +++ b/ios/AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift @@ -4,38 +4,565 @@ import Observation import Speech import UIKit +/// Pure state/resource reducer for `ComposerVoiceInputController`. +/// +/// Consolidates every state transition across `(state, backend, resources, +/// suppressNextRecognitionError, sessionFence)` and guarantees that every exit +/// to `.idle` emits teardown effects for any owned audio tap, `AVAudioSession`, +/// recognition request/task, Mac accumulator/transcriber, and async tasks. +struct ComposerVoiceInputReducer: Equatable, Sendable { + enum Backend: Equatable, Sendable { + case none + case nativeOnDevice + case pairedMac + } + + struct ResourceOwnership: Equatable, Sendable { + var audioSessionActivated = false + var audioTapInstalled = false + var audioEngineActive = false + var capturingPublished = false + var recognitionRequestActive = false + var recognitionTaskActive = false + var macAccumulatorActive = false + var macTranscriberActive = false + var macTranscriptionTaskActive = false + var nativeFinalizationTaskActive = false + + static let none = ResourceOwnership() + + var isClean: Bool { self == .none } + } + + enum Effect: Equatable, Sendable { + case stopAcceptingDraftUpdates + case setCapturing(Bool) + case teardownAudioCapture(removeTap: Bool, deactivateAudioSession: Bool) + case endRecognitionAudio + case releaseRecognition(cancelTask: Bool) + case releaseMacCaptureResources + case cancelMacTranscriptionTask + case cancelNativeFinalizationTask + case scheduleNativeFinalizationTimeout(session: Int) + case recordFailureDiagnostic(VoiceInputFailureLogCategory) + case setErrorMessage(String?) + case clearLiveTranscript + } + + struct BeginResult: Equatable, Sendable { + let session: Int + let effects: [Effect] + } + + enum StopKeepingTranscriptAction: Equatable, Sendable { + case ignore + case finishPairedMac(session: Int, effects: [Effect]) + case finalizeNative(session: Int, effects: [Effect]) + } + + private(set) var state: ComposerVoiceInputController.State = .idle + private(set) var backend: Backend = .none + private(set) var resources: ResourceOwnership = .none + private(set) var suppressNextRecognitionError = false + private(set) var sessionFence = ComposerVoiceSessionFence() + + func isCurrent(_ session: Int) -> Bool { + sessionFence.accepts(session) + } + + mutating func beginSession(backend: Backend) -> BeginResult? { + guard state == .idle, backend != .none else { return nil } + let session = sessionFence.advance() + var effects: [Effect] = [] + if resources.macTranscriptionTaskActive { + resources.macTranscriptionTaskActive = false + effects.append(.cancelMacTranscriptionTask) + } + if resources.nativeFinalizationTaskActive { + resources.nativeFinalizationTaskActive = false + effects.append(.cancelNativeFinalizationTask) + } + suppressNextRecognitionError = false + self.backend = backend + state = .requestingPermission + if backend == .pairedMac { + resources.macTranscriberActive = true + } + effects.append(.setErrorMessage(nil)) + effects.append(.clearLiveTranscript) + return BeginResult(session: session, effects: effects) + } + + /// Cleans up any stale capture resources before starting a new engine. + mutating func prepareAudioCapture() -> [Effect] { + var effects: [Effect] = [] + if resources.capturingPublished { + resources.capturingPublished = false + effects.append(.setCapturing(false)) + } + if resources.audioEngineActive || resources.audioTapInstalled || resources.audioSessionActivated { + let removeTap = resources.audioTapInstalled + let deactivateSession = resources.audioSessionActivated + resources.audioEngineActive = false + resources.audioTapInstalled = false + resources.audioSessionActivated = false + effects.append(.teardownAudioCapture(removeTap: removeTap, deactivateAudioSession: deactivateSession)) + } + if resources.recognitionRequestActive || resources.recognitionTaskActive { + resources.recognitionRequestActive = false + resources.recognitionTaskActive = false + effects.append(.releaseRecognition(cancelTask: true)) + } + return effects + } + + mutating func didActivateAudioSession() { + resources.audioSessionActivated = true + } + + mutating func didAttachAudioEngine() { + resources.audioEngineActive = true + } + + mutating func didInstallAudioTap() { + resources.audioTapInstalled = true + } + + mutating func didCreateRecognitionRequest() { + resources.recognitionRequestActive = true + } + + mutating func didStartRecognitionTask() { + resources.recognitionTaskActive = true + } + + mutating func didCreateMacAccumulator() { + resources.macAccumulatorActive = true + } + + mutating func didStartListening(session: Int) -> [Effect]? { + guard isCurrent(session), state == .requestingPermission else { return nil } + state = .listening + resources.capturingPublished = true + return [.setCapturing(true)] + } + + mutating func stopKeepingTranscript() -> StopKeepingTranscriptAction { + guard state == .listening else { return .ignore } + let session = sessionFence.current + switch backend { + case .pairedMac: + var effects: [Effect] = [] + if resources.capturingPublished { + resources.capturingPublished = false + effects.append(.setCapturing(false)) + } + if resources.audioEngineActive || resources.audioTapInstalled || resources.audioSessionActivated { + let removeTap = resources.audioTapInstalled + let deactivateSession = resources.audioSessionActivated + resources.audioEngineActive = false + resources.audioTapInstalled = false + resources.audioSessionActivated = false + effects.append(.teardownAudioCapture(removeTap: removeTap, deactivateAudioSession: deactivateSession)) + } + if resources.recognitionRequestActive || resources.recognitionTaskActive { + resources.recognitionRequestActive = false + resources.recognitionTaskActive = false + effects.append(.releaseRecognition(cancelTask: true)) + } + if resources.macAccumulatorActive || resources.macTranscriberActive { + resources.macAccumulatorActive = false + resources.macTranscriberActive = false + effects.append(.releaseMacCaptureResources) + } + return .finishPairedMac(session: session, effects: effects) + + case .nativeOnDevice: + suppressNextRecognitionError = true + state = .transcribing + var effects: [Effect] = [] + if resources.capturingPublished { + resources.capturingPublished = false + effects.append(.setCapturing(false)) + } + if resources.audioEngineActive || resources.audioTapInstalled || resources.audioSessionActivated { + let removeTap = resources.audioTapInstalled + let deactivateSession = resources.audioSessionActivated + resources.audioEngineActive = false + resources.audioTapInstalled = false + resources.audioSessionActivated = false + effects.append(.teardownAudioCapture(removeTap: removeTap, deactivateAudioSession: deactivateSession)) + } + if resources.recognitionRequestActive { + effects.append(.endRecognitionAudio) + } + if resources.nativeFinalizationTaskActive { + effects.append(.cancelNativeFinalizationTask) + } + resources.nativeFinalizationTaskActive = true + effects.append(.scheduleNativeFinalizationTimeout(session: session)) + return .finalizeNative(session: session, effects: effects) + + case .none: + return .ignore + } + } + + mutating func beginMacTranscription(session: Int) -> [Effect]? { + guard isCurrent(session), backend == .pairedMac else { return nil } + state = .transcribing + var effects: [Effect] = [] + if resources.macTranscriptionTaskActive { + effects.append(.cancelMacTranscriptionTask) + } + resources.macTranscriptionTaskActive = true + return effects + } + + mutating func macTranscriptionCompleted(session: Int) -> [Effect]? { + guard isCurrent(session), state == .transcribing, backend == .pairedMac else { return nil } + // The completing task is already exiting, so do not emit self-cancellation. + resources.macTranscriptionTaskActive = false + return transitionToIdle(cancelRecognitionTask: true) + } + + mutating func nativeFinalizationTimedOut(session: Int) -> [Effect]? { + guard isCurrent(session), state == .transcribing, backend == .nativeOnDevice else { return nil } + // The timeout task itself is exiting now. + resources.nativeFinalizationTaskActive = false + suppressNextRecognitionError = false + return transitionToIdle(cancelRecognitionTask: true) + } + + mutating func nativeRecognitionTerminated( + session: Int, + errorDescription: String? + ) -> [Effect]? { + guard isCurrent(session), state != .idle, backend == .nativeOnDevice else { return nil } + var effects = transitionToIdle(cancelRecognitionTask: false) + if let errorDescription { + if suppressNextRecognitionError { + suppressNextRecognitionError = false + } else { + effects.append(.setErrorMessage(errorDescription)) + } + } else { + suppressNextRecognitionError = false + } + return effects + } + + mutating func stopForSubmitOrCancel() -> [Effect] { + _ = sessionFence.advance() + suppressNextRecognitionError = true + return transitionToIdle(cancelRecognitionTask: true) + } + + mutating func fail( + session: Int?, + message: String, + logCategory: VoiceInputFailureLogCategory + ) -> [Effect]? { + if let session, !isCurrent(session) { return nil } + suppressNextRecognitionError = false + var effects: [Effect] = [.recordFailureDiagnostic(logCategory)] + effects.append(contentsOf: transitionToIdle(cancelRecognitionTask: true)) + effects.append(.setErrorMessage(message)) + return effects + } + + /// Single canonical exit to `.idle`. Guarantees every owned resource flag + /// is drained and emitted as an explicit teardown effect so no exit to + /// `.idle` can leak a tap, `AVAudioSession`, recognition handle, or task. + private mutating func transitionToIdle(cancelRecognitionTask: Bool) -> [Effect] { + var effects: [Effect] = [] + if resources.macTranscriptionTaskActive { + resources.macTranscriptionTaskActive = false + effects.append(.cancelMacTranscriptionTask) + } + if resources.nativeFinalizationTaskActive { + resources.nativeFinalizationTaskActive = false + effects.append(.cancelNativeFinalizationTask) + } + effects.append(.stopAcceptingDraftUpdates) + if resources.capturingPublished { + resources.capturingPublished = false + effects.append(.setCapturing(false)) + } + if resources.audioEngineActive || resources.audioTapInstalled || resources.audioSessionActivated { + let removeTap = resources.audioTapInstalled + let deactivateSession = resources.audioSessionActivated + resources.audioEngineActive = false + resources.audioTapInstalled = false + resources.audioSessionActivated = false + effects.append(.teardownAudioCapture(removeTap: removeTap, deactivateAudioSession: deactivateSession)) + } + if resources.recognitionRequestActive || resources.recognitionTaskActive { + resources.recognitionRequestActive = false + resources.recognitionTaskActive = false + effects.append(.releaseRecognition(cancelTask: cancelRecognitionTask)) + } + if resources.macAccumulatorActive || resources.macTranscriberActive { + resources.macAccumulatorActive = false + resources.macTranscriberActive = false + effects.append(.releaseMacCaptureResources) + } + resources = .none + backend = .none + state = .idle + return effects + } +} + +// MARK: - Injectable Platform Seams + +struct ComposerVoiceAudioSessionInputMetrics: Equatable, Sendable { + let isInputAvailable: Bool + let sampleRate: Double + let inputNumberOfChannels: Int +} + +@MainActor +protocol ComposerVoiceAudioSessionDriver: AnyObject { + func activateForRecording() throws -> ComposerVoiceAudioSessionInputMetrics + func deactivateAfterRecording() +} + +protocol ComposerVoiceNativeRecognitionRequest: AnyObject, Sendable { + func append(_ buffer: AVAudioPCMBuffer) + func endAudio() +} + +@MainActor +protocol ComposerVoiceNativeRecognitionTask: AnyObject { + func cancel() +} + +struct ComposerVoiceRecognitionUpdate: Equatable, Sendable { + let transcript: String? + let isFinal: Bool + let errorDescription: String? +} + +@MainActor +protocol ComposerVoiceAudioEngineHandle: AnyObject { + var isRunning: Bool { get } + var inputSampleRate: Double { get } + var inputChannelCount: UInt32 { get } + func installMacTap(into accumulator: ComposerMacSpeechPCMAccumulator) + func installNativeTap(forwardingTo request: any ComposerVoiceNativeRecognitionRequest) + func prepareAndStart() throws + func stopAndReset(removeTap: Bool) +} + +@MainActor +protocol ComposerVoiceNativeSpeechDriver: AnyObject { + func prepareOnDeviceRecognizer(for locale: Locale) -> Bool + func makeRequest() -> any ComposerVoiceNativeRecognitionRequest + func startRecognition( + request: any ComposerVoiceNativeRecognitionRequest, + onUpdate: @escaping @MainActor (ComposerVoiceRecognitionUpdate) -> Void + ) -> (any ComposerVoiceNativeRecognitionTask)? +} + +// MARK: - Live Platform Implementations + +@MainActor +private final class LiveComposerVoiceAudioSessionDriver: ComposerVoiceAudioSessionDriver { + func activateForRecording() throws -> ComposerVoiceAudioSessionInputMetrics { + let audioSession = AVAudioSession.sharedInstance() + try audioSession.setCategory( + ComposerVoiceAudioSessionConfiguration.category, + mode: ComposerVoiceAudioSessionConfiguration.mode, + options: ComposerVoiceAudioSessionConfiguration.options + ) + try audioSession.setActive(true, options: .notifyOthersOnDeactivation) + return ComposerVoiceAudioSessionInputMetrics( + isInputAvailable: audioSession.isInputAvailable, + sampleRate: audioSession.sampleRate, + inputNumberOfChannels: audioSession.inputNumberOfChannels + ) + } + + func deactivateAfterRecording() { + try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + } +} + +private final class LiveComposerVoiceNativeRecognitionRequest: ComposerVoiceNativeRecognitionRequest, @unchecked Sendable { + let underlying: SFSpeechAudioBufferRecognitionRequest + + init() { + let request = SFSpeechAudioBufferRecognitionRequest() + request.shouldReportPartialResults = true + request.requiresOnDeviceRecognition = true + self.underlying = request + } + + func append(_ buffer: AVAudioPCMBuffer) { + underlying.append(buffer) + } + + func endAudio() { + underlying.endAudio() + } +} + +@MainActor +private final class LiveComposerVoiceNativeRecognitionTask: ComposerVoiceNativeRecognitionTask { + private let underlying: SFSpeechRecognitionTask + + init(_ underlying: SFSpeechRecognitionTask) { + self.underlying = underlying + } + + func cancel() { + underlying.cancel() + } +} + +@MainActor +private final class LiveComposerVoiceAudioEngineHandle: ComposerVoiceAudioEngineHandle { + private let engine: AVAudioEngine + + init(engine: AVAudioEngine) { + self.engine = engine + } + + var isRunning: Bool { engine.isRunning } + + var inputSampleRate: Double { + engine.inputNode.outputFormat(forBus: 0).sampleRate + } + + var inputChannelCount: UInt32 { + engine.inputNode.outputFormat(forBus: 0).channelCount + } + + func installMacTap(into accumulator: ComposerMacSpeechPCMAccumulator) { + let inputNode = engine.inputNode + let recordingFormat = inputNode.outputFormat(forBus: 0) + inputNode.installTap(onBus: 0, bufferSize: 1_024, format: recordingFormat) { buffer, _ in + accumulator.append(buffer) + } + } + + func installNativeTap(forwardingTo request: any ComposerVoiceNativeRecognitionRequest) { + let inputNode = engine.inputNode + let recordingFormat = inputNode.outputFormat(forBus: 0) + inputNode.installTap(onBus: 0, bufferSize: 1_024, format: recordingFormat) { [weak request] buffer, _ in + request?.append(buffer) + } + } + + func prepareAndStart() throws { + engine.prepare() + try engine.start() + } + + func stopAndReset(removeTap: Bool) { + if engine.isRunning { engine.stop() } + if removeTap { + engine.inputNode.removeTap(onBus: 0) + } + engine.reset() + } +} + +@MainActor +private final class LiveComposerVoiceNativeSpeechDriver: ComposerVoiceNativeSpeechDriver { + private let speechRecognizerFactory: () -> SFSpeechRecognizer? + private var speechRecognizer: SFSpeechRecognizer? + + init(speechRecognizerFactory: @escaping () -> SFSpeechRecognizer?) { + self.speechRecognizerFactory = speechRecognizerFactory + } + + func prepareOnDeviceRecognizer(for locale: Locale) -> Bool { + if let speechRecognizer { + return speechRecognizer.supportsOnDeviceRecognition + } + let target = Self.normalizedLocaleIdentifier(locale.identifier) + guard SFSpeechRecognizer.supportedLocales().contains(where: { + Self.normalizedLocaleIdentifier($0.identifier) == target + }) else { return false } + + let recognizer = speechRecognizerFactory() + guard recognizer?.supportsOnDeviceRecognition == true else { return false } + speechRecognizer = recognizer + return true + } + + func makeRequest() -> any ComposerVoiceNativeRecognitionRequest { + LiveComposerVoiceNativeRecognitionRequest() + } + + func startRecognition( + request: any ComposerVoiceNativeRecognitionRequest, + onUpdate: @escaping @MainActor (ComposerVoiceRecognitionUpdate) -> Void + ) -> (any ComposerVoiceNativeRecognitionTask)? { + guard let speechRecognizer, + let liveRequest = request as? LiveComposerVoiceNativeRecognitionRequest else { + return nil + } + let task = speechRecognizer.recognitionTask(with: liveRequest.underlying) { result, error in + let update = ComposerVoiceRecognitionUpdate( + transcript: result?.bestTranscription.formattedString, + isFinal: result?.isFinal == true, + errorDescription: error?.localizedDescription + ) + Task { @MainActor in onUpdate(update) } + } + return LiveComposerVoiceNativeRecognitionTask(task) + } + + private static func normalizedLocaleIdentifier(_ identifier: String) -> String { + identifier.replacingOccurrences(of: "_", with: "-").lowercased() + } +} + +// MARK: - Controller + /// Composer dictation using either native on-device recognition or the explicitly /// selected, authenticated paired-Mac local speech model. @MainActor @Observable final class ComposerVoiceInputController { - enum State: Equatable { + enum State: Equatable, Sendable { case idle case requestingPermission case listening case transcribing } - private(set) var state: State = .idle + struct Dependencies { + var selectedMode: @MainActor () -> AidenVoiceInputMode + var isAppActive: @MainActor () -> Bool + var requestMicrophonePermission: @MainActor () async -> Bool + var requestSpeechAuthorization: @MainActor () async -> SFSpeechRecognizerAuthorizationStatus + var audioSession: any ComposerVoiceAudioSessionDriver + var audioEngineFactory: @MainActor () -> any ComposerVoiceAudioEngineHandle + var nativeSpeech: any ComposerVoiceNativeSpeechDriver + var makeMacAccumulator: @MainActor () -> ComposerMacSpeechPCMAccumulator + var finalizationSleep: @Sendable (Duration) async throws -> Void + var setCapturing: @MainActor (Bool) -> Void + } + + private(set) var reducer = ComposerVoiceInputReducer() + var state: State { reducer.state } private(set) var errorMessage: String? private(set) var liveTranscript = "" - private let speechRecognizerFactory: () -> SFSpeechRecognizer? - private let audioEngineFactory: () -> AVAudioEngine - private var speechRecognizer: SFSpeechRecognizer? - private var audioEngine: AVAudioEngine? - private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? - private var recognitionTask: SFSpeechRecognitionTask? - private var draftUpdateSession = ComposerVoiceDraftUpdateSession() - private var updateDraft: ((String) -> Void)? - private var suppressNextRecognitionError = false - private var activatedAudioSessionForRecording = false - private var audioTapInstalled = false - private var macAccumulator: ComposerMacSpeechPCMAccumulator? - private var macTranscriber: ((Data) async throws -> String)? - private var macTranscriptionTask: Task? - private var nativeFinalizationTask: Task? - private var sessionFence = ComposerVoiceSessionFence() + @ObservationIgnored private let dependencies: Dependencies + @ObservationIgnored private var audioEngine: (any ComposerVoiceAudioEngineHandle)? + @ObservationIgnored private var recognitionRequest: (any ComposerVoiceNativeRecognitionRequest)? + @ObservationIgnored private var recognitionTask: (any ComposerVoiceNativeRecognitionTask)? + @ObservationIgnored private var draftUpdateSession = ComposerVoiceDraftUpdateSession() + @ObservationIgnored private var updateDraft: ((String) -> Void)? + @ObservationIgnored private var macAccumulator: ComposerMacSpeechPCMAccumulator? + @ObservationIgnored private var macTranscriber: ((Data) async throws -> String)? + @ObservationIgnored private var macTranscriptionTask: Task? + @ObservationIgnored private var nativeFinalizationTask: Task? @ObservationIgnored var locale = Locale.current @@ -45,8 +572,31 @@ final class ComposerVoiceInputController { }, audioEngineFactory: @escaping () -> AVAudioEngine = { AVAudioEngine() } ) { - self.speechRecognizerFactory = speechRecognizerFactory - self.audioEngineFactory = audioEngineFactory + self.dependencies = Dependencies( + selectedMode: { AidenVoiceInputMode.selected }, + isAppActive: { UIApplication.shared.applicationState == .active }, + requestMicrophonePermission: { await ComposerVoiceMicrophonePermissionRequester.request() }, + requestSpeechAuthorization: { + await withCheckedContinuation { continuation in + SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) } + } + }, + audioSession: LiveComposerVoiceAudioSessionDriver(), + audioEngineFactory: { LiveComposerVoiceAudioEngineHandle(engine: audioEngineFactory()) }, + nativeSpeech: LiveComposerVoiceNativeSpeechDriver(speechRecognizerFactory: speechRecognizerFactory), + makeMacAccumulator: { ComposerMacSpeechPCMAccumulator() }, + finalizationSleep: { try await Task.sleep(for: $0) }, + setCapturing: { AidenComposerAudioCaptureState.shared.setCapturing($0) } + ) + } + + init(dependencies: Dependencies) { + self.dependencies = dependencies + } + + deinit { + macTranscriptionTask?.cancel() + nativeFinalizationTask?.cancel() } var isListening: Bool { state == .listening } @@ -61,7 +611,7 @@ final class ComposerVoiceInputController { stopKeepingTranscript() } else { guard state == .idle else { return } - if AidenVoiceInputMode.selected == .pairedMac { + if dependencies.selectedMode() == .pairedMac { await startMac( currentDraft: currentDraft, updateDraft: updateDraft, @@ -74,32 +624,21 @@ final class ComposerVoiceInputController { } func stopKeepingTranscript() { - if macAccumulator != nil { - finishMacRecording() + switch reducer.stopKeepingTranscript() { + case .ignore: return - } - suppressNextRecognitionError = true - let session = sessionFence.current - state = .transcribing - finishNativeAudioCapture() - nativeFinalizationTask?.cancel() - nativeFinalizationTask = Task { - try? await Task.sleep(for: .seconds(2)) - guard !Task.isCancelled, isCurrent(session), state == .transcribing else { return } - stopAcceptingDraftUpdates() - stopAudio(cancelTask: true) - state = .idle + case let .finishPairedMac(session, effects): + let pcm = macAccumulator?.data ?? Data() + let transcriber = macTranscriber + apply(effects) + finishMacRecording(session: session, pcm: pcm, transcriber: transcriber) + case let .finalizeNative(_, effects): + apply(effects) } } func stopBeforeSubmittingDraft() { - invalidateSession() - suppressNextRecognitionError = true - stopAcceptingDraftUpdates() - stopAudio(cancelTask: true) - macAccumulator = nil - macTranscriber = nil - state = .idle + apply(reducer.stopForSubmitOrCancel()) } func cancelDiscardingRecording() { @@ -111,323 +650,259 @@ final class ComposerVoiceInputController { updateDraft: @escaping (String) -> Void, transcriber: @escaping (Data) async throws -> String ) async { - let session = beginSession() - errorMessage = nil - liveTranscript = "" + guard let begun = reducer.beginSession(backend: .pairedMac) else { return } + let session = begun.session + apply(begun.effects) draftUpdateSession.begin(baseDraft: currentDraft) self.updateDraft = updateDraft macTranscriber = transcriber - state = .requestingPermission - let microphoneGranted = await ComposerVoiceMicrophonePermissionRequester.request() - guard isCurrent(session), state == .requestingPermission else { return } + let microphoneGranted = await dependencies.requestMicrophonePermission() + guard reducer.isCurrent(session), state == .requestingPermission else { return } guard microphoneGranted else { fail( + session: session, String(localized: "Microphone access is disabled. Enable it in Settings to use voice input."), logCategory: .microphonePermission ) return } - guard isCurrent(session), ComposerVoiceInputStartPolicy.canStart(appIsActive: UIApplication.shared.applicationState == .active) else { - fail(ComposerVoiceInputError.appNotActive.localizedDescription, logCategory: .appNotActive) + guard reducer.isCurrent(session), ComposerVoiceInputStartPolicy.canStart(appIsActive: dependencies.isAppActive()) else { + fail(session: session, ComposerVoiceInputError.appNotActive.localizedDescription, logCategory: .appNotActive) return } do { try startMacAudioCapture() - state = .listening + if let effects = reducer.didStartListening(session: session) { + apply(effects) + } } catch { - fail(error.localizedDescription, logCategory: Self.logCategory(for: error)) + fail(session: session, error.localizedDescription, logCategory: Self.logCategory(for: error)) } } private func startMacAudioCapture() throws { - stopAudio(cancelTask: true) - let audioSession = AVAudioSession.sharedInstance() - try audioSession.setCategory( - ComposerVoiceAudioSessionConfiguration.category, - mode: ComposerVoiceAudioSessionConfiguration.mode, - options: ComposerVoiceAudioSessionConfiguration.options - ) - try audioSession.setActive(true, options: .notifyOthersOnDeactivation) - activatedAudioSessionForRecording = true + apply(reducer.prepareAudioCapture()) + let metrics = try dependencies.audioSession.activateForRecording() + reducer.didActivateAudioSession() try ComposerVoiceInputStartPolicy.validateAudioSessionInput( - isInputAvailable: audioSession.isInputAvailable, - sampleRate: audioSession.sampleRate, - inputNumberOfChannels: audioSession.inputNumberOfChannels + isInputAvailable: metrics.isInputAvailable, + sampleRate: metrics.sampleRate, + inputNumberOfChannels: metrics.inputNumberOfChannels ) - let engine = audioEngineFactory() + let engine = dependencies.audioEngineFactory() audioEngine = engine - let inputNode = engine.inputNode - let recordingFormat = inputNode.outputFormat(forBus: 0) - try ComposerVoiceInputPreflight.validate(recordingFormat: recordingFormat) - let accumulator = ComposerMacSpeechPCMAccumulator() + reducer.didAttachAudioEngine() + try ComposerVoiceInputPreflight.validate( + sampleRate: engine.inputSampleRate, + channelCount: engine.inputChannelCount + ) + let accumulator = dependencies.makeMacAccumulator() macAccumulator = accumulator - inputNode.installTap(onBus: 0, bufferSize: 1_024, format: recordingFormat) { buffer, _ in - accumulator.append(buffer) - } - audioTapInstalled = true - engine.prepare() - try engine.start() - AidenComposerAudioCaptureState.shared.setCapturing(true) + reducer.didCreateMacAccumulator() + engine.installMacTap(into: accumulator) + reducer.didInstallAudioTap() + try engine.prepareAndStart() } - private func finishMacRecording() { - let session = sessionFence.current - let pcm = macAccumulator?.data ?? Data() - let transcriber = macTranscriber - macAccumulator = nil - macTranscriber = nil - stopAudio(cancelTask: true) + private func finishMacRecording( + session: Int, + pcm: Data, + transcriber: ((Data) async throws -> String)? + ) { guard !pcm.isEmpty, let transcriber else { - fail(String(localized: "No speech was recorded."), logCategory: .audioStartup) + fail(session: session, String(localized: "No speech was recorded."), logCategory: .audioStartup) return } - state = .transcribing - macTranscriptionTask?.cancel() - macTranscriptionTask = Task { + guard let effects = reducer.beginMacTranscription(session: session) else { return } + apply(effects) + macTranscriptionTask = Task { [weak self] in do { let transcript = try await transcriber(pcm) try Task.checkCancellation() - guard isCurrent(session), state == .transcribing else { return } - liveTranscript = transcript - if let draft = draftUpdateSession.composedDraft(for: transcript) { - updateDraft?(draft) + guard let self, self.reducer.isCurrent(session), self.state == .transcribing else { return } + self.liveTranscript = transcript + if let draft = self.draftUpdateSession.composedDraft(for: transcript) { + self.updateDraft?(draft) + } + self.macTranscriptionTask = nil + if let completionEffects = self.reducer.macTranscriptionCompleted(session: session) { + self.apply(completionEffects) } - stopAcceptingDraftUpdates() - state = .idle } catch { - guard !Task.isCancelled, isCurrent(session), state == .transcribing else { return } - fail(error.localizedDescription, logCategory: .audioStartup) + guard let self, !Task.isCancelled, self.reducer.isCurrent(session), self.state == .transcribing else { return } + self.macTranscriptionTask = nil + self.fail(session: session, error.localizedDescription, logCategory: .audioStartup) } } } private func start(currentDraft: String, updateDraft: @escaping (String) -> Void) async { - guard state == .idle else { return } - let session = beginSession() - - errorMessage = nil - liveTranscript = "" - suppressNextRecognitionError = false + guard let begun = reducer.beginSession(backend: .nativeOnDevice) else { return } + let session = begun.session + apply(begun.effects) draftUpdateSession.begin(baseDraft: currentDraft) self.updateDraft = updateDraft - state = .requestingPermission - guard let speechRecognizer = onDeviceSpeechRecognizerForRecording() else { + guard dependencies.nativeSpeech.prepareOnDeviceRecognizer(for: locale) else { fail( + session: session, String(localized: "On-device speech recognition is not available for the current locale."), logCategory: .speechUnavailable ) return } - let speechStatus = await requestSpeechAuthorization() - guard isCurrent(session), state == .requestingPermission else { return } + let speechStatus = await dependencies.requestSpeechAuthorization() + guard reducer.isCurrent(session), state == .requestingPermission else { return } guard speechStatus == .authorized else { - fail(Self.speechAuthorizationMessage(for: speechStatus), logCategory: .speechAuthorization) + fail(session: session, Self.speechAuthorizationMessage(for: speechStatus), logCategory: .speechAuthorization) return } - let microphoneGranted = await ComposerVoiceMicrophonePermissionRequester.request() - guard isCurrent(session), state == .requestingPermission else { return } + let microphoneGranted = await dependencies.requestMicrophonePermission() + guard reducer.isCurrent(session), state == .requestingPermission else { return } guard microphoneGranted else { fail( + session: session, String(localized: "Microphone access is disabled. Enable it in Settings to use voice input."), logCategory: .microphonePermission ) return } - guard isCurrent(session), ComposerVoiceInputStartPolicy.canStart( - appIsActive: UIApplication.shared.applicationState == .active + guard reducer.isCurrent(session), ComposerVoiceInputStartPolicy.canStart( + appIsActive: dependencies.isAppActive() ) else { - fail(ComposerVoiceInputError.appNotActive.localizedDescription, logCategory: .appNotActive) + fail(session: session, ComposerVoiceInputError.appNotActive.localizedDescription, logCategory: .appNotActive) return } do { - try startRecognition(speechRecognizer: speechRecognizer, session: session) - state = .listening + try startRecognition(session: session) + if let effects = reducer.didStartListening(session: session) { + apply(effects) + } } catch { - fail(error.localizedDescription, logCategory: Self.logCategory(for: error)) + fail(session: session, error.localizedDescription, logCategory: Self.logCategory(for: error)) } } - private func startRecognition(speechRecognizer: SFSpeechRecognizer, session: Int) throws { - stopAudio(cancelTask: true) + private func startRecognition(session: Int) throws { + apply(reducer.prepareAudioCapture()) - let audioSession = AVAudioSession.sharedInstance() - try audioSession.setCategory( - ComposerVoiceAudioSessionConfiguration.category, - mode: ComposerVoiceAudioSessionConfiguration.mode, - options: ComposerVoiceAudioSessionConfiguration.options - ) - try audioSession.setActive(true, options: .notifyOthersOnDeactivation) - activatedAudioSessionForRecording = true + let metrics = try dependencies.audioSession.activateForRecording() + reducer.didActivateAudioSession() try ComposerVoiceInputStartPolicy.validateAudioSessionInput( - isInputAvailable: audioSession.isInputAvailable, - sampleRate: audioSession.sampleRate, - inputNumberOfChannels: audioSession.inputNumberOfChannels + isInputAvailable: metrics.isInputAvailable, + sampleRate: metrics.sampleRate, + inputNumberOfChannels: metrics.inputNumberOfChannels ) - let request = SFSpeechAudioBufferRecognitionRequest() - request.shouldReportPartialResults = true - request.requiresOnDeviceRecognition = true + let request = dependencies.nativeSpeech.makeRequest() recognitionRequest = request + reducer.didCreateRecognitionRequest() - let engine = audioEngineFactory() + let engine = dependencies.audioEngineFactory() audioEngine = engine + reducer.didAttachAudioEngine() try ComposerVoiceInputStartPolicy.validateAudioEngine(isRunning: engine.isRunning) + try ComposerVoiceInputPreflight.validate( + sampleRate: engine.inputSampleRate, + channelCount: engine.inputChannelCount + ) + engine.installNativeTap(forwardingTo: request) + reducer.didInstallAudioTap() - let inputNode = engine.inputNode - let recordingFormat = inputNode.outputFormat(forBus: 0) - try ComposerVoiceInputPreflight.validate(recordingFormat: recordingFormat) - inputNode.installTap(onBus: 0, bufferSize: 1_024, format: recordingFormat) { [weak request] buffer, _ in - request?.append(buffer) + recognitionTask = dependencies.nativeSpeech.startRecognition(request: request) { [weak self] update in + self?.handleRecognition(update: update, session: session) } - audioTapInstalled = true - - engine.prepare() - recognitionTask = speechRecognizer.recognitionTask(with: request) { [weak self] result, error in - Task { @MainActor in self?.handleRecognition(result: result, error: error, session: session) } + if recognitionTask != nil { + reducer.didStartRecognitionTask() } - try engine.start() - AidenComposerAudioCaptureState.shared.setCapturing(true) + try engine.prepareAndStart() } - private func handleRecognition(result: SFSpeechRecognitionResult?, error: Error?, session: Int) { - guard isCurrent(session), state != .idle else { return } - if let result { - liveTranscript = result.bestTranscription.formattedString + private func handleRecognition(update: ComposerVoiceRecognitionUpdate, session: Int) { + guard reducer.isCurrent(session), state != .idle else { return } + if let transcript = update.transcript { + liveTranscript = transcript if let draft = draftUpdateSession.composedDraft(for: liveTranscript) { updateDraft?(draft) } } - if let error { - nativeFinalizationTask?.cancel() - nativeFinalizationTask = nil - stopAcceptingDraftUpdates() - stopAudio(cancelTask: false) - state = .idle - if suppressNextRecognitionError { - suppressNextRecognitionError = false - } else { - errorMessage = error.localizedDescription - } - } else if result?.isFinal == true { - nativeFinalizationTask?.cancel() - nativeFinalizationTask = nil - stopAcceptingDraftUpdates() - stopAudio(cancelTask: false) - state = .idle - suppressNextRecognitionError = false - } - } - - private func stopAcceptingDraftUpdates() { - draftUpdateSession.stopAcceptingUpdates() - updateDraft = nil - } - - private func stopAudio(cancelTask: Bool) { - AidenComposerAudioCaptureState.shared.setCapturing(false) - if let audioEngine { - if audioEngine.isRunning { audioEngine.stop() } - if audioTapInstalled { - audioEngine.inputNode.removeTap(onBus: 0) - audioTapInstalled = false + if let errorDescription = update.errorDescription { + if let effects = reducer.nativeRecognitionTerminated(session: session, errorDescription: errorDescription) { + apply(effects) } - audioEngine.reset() - } - audioEngine = nil - recognitionRequest?.endAudio() - if cancelTask { recognitionTask?.cancel() } - recognitionTask = nil - recognitionRequest = nil - if activatedAudioSessionForRecording { - try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) - activatedAudioSessionForRecording = false - } - } - - private func finishNativeAudioCapture() { - AidenComposerAudioCaptureState.shared.setCapturing(false) - if let audioEngine { - if audioEngine.isRunning { audioEngine.stop() } - if audioTapInstalled { - audioEngine.inputNode.removeTap(onBus: 0) - audioTapInstalled = false + } else if update.isFinal { + if let effects = reducer.nativeRecognitionTerminated(session: session, errorDescription: nil) { + apply(effects) } - audioEngine.reset() - } - audioEngine = nil - recognitionRequest?.endAudio() - if activatedAudioSessionForRecording { - try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) - activatedAudioSessionForRecording = false - } - } - - private func onDeviceSpeechRecognizerForRecording() -> SFSpeechRecognizer? { - if let speechRecognizer { - return speechRecognizer.supportsOnDeviceRecognition ? speechRecognizer : nil } - - let target = Self.normalizedLocaleIdentifier(locale.identifier) - guard SFSpeechRecognizer.supportedLocales().contains(where: { - Self.normalizedLocaleIdentifier($0.identifier) == target - }) else { return nil } - - let recognizer = speechRecognizerFactory() - guard recognizer?.supportsOnDeviceRecognition == true else { return nil } - speechRecognizer = recognizer - return recognizer - } - - private static func normalizedLocaleIdentifier(_ identifier: String) -> String { - identifier.replacingOccurrences(of: "_", with: "-").lowercased() - } - - private func fail(_ message: String, logCategory: VoiceInputFailureLogCategory) { - AidenDiagnostics.record( - .speech, - event: .speechFailed, - outcome: .failed, - code: logCategory.diagnosticCode - ) - suppressNextRecognitionError = false - stopAcceptingDraftUpdates() - stopAudio(cancelTask: true) - macAccumulator = nil - macTranscriber = nil - state = .idle - errorMessage = message - } - - private func beginSession() -> Int { - let session = sessionFence.advance() - macTranscriptionTask?.cancel() - macTranscriptionTask = nil - nativeFinalizationTask?.cancel() - nativeFinalizationTask = nil - return session } - private func invalidateSession() { - sessionFence.advance() - macTranscriptionTask?.cancel() - macTranscriptionTask = nil - nativeFinalizationTask?.cancel() - nativeFinalizationTask = nil + private func fail(session: Int?, _ message: String, logCategory: VoiceInputFailureLogCategory) { + guard let effects = reducer.fail(session: session, message: message, logCategory: logCategory) else { return } + apply(effects) } - private func isCurrent(_ session: Int) -> Bool { sessionFence.accepts(session) } - - private func requestSpeechAuthorization() async -> SFSpeechRecognizerAuthorizationStatus { - await withCheckedContinuation { continuation in - SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) } + private func apply(_ effects: [ComposerVoiceInputReducer.Effect]) { + for effect in effects { + switch effect { + case .stopAcceptingDraftUpdates: + draftUpdateSession.stopAcceptingUpdates() + updateDraft = nil + case let .setCapturing(capturing): + dependencies.setCapturing(capturing) + case let .teardownAudioCapture(removeTap, deactivateAudioSession): + if let audioEngine { + audioEngine.stopAndReset(removeTap: removeTap) + } + audioEngine = nil + if deactivateAudioSession { + dependencies.audioSession.deactivateAfterRecording() + } + case .endRecognitionAudio: + recognitionRequest?.endAudio() + case let .releaseRecognition(cancelTask): + recognitionRequest?.endAudio() + if cancelTask { recognitionTask?.cancel() } + recognitionTask = nil + recognitionRequest = nil + case .releaseMacCaptureResources: + macAccumulator = nil + macTranscriber = nil + case .cancelMacTranscriptionTask: + macTranscriptionTask?.cancel() + macTranscriptionTask = nil + case .cancelNativeFinalizationTask: + nativeFinalizationTask?.cancel() + nativeFinalizationTask = nil + case let .scheduleNativeFinalizationTimeout(session): + let sleep = dependencies.finalizationSleep + nativeFinalizationTask = Task { [weak self] in + try? await sleep(.seconds(2)) + guard !Task.isCancelled, let self else { return } + self.nativeFinalizationTask = nil + if let timeoutEffects = self.reducer.nativeFinalizationTimedOut(session: session) { + self.apply(timeoutEffects) + } + } + case let .recordFailureDiagnostic(logCategory): + AidenDiagnostics.record( + .speech, + event: .speechFailed, + outcome: .failed, + code: logCategory.diagnosticCode + ) + case let .setErrorMessage(message): + errorMessage = message + case .clearLiveTranscript: + liveTranscript = "" + } } } @@ -457,7 +932,7 @@ final class ComposerVoiceInputController { } } -struct ComposerVoiceSessionFence { +struct ComposerVoiceSessionFence: Equatable, Sendable { private(set) var current = 0 mutating func advance() -> Int { @@ -547,7 +1022,7 @@ enum ComposerVoiceInputError: LocalizedError { } } -enum VoiceInputFailureLogCategory: String { +enum VoiceInputFailureLogCategory: String, Equatable, Sendable { case speechUnavailable, speechAuthorization, microphonePermission, appNotActive case noAudioInput, invalidInputFormat, audioEngineAlreadyRunning, audioStartup } diff --git a/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift b/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift index dce0ad8558..15e7e05b88 100644 --- a/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift +++ b/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift @@ -87,7 +87,7 @@ final class AidenHostConnection { /// How an attempt reaches the machine. A person waits on `interactive`, and /// its failure is theirs to see. `probe` is a background check: it gives up /// rather than waits, and it never touches the app-wide error. - enum ConnectRoute { + enum ConnectRoute: Equatable, Sendable { case interactive case probe } @@ -104,41 +104,34 @@ final class AidenHostConnection { let client: AidenRemoteClient } - private struct ConnectInFlight { + private struct ConnectInFlightTask { let attempt: Int - let route: ConnectRoute let work: Task } - /// Where the machine stood before an attempt, so stopping that attempt - /// doesn't leave it saying "Connecting". - private struct SettledState { - let connectionState: AidenRemoteConnectionState - let connectionIssue: AidenConnectionIssue? - } - let instanceId: String private(set) var installation: AidenInstallation - private(set) var connectionState: AidenRemoteConnectionState = .connecting - private(set) var connectionIssue: AidenConnectionIssue? + private(set) var lifecycle: AidenHostConnectionLifecycle + var connectionState: AidenRemoteConnectionState { lifecycle.connectionState } + var connectionIssue: AidenConnectionIssue? { lifecycle.connectionIssue } private(set) var server: AidenServer? private(set) var workspaces: [AidenWorkspace] = [] /// The activation lease every request context carries. A reconnect leaves /// it alone, so contexts survive a dropped network. Each arrival of the /// selection moves it, so A -> B -> A can't make an old context current /// again. - private(set) var generation: Int + var generation: Int { lifecycle.generation } /// The machine's own lease, which `isLive` compares. Only a re-pairing, /// `disconnect()`, or a revocation moves it. The selection never does, so /// owner work survives the selection leaving and coming back. - private(set) var hostGeneration: Int + var hostGeneration: Int { lifecycle.hostGeneration } /// Moves on every connect attempt, so a late answer from an earlier attempt /// is dropped. - private(set) var connectionGeneration: Int - private(set) var isRevoked = false + var connectionGeneration: Int { lifecycle.connectionGeneration } + var isRevoked: Bool { lifecycle.isRevoked } /// Revoked with its cached data still in place, because a view is showing /// it. `completeRevokedPurge(instanceId:)` ends this. - private(set) var isPurgePending = false + var isPurgePending: Bool { lifecycle.isPurgePending } @ObservationIgnored weak var delegate: (any AidenHostConnectionDelegate)? private let loadCredential: () throws -> String @@ -146,8 +139,7 @@ final class AidenHostConnection { private let probeClientFactory: AidenRemoteCoordinator.ClientFactory private var cachedClient: CachedClient? private var cachedProbeClient: CachedClient? - private var connectInFlight: ConnectInFlight? - private var settledState: SettledState? + @ObservationIgnored private var connectInFlightTask: ConnectInFlightTask? /// Waits out a connect's `timeout`. A test replaces it to say when the /// deadline passes, rather than racing a real one. @ObservationIgnored var waitForDeadline: @MainActor (TimeInterval) async -> Void = { timeout in @@ -170,27 +162,23 @@ final class AidenHostConnection { loadCredential = credential self.clientFactory = clientFactory self.probeClientFactory = probeClientFactory ?? clientFactory - self.generation = generation - self.hostGeneration = hostGeneration - self.connectionGeneration = connectionGeneration + self.lifecycle = AidenHostConnectionLifecycle( + generation: generation, + hostGeneration: hostGeneration, + connectionGeneration: connectionGeneration + ) } /// `timeout` bounds the whole attempt. Past it, a machine that hasn't /// answered goes offline and whatever is still running stops. func connect(over route: ConnectRoute = .interactive, timeout: TimeInterval? = nil) async { - guard !isRevoked else { return } - connectionGeneration &+= 1 - let attempt = connectionGeneration - if connectionState != .connecting { - settledState = SettledState(connectionState: connectionState, connectionIssue: connectionIssue) - } - connectionState = .connecting - connectionIssue = nil - if route == .interactive { + guard let started = lifecycle.beginConnect(over: route) else { return } + let attempt = started.attempt + if started.notifyWillConnect { delegate?.hostConnectionWillConnect(self) } let work = Task { await run(attempt: attempt, over: route) } - connectInFlight = ConnectInFlight(attempt: attempt, route: route, work: work) + connectInFlightTask = ConnectInFlightTask(attempt: attempt, work: work) let waitForDeadline = waitForDeadline let deadline = timeout.map { timeout in Task { @@ -208,39 +196,25 @@ final class AidenHostConnection { work.cancel() } deadline?.cancel() - if connectInFlight?.attempt == attempt { - connectInFlight = nil + lifecycle.finishConnect(attempt: attempt) + if connectInFlightTask?.attempt == attempt { + connectInFlightTask = nil } } /// Offline, or checking again after being offline. Each probe passes through /// `.connecting`, and that isn't news of the machine coming back. - var isKnownOffline: Bool { - switch connectionState { - case .offline: true - case .connecting: - if case .offline = settledState?.connectionState { true } else { false } - default: false - } - } + var isKnownOffline: Bool { lifecycle.isKnownOffline } /// Connected, or checking again after being connected. A machine that /// hasn't answered since launch isn't known online, whatever its saved rows /// say. - var isKnownOnline: Bool { - switch connectionState { - case .connected: true - case .connecting: settledState?.connectionState == .connected - default: false - } - } + var isKnownOnline: Bool { lifecycle.isKnownOnline } /// True while the newest attempt is running. `connectionState` can't say: /// it starts at `.connecting`, and `disconnect()` returns it there, with /// nothing in flight either time. - var isConnectInFlight: Bool { - connectInFlight?.attempt == connectionGeneration - } + var isConnectInFlight: Bool { lifecycle.isConnectInFlight } /// Stops the attempt in flight and puts the machine back where it stood /// before it. Only `connectionGeneration` moves, so every live context stays @@ -252,30 +226,21 @@ final class AidenHostConnection { /// `.probe`, so an interactive connect that took over from its probe isn't /// cut short by the app leaving the foreground. func cancelConnect(over route: ConnectRoute? = nil) { - guard isConnectInFlight else { return } - if let route, connectInFlight?.route != route { return } - connectInFlight?.work.cancel() - connectInFlight = nil - connectionGeneration &+= 1 - if connectionState == .connecting, let settledState { - connectionState = settledState.connectionState - connectionIssue = settledState.connectionIssue + guard let cancelled = lifecycle.cancelConnect(over: route) else { return } + if connectInFlightTask?.attempt == cancelled.cancelledAttempt { + connectInFlightTask?.work.cancel() + connectInFlightTask = nil } } /// Ends this connection's lease: contexts and answers from before this /// call go stale. The state returns to where a new connection starts. func disconnect() { - generation &+= 1 - hostGeneration &+= 1 - connectionGeneration &+= 1 + lifecycle.disconnect() cachedClient = nil cachedProbeClient = nil - settledState = nil server = nil workspaces = [] - connectionIssue = nil - connectionState = .connecting } func requestContext( @@ -334,7 +299,7 @@ final class AidenHostConnection { /// dropped. func handlePollError(_ error: Error, sinceConnect generation: Int) async -> Bool { let isRevocation = (error as? AidenRemoteClientError)?.isCredentialRevoked == true - guard isRevocation || (connectionGeneration == generation && !isConnectInFlight) else { return false } + guard lifecycle.acceptsPollError(sinceConnect: generation, isRevocation: isRevocation) else { return false } await record(error, over: .probe) return true } @@ -413,15 +378,13 @@ final class AidenHostConnection { } func adopt(connectionState: AidenRemoteConnectionState) { - self.connectionState = connectionState - settledState = nil - if connectionState == .needsPairing { + if lifecycle.adopt(connectionState: connectionState) { delegate?.hostConnectionNeedsPairing(self) } } func adopt(connectionIssue: AidenConnectionIssue?) { - self.connectionIssue = connectionIssue + lifecycle.adopt(connectionIssue: connectionIssue) } func adopt(server: AidenServer?) { @@ -433,36 +396,34 @@ final class AidenHostConnection { } func advanceGeneration() { - generation &+= 1 + lifecycle.advanceGeneration() } /// A new pairing replaced the one earlier contexts were issued under. func advanceHostGeneration() { - hostGeneration &+= 1 + lifecycle.advanceHostGeneration() } func advanceConnectionGeneration() { - connectionGeneration &+= 1 + lifecycle.advanceConnectionGeneration() } /// A revoked connection stays revoked: its credential is gone for good, so /// it issues no context or client and never connects again. func markRevoked() { - isRevoked = true - hostGeneration &+= 1 + lifecycle.markRevoked() } /// Revoked, with the purge held back until the views showing this machine /// have gone. Nothing here reconnects it, so it stops at `.needsPairing`. func markRevokedWithPurgePending() { - markRevoked() - isPurgePending = true - connectionIssue = nil - adopt(connectionState: .needsPairing) + if lifecycle.markRevokedWithPurgePending() { + delegate?.hostConnectionNeedsPairing(self) + } } func purgeStarted() { - isPurgePending = false + lifecycle.purgeStarted() } var isSelected: Bool { @@ -488,7 +449,7 @@ final class AidenHostConnection { /// Every attempt lands on this machine's own connection, selected or not. /// The selection leaving stops a running attempt through `cancelConnect()`. private func isCurrent(attempt: Int) -> Bool { - connectionGeneration == attempt + lifecycle.isCurrent(attempt: attempt) } private func run(attempt: Int, over route: ConnectRoute) async { @@ -506,8 +467,7 @@ final class AidenHostConnection { } private func expire(attempt: Int, over route: ConnectRoute) async { - guard isCurrent(attempt: attempt), connectionState == .connecting else { return } - connectionGeneration &+= 1 + guard lifecycle.expireConnect(attempt: attempt) else { return } await record(URLError(.timedOut), over: route) } @@ -520,21 +480,24 @@ final class AidenHostConnection { await delegate.hostConnectionWasRevokedInBackground(self) } } else { - markRevoked() - disconnect() - connectionState = .needsPairing + lifecycle.revokeStandalone() + cachedClient = nil + cachedProbeClient = nil + server = nil + workspaces = [] } return } - if let clientError = error as? AidenRemoteClientError, - case .server = clientError, connectionState != .connecting { - connectionIssue = nil - connectionState = .connected + let isServerError: Bool + if let clientError = error as? AidenRemoteClientError, case .server = clientError { + isServerError = true } else { - let issue = AidenConnectionIssue.classify(error) - connectionIssue = issue - connectionState = .offline(message: issue.message) + isServerError = false } + guard lifecycle.recordNonRevocationFailure( + isServerError: isServerError, + issue: AidenConnectionIssue.classify(error) + ) else { return } if route == .interactive { delegate?.hostConnection(self, didFailWith: error) } @@ -575,10 +538,9 @@ final class AidenHostConnection { } guard isCurrent(attempt: attempt) else { return } try delegate?.hostConnection(self, didReceive: server) + guard lifecycle.markConnected(attempt: attempt) else { return } self.server = server applyWorkspaceSnapshot(workspaces) - connectionIssue = nil - connectionState = .connected await refreshDeviceIdentity(using: client, currentName: server.deviceName) await negotiateProgressCapabilitiesIfNeeded(server: server, client: client, attempt: attempt, over: route) for capabilities in Self.capabilitiesAskedForAlone { diff --git a/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift b/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift new file mode 100644 index 0000000000..7702d03989 --- /dev/null +++ b/ios/AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift @@ -0,0 +1,292 @@ +import Foundation + +/// Pure lifecycle state machine for one paired machine's connection. +/// +/// Consolidates the eight coupled axes previously tracked across +/// `AidenHostConnection`: +/// - terminal custody (`active` vs `revoked(purgePending:)`) +/// - visible connection state and issue (`connectionState`, `connectionIssue`) +/// - prior settled state (`settledState`) for `isKnownOnline`, `isKnownOffline`, +/// and cancel-rollback +/// - in-flight connect attempt (`attemptState`: `.idle` vs `.inFlight`) +/// - monotonic lease generations (`generation`, `hostGeneration`, +/// `connectionGeneration`) +struct AidenHostConnectionLifecycle: Equatable { + enum Custody: Equatable, Sendable { + case active + case revoked(purgePending: Bool) + } + + struct SettledState: Equatable { + let connectionState: AidenRemoteConnectionState + let connectionIssue: AidenConnectionIssue? + } + + enum AttemptState: Equatable, Sendable { + case idle + case inFlight(attempt: Int, route: AidenHostConnection.ConnectRoute) + } + + struct BeginConnectResult: Equatable, Sendable { + let attempt: Int + let notifyWillConnect: Bool + } + + struct CancelConnectResult: Equatable, Sendable { + let cancelledAttempt: Int + let route: AidenHostConnection.ConnectRoute + } + + private(set) var custody: Custody + private(set) var connectionState: AidenRemoteConnectionState + private(set) var connectionIssue: AidenConnectionIssue? + private(set) var settledState: SettledState? + private(set) var attemptState: AttemptState + private(set) var generation: Int + private(set) var hostGeneration: Int + private(set) var connectionGeneration: Int + + init( + generation: Int = 0, + hostGeneration: Int = 0, + connectionGeneration: Int = 0, + connectionState: AidenRemoteConnectionState = .connecting, + connectionIssue: AidenConnectionIssue? = nil, + custody: Custody = .active + ) { + self.custody = custody + self.connectionState = connectionState + self.connectionIssue = connectionIssue + self.settledState = nil + self.attemptState = .idle + self.generation = generation + self.hostGeneration = hostGeneration + self.connectionGeneration = connectionGeneration + } + + // MARK: - Derived queries + + var isRevoked: Bool { + if case .revoked = custody { return true } + return false + } + + /// Revoked with its cached data still in place, because a view is showing + /// it. `purgeStarted()` ends this. + var isPurgePending: Bool { + if case .revoked(purgePending: true) = custody { return true } + return false + } + + /// True while the newest attempt is running. `connectionState` can't say: + /// it starts at `.connecting`, and `disconnect()` returns it there, with + /// nothing in flight either time. + var isConnectInFlight: Bool { + guard !isRevoked, case .inFlight(let attempt, _) = attemptState else { return false } + return attempt == connectionGeneration + } + + var inFlightRoute: AidenHostConnection.ConnectRoute? { + guard isConnectInFlight, case .inFlight(_, let route) = attemptState else { return nil } + return route + } + + /// Offline, or checking again after being offline. Each probe passes through + /// `.connecting`, and that isn't news of the machine coming back. + var isKnownOffline: Bool { + switch connectionState { + case .offline: true + case .connecting: + if case .offline = settledState?.connectionState { true } else { false } + default: false + } + } + + /// Connected, or checking again after being connected. A machine that + /// hasn't answered since launch isn't known online, whatever its saved rows + /// say. + var isKnownOnline: Bool { + switch connectionState { + case .connected: true + case .connecting: settledState?.connectionState == .connected + default: false + } + } + + /// Whether `attempt` is still the current attempt on an active connection. + func isCurrent(attempt: Int) -> Bool { + !isRevoked && connectionGeneration == attempt + } + + /// Whether a poll failure observed at `generation` should be recorded. + /// Revocation always counts while active; transport errors are dropped if + /// another connect started, one is in flight, or the connection is already + /// revoked. + func acceptsPollError(sinceConnect generation: Int, isRevocation: Bool) -> Bool { + if isRevocation { return !isRevoked } + return !isRevoked && connectionGeneration == generation && !isConnectInFlight + } + + // MARK: - Pure transitions + + /// Starts a new connect attempt when custody is `.active`. Returns nil once + /// revoked because terminal custody never reconnects. + mutating func beginConnect(over route: AidenHostConnection.ConnectRoute) -> BeginConnectResult? { + guard !isRevoked else { return nil } + connectionGeneration &+= 1 + let attempt = connectionGeneration + if connectionState != .connecting { + settledState = SettledState(connectionState: connectionState, connectionIssue: connectionIssue) + } + connectionState = .connecting + connectionIssue = nil + attemptState = .inFlight(attempt: attempt, route: route) + return BeginConnectResult(attempt: attempt, notifyWillConnect: route == .interactive) + } + + /// Marks the active attempt as connected while preserving `attemptState` so + /// post-connect capability negotiation stays fenced to the same attempt. + @discardableResult + mutating func markConnected(attempt: Int) -> Bool { + guard isCurrent(attempt: attempt) else { return false } + connectionIssue = nil + connectionState = .connected + return true + } + + /// Clears `attemptState` when `attempt`'s task exits, without disturbing a + /// newer superseding attempt. + mutating func finishConnect(attempt: Int) { + if case .inFlight(let current, _) = attemptState, current == attempt { + attemptState = .idle + } + } + + /// Stops the attempt in flight (optionally filtered to `route`) and puts + /// the machine back where it stood before it. Only `connectionGeneration` + /// moves, so every live context stays live. + @discardableResult + mutating func cancelConnect(over route: AidenHostConnection.ConnectRoute? = nil) -> CancelConnectResult? { + guard isConnectInFlight, case .inFlight(let currentAttempt, let currentRoute) = attemptState else { + return nil + } + if let route, currentRoute != route { return nil } + attemptState = .idle + connectionGeneration &+= 1 + if connectionState == .connecting, let settledState { + connectionState = settledState.connectionState + connectionIssue = settledState.connectionIssue + } + return CancelConnectResult(cancelledAttempt: currentAttempt, route: currentRoute) + } + + /// Expires a still-connecting attempt whose deadline elapsed. Returns false + /// if the connection is revoked, superseded, or has already settled. + @discardableResult + mutating func expireConnect(attempt: Int) -> Bool { + guard isCurrent(attempt: attempt), connectionState == .connecting else { return false } + connectionGeneration &+= 1 + attemptState = .idle + return true + } + + /// Records a non-revocation failure. A structured server error on an + /// already-settled connection leaves it `.connected`; any other failure + /// takes it `.offline`. No-op once revoked. + @discardableResult + mutating func recordNonRevocationFailure( + isServerError: Bool, + issue: @autoclosure () -> AidenConnectionIssue + ) -> Bool { + guard !isRevoked else { return false } + if isServerError, connectionState != .connecting { + connectionIssue = nil + connectionState = .connected + } else { + let resolved = issue() + connectionIssue = resolved + connectionState = .offline(message: resolved.message) + } + return true + } + + /// Ends this connection's lease: contexts and answers from before this call + /// go stale. Custody stays terminal if already revoked. + mutating func disconnect() { + generation &+= 1 + hostGeneration &+= 1 + connectionGeneration &+= 1 + attemptState = .idle + settledState = nil + connectionIssue = nil + connectionState = isRevoked ? .needsPairing : .connecting + } + + /// Adopts an externally provided connection state. Revoked connections only + /// accept `.needsPairing`. Returns true when `.needsPairing` is adopted so + /// the owner can notify `hostConnectionNeedsPairing`. + @discardableResult + mutating func adopt(connectionState: AidenRemoteConnectionState) -> Bool { + if isRevoked, connectionState != .needsPairing { return false } + self.connectionState = connectionState + settledState = nil + return connectionState == .needsPairing + } + + mutating func adopt(connectionIssue: AidenConnectionIssue?) { + self.connectionIssue = connectionIssue + } + + mutating func advanceGeneration() { + generation &+= 1 + } + + mutating func advanceHostGeneration() { + hostGeneration &+= 1 + } + + mutating func advanceConnectionGeneration() { + connectionGeneration &+= 1 + } + + /// Terminal custody transition: once revoked, the connection never issues a + /// context or client and never connects again. Preserves `purgePending` if + /// already set. + mutating func markRevoked() { + custody = .revoked(purgePending: isPurgePending) + hostGeneration &+= 1 + connectionGeneration &+= 1 + attemptState = .idle + settledState = nil + } + + /// Terminal custody transition with cached data held until on-screen views + /// leave. Stops at `.needsPairing` and returns true so the owner notifies + /// `hostConnectionNeedsPairing`. + @discardableResult + mutating func markRevokedWithPurgePending() -> Bool { + custody = .revoked(purgePending: true) + hostGeneration &+= 1 + connectionGeneration &+= 1 + attemptState = .idle + settledState = nil + connectionIssue = nil + connectionState = .needsPairing + return true + } + + /// Clears `purgePending` once purge starts without changing whether the + /// connection is revoked. + mutating func purgeStarted() { + if case .revoked = custody { + custody = .revoked(purgePending: false) + } + } + + /// Standalone revocation (no delegate): revokes, ends the lease, and stops + /// at `.needsPairing`. + mutating func revokeStandalone() { + markRevoked() + disconnect() + } +} diff --git a/ios/AidenOnTheGoTests/AidenChatMutationSubMachinesTests.swift b/ios/AidenOnTheGoTests/AidenChatMutationSubMachinesTests.swift new file mode 100644 index 0000000000..c5fd497dc7 --- /dev/null +++ b/ios/AidenOnTheGoTests/AidenChatMutationSubMachinesTests.swift @@ -0,0 +1,320 @@ +import Foundation +import XCTest +@testable import AidenOnTheGo + +@MainActor +final class AidenChatMutationSubMachinesTests: XCTestCase { + private let contextA = AidenRemoteRequestContext( + instanceId: "inst-1", + deviceId: "dev-1", + generation: 1, + hostGeneration: 1, + scope: .owner + ) + + private let contextB = AidenRemoteRequestContext( + instanceId: "inst-1", + deviceId: "dev-2", + generation: 2, + hostGeneration: 2, + scope: .owner + ) + + private func serverError(_ status: Int, code: String) throws -> AidenRemoteClientError { + let body = try AidenRemoteJSONDecoder.decode( + AidenRemoteErrorEnvelope.Body.self, + from: Data(#"{"code":"\#(code)","message":"Refused.","requestId":"req-1","retryable":false}"#.utf8) + ) + return .server(statusCode: status, body: body) + } + + private func sampleChat(workspaceId: String = "ws-new", revision: String = "rev-2") -> AidenChat { + AidenChat( + id: "chat-1", + workspaceId: workspaceId, + title: "New chat", + providerId: nil, + modelId: nil, + messages: [], + createdAt: Date(timeIntervalSince1970: 1_000), + updatedAt: Date(timeIntervalSince1970: 1_000), + revision: revision + ) + } + + // MARK: - Worktree Setup Sub-Machine + + func testWorktreeSetupKeyReuseAndDefinitiveSpending() throws { + let machine = AidenWorktreeSetupMachine() + let firstKey = UUID() + let secondKey = UUID() + + let attempt1 = machine.begin(for: "Build feature", makeKey: { firstKey }) + XCTAssertEqual(attempt1.idempotencyKey, firstKey) + XCTAssertTrue(machine.isSettingUp) + + // Ambiguous transport error retains key for identical text retry. + machine.recordFailure(URLError(.timedOut)) + machine.endPhase() + XCTAssertFalse(machine.isSettingUp) + XCTAssertEqual(machine.retainedAttempt?.idempotencyKey, firstKey) + + let retry = machine.begin(for: "Build feature", makeKey: { secondKey }) + XCTAssertEqual(retry.idempotencyKey, firstKey) + + // 409 idempotency_in_flight also retains key. + machine.recordFailure(try serverError(409, code: "idempotency_in_flight")) + machine.endPhase() + XCTAssertEqual(machine.retainedAttempt?.idempotencyKey, firstKey) + + // Definitive server refusal spends the key. + machine.recordFailure(try serverError(409, code: "revision_conflict")) + XCTAssertNil(machine.retainedAttempt) + + let fresh = machine.begin(for: "Build feature", makeKey: { secondKey }) + XCTAssertEqual(fresh.idempotencyKey, secondKey) + } + + func testWorktreeSetupCancelAfterFinishGuardAdoptsWorktreeThenThrowsCancellation() async throws { + let machine = AidenWorktreeSetupMachine() + let movedChat = sampleChat(workspaceId: "ws-worktree", revision: "rev-wt") + let movedResult = AidenChatNewWorktree(chat: movedChat, branch: "aiden/build-feature") + + var adoptedWorkspaceId: String? + + // Simulate Cancel pressed right as the Mac returns its moved worktree, + // after `setup` already finished (so `setup.isCancelled` is false). + do { + _ = try await machine.execute( + text: "Build feature", + operation: { _ in movedResult }, + onMoved: { moved in + // Press cancel while adopting the already-finished result. + machine.cancel() + XCTAssertTrue(machine.isCanceled) + adoptedWorkspaceId = moved.chat.workspaceId + return true + } + ) + XCTFail("Expected CancellationError from cancel-after-finish guard") + } catch is CancellationError { + XCTAssertEqual(adoptedWorkspaceId, "ws-worktree", "Worktree must still be adopted") + XCTAssertFalse(machine.isSettingUp) + XCTAssertNil(machine.retainedAttempt, "Moved worktree spends the attempt key") + } + } + + // MARK: - Fork & Continue-in-New-Chat Sub-Machines + + func testForkAttemptRetainsKeyOnAmbiguousFailureAndClearsOnSuccessOrRefusal() throws { + var machine = AidenChatForkAttemptMachine() + let request = AidenChatForkAttempt.Request( + chatId: "chat-1", + revision: "rev-1", + messageId: "msg-2", + position: .after, + summaryFocus: nil + ) + let key1 = UUID() + let key2 = UUID() + + let first = machine.begin(context: contextA, request: request, makeKey: { key1 }) + XCTAssertEqual(first.idempotencyKey, key1) + + // Cancellation and transport errors keep the key. + machine.recordFailure(CancellationError(), for: first) + XCTAssertEqual(machine.retained?.idempotencyKey, key1) + + machine.recordFailure(URLError(.networkConnectionLost), for: first) + XCTAssertEqual(machine.retained?.idempotencyKey, key1) + + // 409 idempotency_in_flight keeps the key. + machine.recordFailure(try serverError(409, code: "idempotency_in_flight"), for: first) + XCTAssertEqual(machine.retained?.idempotencyKey, key1) + + // Re-attempt with same context + request reuses key1. + let retry = machine.begin(context: contextA, request: request, makeKey: { key2 }) + XCTAssertEqual(retry.idempotencyKey, key1) + + // Different context mints a new key. + let otherContext = machine.begin(context: contextB, request: request, makeKey: { key2 }) + XCTAssertEqual(otherContext.idempotencyKey, key2) + + // Definitive server refusal clears retained key. + machine.recordFailure(try serverError(409, code: "revision_conflict"), for: otherContext) + XCTAssertNil(machine.retained) + + // Success clears retained key. + let third = machine.begin(context: contextA, request: request, makeKey: { key1 }) + machine.recordSuccess(third) + XCTAssertNil(machine.retained) + } + + func testContinueInNewChatAttemptRetainsKeyOnAmbiguousFailureAndClearsOnDefinitiveRefusal() throws { + var machine = AidenContinueInNewChatAttemptMachine() + let key1 = UUID() + let key2 = UUID() + + let first = machine.begin( + context: contextA, + chatId: "chat-1", + revision: "rev-1", + workspaceId: "ws-2", + makeKey: { key1 } + ) + XCTAssertEqual(first.idempotencyKey, key1) + + machine.recordFailure(URLError(.timedOut), for: first) + XCTAssertEqual(machine.retained?.idempotencyKey, key1) + + let sameTarget = machine.begin( + context: contextA, + chatId: "chat-1", + revision: "rev-1", + workspaceId: "ws-2", + makeKey: { key2 } + ) + XCTAssertEqual(sameTarget.idempotencyKey, key1) + + // Different destination workspace mints a fresh key. + let differentTarget = machine.begin( + context: contextA, + chatId: "chat-1", + revision: "rev-1", + workspaceId: "ws-3", + makeKey: { key2 } + ) + XCTAssertEqual(differentTarget.idempotencyKey, key2) + + machine.recordFailure(try serverError(404, code: "not_found"), for: differentTarget) + XCTAssertNil(machine.retained) + } + + // MARK: - Approval & Question Snapshot Generation Fences + + func testApprovalSnapshotFenceCoalescesIdenticalFallbackAndRejectsStaleGenerations() { + var fence = AidenApprovalSnapshotFence() + + let first = fence.begin( + streamID: "stream-1", + context: contextA, + pendingApproval: nil, + streamState: .running, + isFallback: false, + isInFlightContextLive: false + ) + XCTAssertNotNil(first) + XCTAssertEqual(first?.generation, 1) + + // Fallback read with identical stream/live context/approval/state coalesces. + let coalesced = fence.begin( + streamID: "stream-1", + context: contextA, + pendingApproval: nil, + streamState: .running, + isFallback: true, + isInFlightContextLive: true + ) + XCTAssertNil(coalesced) + + // Non-fallback read advances generation and supersedes `first`. + let second = fence.begin( + streamID: "stream-1", + context: contextA, + pendingApproval: nil, + streamState: .running, + isFallback: false, + isInFlightContextLive: true + ) + XCTAssertEqual(second?.generation, 2) + + XCTAssertFalse(fence.accepts( + first!, + activeStreamID: "stream-1", + pendingApproval: nil, + streamState: .running, + isRemoved: false, + isContextLive: true + )) + XCTAssertTrue(fence.accepts( + second!, + activeStreamID: "stream-1", + pendingApproval: nil, + streamState: .running, + isRemoved: false, + isContextLive: true + )) + + // Finishing `first` must not clear `second`'s in-flight token. + fence.finish(first!) + XCTAssertEqual(fence.inFlight, second) + + // State mutation, stream change, removal, or dead context rejects `second`. + XCTAssertFalse(fence.accepts( + second!, + activeStreamID: "stream-1", + pendingApproval: nil, + streamState: .done, + isRemoved: false, + isContextLive: true + )) + XCTAssertFalse(fence.accepts( + second!, + activeStreamID: "stream-2", + pendingApproval: nil, + streamState: .running, + isRemoved: false, + isContextLive: true + )) + XCTAssertFalse(fence.accepts( + second!, + activeStreamID: "stream-1", + pendingApproval: nil, + streamState: .running, + isRemoved: true, + isContextLive: true + )) + + fence.finish(second!) + XCTAssertNil(fence.inFlight) + } + + func testQuestionSnapshotFenceAdvancesMonotonicallyAndRejectsSupersededReads() { + var fence = AidenQuestionSnapshotFence() + let q1 = AidenPendingQuestion(id: "q-1", questions: [], expiresAt: .distantFuture, canRespond: true) + + let first = fence.begin(streamID: "stream-1", pendingQuestion: nil, streamState: .waitingForApproval) + let second = fence.begin(streamID: "stream-1", pendingQuestion: nil, streamState: .waitingForApproval) + XCTAssertEqual(first.generation, 1) + XCTAssertEqual(second.generation, 2) + + XCTAssertFalse(fence.accepts( + first, + activeStreamID: "stream-1", + pendingQuestion: nil, + streamState: .waitingForApproval, + isContextLive: true + )) + XCTAssertTrue(fence.accepts( + second, + activeStreamID: "stream-1", + pendingQuestion: nil, + streamState: .waitingForApproval, + isContextLive: true + )) + XCTAssertFalse(fence.accepts( + second, + activeStreamID: "stream-1", + pendingQuestion: q1, + streamState: .waitingForApproval, + isContextLive: true + )) + XCTAssertFalse(fence.accepts( + second, + activeStreamID: "stream-1", + pendingQuestion: nil, + streamState: .waitingForApproval, + isContextLive: false + )) + } +} diff --git a/ios/AidenOnTheGoTests/AidenForeignRunObserverTests.swift b/ios/AidenOnTheGoTests/AidenForeignRunObserverTests.swift new file mode 100644 index 0000000000..c0974923d1 --- /dev/null +++ b/ios/AidenOnTheGoTests/AidenForeignRunObserverTests.swift @@ -0,0 +1,304 @@ +import Foundation +import XCTest +@testable import AidenOnTheGo + +@MainActor +final class AidenForeignRunObserverTests: XCTestCase { + private let sampleContext = AidenRemoteRequestContext( + instanceId: "inst-1", + deviceId: "dev-1", + generation: 1, + hostGeneration: 1, + scope: .owner + ) + + private func decodeEvent(_ json: String) throws -> AidenRemoteRunEvent { + try AidenRemoteJSONDecoder.decode(AidenRemoteRunEvent.self, from: Data(json.utf8)) + } + + private func startedEvent(runId: String, sequence: Int = 1) throws -> AidenRemoteRunEvent { + try decodeEvent(""" + {"protocolVersion":1,"streamId":"\(runId)","sequence":\(sequence),"timestamp":"2026-11-24T00:00:00Z","type":"run.started","terminal":false,"payload":{"runId":"\(runId)","chatId":"chat-1","origin":"desktop"}} + """) + } + + private func textDeltaEvent(runId: String, sequence: Int, text: String) throws -> AidenRemoteRunEvent { + try decodeEvent(""" + {"protocolVersion":1,"streamId":"\(runId)","sequence":\(sequence),"timestamp":"2026-11-24T00:00:01Z","type":"text_delta","terminal":false,"payload":{"text":"\(text)"}} + """) + } + + private func endedEvent(runId: String, sequence: Int, state: String = "done") throws -> AidenRemoteRunEvent { + try decodeEvent(""" + {"protocolVersion":1,"streamId":"\(runId)","sequence":\(sequence),"timestamp":"2026-11-24T00:00:02Z","type":"run.ended","terminal":true,"payload":{"runId":"\(runId)","chatId":"chat-1","state":"\(state)"}} + """) + } + + private func serverError(_ status: Int, code: String) throws -> AidenRemoteClientError { + let body = try AidenRemoteJSONDecoder.decode( + AidenRemoteErrorEnvelope.Body.self, + from: Data(#"{"code":"\#(code)","message":"Refused.","requestId":"req-1","retryable":false}"#.utf8) + ) + return .server(statusCode: status, body: body) + } + + private func makeHost( + isRemoved: @escaping @MainActor () -> Bool = { false }, + isContextLive: @escaping @MainActor (AidenRemoteRequestContext) -> Bool = { _ in true }, + hasActiveStream: @escaping @MainActor () -> Bool = { false }, + isStarting: @escaping @MainActor () -> Bool = { false }, + openEventStream: @escaping @MainActor (AidenRemoteRequestContext, AidenForeignRunProjection?) throws -> AsyncThrowingStream, + handleCredentialRevocation: @escaping @MainActor (Error, AidenRemoteRequestContext) async -> Bool = { _, _ in false }, + reconcileChat: @escaping @MainActor (AidenRemoteRequestContext) async -> Bool = { _ in true }, + onGoLive: @escaping @MainActor (AidenForeignRunProjection, AidenRemoteRequestContext) async -> Void = { _, _ in }, + onPublishUpdate: @escaping @MainActor (AidenForeignRunProjection, Bool, AidenRemoteRequestContext) -> Void = { _, _, _ in }, + onPerformEffect: @escaping @MainActor (AidenForeignRunProjection.Effect, String, AidenRemoteRequestContext) async -> Bool = { effect, _, _ in + if case .ended = effect { return true } + return false + }, + onReconnectExhaustedLive: @escaping @MainActor (String, AidenRemoteRequestContext) async -> Void = { _, _ in }, + onFlushBeforeQuietEnd: @escaping @MainActor () -> Void = {}, + onEndedQuietlyLive: @escaping @MainActor (AidenRemoteRunEndState?, Bool) -> Void = { _, _ in }, + onClearLiveOutput: @escaping @MainActor () -> Void = {}, + onClearLiveOutputAndPrompts: @escaping @MainActor () -> Void = {}, + onObservationFinished: @escaping @MainActor () -> Void = {} + ) -> AidenForeignRunObserver.Host { + AidenForeignRunObserver.Host( + currencyInputs: { context in + AidenForeignRunObserver.CurrencyInputs( + isTaskCancelled: Task.isCancelled, + isRemoved: isRemoved(), + isContextLive: isContextLive(context), + hasActiveStream: hasActiveStream(), + isStarting: isStarting() + ) + }, + isRemoved: isRemoved, + hasActiveStream: hasActiveStream, + openEventStream: openEventStream, + handleCredentialRevocation: handleCredentialRevocation, + reconcileChat: reconcileChat, + bumpTranscriptGeneration: {}, + onGoLive: onGoLive, + onPublishUpdate: onPublishUpdate, + onPerformEffect: onPerformEffect, + onReconnectExhaustedLive: onReconnectExhaustedLive, + onFlushBeforeQuietEnd: onFlushBeforeQuietEnd, + onEndedQuietlyLive: onEndedQuietlyLive, + onClearLiveOutput: onClearLiveOutput, + onClearLiveOutputAndPrompts: onClearLiveOutputAndPrompts, + onObservationFinished: onObservationFinished + ) + } + + func testSixConditionCurrencyFenceRejectsEachViolationIndependently() { + let observer = AidenForeignRunObserver() + let currentGen = observer.generation + + let baseline = AidenForeignRunObserver.CurrencyInputs( + isTaskCancelled: false, + isRemoved: false, + isContextLive: true, + hasActiveStream: false, + isStarting: false + ) + XCTAssertTrue(observer.isCurrent(generation: currentGen, inputs: baseline)) + XCTAssertFalse(observer.isRecoveryFenced(inputs: baseline)) + + // 1. Wrong generation + XCTAssertFalse(observer.isCurrent(generation: currentGen &+ 1, inputs: baseline)) + // 2. Task cancelled + XCTAssertFalse(observer.isCurrent(generation: currentGen, inputs: .init( + isTaskCancelled: true, isRemoved: false, isContextLive: true, hasActiveStream: false, isStarting: false + ))) + // 3. Chat removed + XCTAssertFalse(observer.isCurrent(generation: currentGen, inputs: .init( + isTaskCancelled: false, isRemoved: true, isContextLive: true, hasActiveStream: false, isStarting: false + ))) + // 4. Context not live + XCTAssertFalse(observer.isCurrent(generation: currentGen, inputs: .init( + isTaskCancelled: false, isRemoved: false, isContextLive: false, hasActiveStream: false, isStarting: false + ))) + // 5. Active owned stream + XCTAssertFalse(observer.isCurrent(generation: currentGen, inputs: .init( + isTaskCancelled: false, isRemoved: false, isContextLive: true, hasActiveStream: true, isStarting: false + ))) + // 6. Starting a local send + XCTAssertFalse(observer.isCurrent(generation: currentGen, inputs: .init( + isTaskCancelled: false, isRemoved: false, isContextLive: true, hasActiveStream: false, isStarting: true + ))) + + // Recovery fence trips on active stream, starting, removed, cancelled, or dead context. + XCTAssertTrue(observer.isRecoveryFenced(inputs: .init( + isTaskCancelled: false, isRemoved: false, isContextLive: true, hasActiveStream: true, isStarting: false + ))) + XCTAssertTrue(observer.isRecoveryFenced(inputs: .init( + isTaskCancelled: false, isRemoved: false, isContextLive: true, hasActiveStream: false, isStarting: true + ))) + } + + func testProbeBackoffFollows5s10s20s30sCapAndResetsWhenBusyOrLive() { + let delays = (0..<6).map { AidenForeignRunObserver.probeDelay(afterIdleProbes: $0) } + XCTAssertEqual(delays, [.seconds(5), .seconds(10), .seconds(20), .seconds(30), .seconds(30), .seconds(30)]) + XCTAssertEqual(AidenForeignRunObserver.probeDelay(afterIdleProbes: -3), .seconds(5)) + } + + func testAttachPromotesToLiveAfterSettleAndEndsQuietlyOnTerminalEvent() async throws { + let observer = AidenForeignRunObserver() + observer.settleSleep = { _ in } + observer.reconnectSleep = { _ in } + + let started = try startedEvent(runId: "run-live") + let delta = try textDeltaEvent(runId: "run-live", sequence: 2, text: "Hello from Mac") + let ended = try endedEvent(runId: "run-live", sequence: 3, state: "done") + + var wentLiveRunId: String? + var publishedTexts: [String] = [] + var reconcileCount = 0 + var endedStates: [AidenRemoteRunEndState?] = [] + var finishedCalls = 0 + var streamContinuation: AsyncThrowingStream.Continuation? + + let host = makeHost( + openEventStream: { _, _ in + AsyncThrowingStream { continuation in + streamContinuation = continuation + continuation.yield(started) + } + }, + reconcileChat: { _ in + reconcileCount += 1 + return true + }, + onGoLive: { projection, _ in + wentLiveRunId = projection.runId + }, + onPublishUpdate: { projection, _, _ in + publishedTexts.append(projection.liveText) + }, + onEndedQuietlyLive: { endState, _ in + endedStates.append(endState) + }, + onObservationFinished: { + finishedCalls += 1 + } + ) + + let task = try XCTUnwrap(observer.startObservation(context: sampleContext, reason: .load, host: host)) + let deadline = ContinuousClock.now + .seconds(5) + while !observer.isLive, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + XCTAssertTrue(observer.isLive) + XCTAssertEqual(wentLiveRunId, "run-live") + XCTAssertEqual(observer.shownLiveCount, 1) + XCTAssertEqual(observer.accountedRunId, "run-live") + + streamContinuation?.yield(delta) + streamContinuation?.yield(ended) + streamContinuation?.finish() + await task.value + + XCTAssertFalse(observer.isLive) + XCTAssertFalse(observer.isLookingForRun) + XCTAssertNil(observer.projection) + XCTAssertEqual(publishedTexts.last, "Hello from Mac") + XCTAssertEqual(reconcileCount, 1) + XCTAssertEqual(endedStates, [.done]) + XCTAssertEqual(finishedCalls, 1) + } + + func testAnnouncedTurnRetriesOnceOn404ThenReconcilesChat() async throws { + let observer = AidenForeignRunObserver() + observer.announcedRunRetrySleep = { _ in } + observer.reconnectSleep = { _ in } + let notFound = try serverError(404, code: "run_gone") + + var openCount = 0 + var reconcileCount = 0 + let host = makeHost( + openEventStream: { _, _ in + openCount += 1 + return AsyncThrowingStream { continuation in + continuation.finish(throwing: notFound) + } + }, + reconcileChat: { _ in + reconcileCount += 1 + return true + } + ) + + let task = try XCTUnwrap(observer.startObservation(context: sampleContext, reason: .announcedTurn, host: host)) + await task.value + + XCTAssertEqual(openCount, 2, "Announced turn should retry 404 exactly once") + XCTAssertEqual(reconcileCount, 1, "Unobservable announced run should still reconcile chat") + XCTAssertFalse(observer.isLookingForRun) + } + + func testEndedBeforeAttachSkipsLiveAndReconcilesOnlyForNewRun() async throws { + let observer = AidenForeignRunObserver() + // Keep settleSleep pending so the replay ends before settling. + observer.settleSleep = { _ in try await Task.sleep(for: .seconds(60)) } + + let started = try startedEvent(runId: "run-old") + let ended = try endedEvent(runId: "run-old", sequence: 2, state: "done") + + var wentLive = false + var reconcileCount = 0 + let host = makeHost( + openEventStream: { _, _ in + AsyncThrowingStream { continuation in + continuation.yield(started) + continuation.yield(ended) + continuation.finish() + } + }, + reconcileChat: { _ in + reconcileCount += 1 + return true + }, + onGoLive: { _, _ in wentLive = true } + ) + + let first = try XCTUnwrap(observer.startObservation(context: sampleContext, reason: .load, host: host)) + await first.value + + XCTAssertFalse(wentLive) + XCTAssertEqual(reconcileCount, 1) + XCTAssertEqual(observer.accountedRunId, "run-old") + + // Seeing the same accounted run again does not trigger another reconcile. + let second = try XCTUnwrap(observer.startObservation(context: sampleContext, reason: .load, host: host)) + await second.value + + XCTAssertEqual(reconcileCount, 1) + } + + func testStopProbeCancelsUnsettledProbeLookupAndPreservesAnnouncedTurnPrecedence() async throws { + let observer = AidenForeignRunObserver() + observer.queueAnnouncedTurn(reason: .firstRosterTurn) + observer.queueAnnouncedTurn(reason: .announcedTurn) + observer.queueAnnouncedTurn(reason: .firstRosterTurn) + XCTAssertEqual(observer.consumeQueuedAnnouncedTurn(), .announcedTurn) + XCTAssertNil(observer.consumeQueuedAnnouncedTurn()) + + var streamContinuation: AsyncThrowingStream.Continuation? + let host = makeHost( + openEventStream: { _, _ in + AsyncThrowingStream { continuation in + streamContinuation = continuation + } + } + ) + let attach = try XCTUnwrap(observer.startObservation(context: sampleContext, reason: .probe, host: host)) + XCTAssertTrue(observer.isLookingForRun) + XCTAssertTrue(observer.lookupIsProbes) + + observer.stopProbe(hasActiveStream: false, onClearLiveOutputAndPrompts: {}) + XCTAssertFalse(observer.isLookingForRun) + streamContinuation?.finish() + await attach.value + } +} diff --git a/ios/AidenOnTheGoTests/AidenHostConnectionTests.swift b/ios/AidenOnTheGoTests/AidenHostConnectionTests.swift index 6b15a82624..1dc695dead 100644 --- a/ios/AidenOnTheGoTests/AidenHostConnectionTests.swift +++ b/ios/AidenOnTheGoTests/AidenHostConnectionTests.swift @@ -1,7 +1,8 @@ -#if DEBUG import XCTest @testable import AidenOnTheGo +#if DEBUG + @MainActor final class AidenHostConnectionTests: XCTestCase { private let revokedJSON = Data(""" @@ -265,5 +266,211 @@ final class AidenHostConnectionTests: XCTestCase { XCTAssertTrue(coordinator.workspaces.isEmpty) XCTAssertThrowsError(try coordinator.requestContext()) } + + func testExpireAfterRevokeLeavesConnectionAtNeedsPairing() async throws { + let responder = AidenDemoResponder() + _ = AidenDemoHosts.coordinator(.one, responder: responder) + let connection = standalone("studio", responder: responder) + let releaseServer = responder.hold(instanceId: "studio", path: "/server") + var deadlinePassed = false + connection.waitForDeadline = { _ in + while !deadlinePassed, !Task.isCancelled { + try? await Task.sleep(nanoseconds: 1_000_000) + } + } + + let attempt = Task { await connection.connect(over: .probe, timeout: 10) } + try await waitForRequest("GET /server", instanceId: "studio", responder: responder) + XCTAssertTrue(connection.isConnectInFlight) + + connection.markRevokedWithPurgePending() + XCTAssertTrue(connection.isRevoked) + XCTAssertTrue(connection.isPurgePending) + XCTAssertFalse(connection.isConnectInFlight) + XCTAssertEqual(connection.connectionState, .needsPairing) + + deadlinePassed = true + releaseServer() + await attempt.value + + XCTAssertTrue(connection.isRevoked) + XCTAssertTrue(connection.isPurgePending) + XCTAssertEqual(connection.connectionState, .needsPairing) + XCTAssertNil(connection.connectionIssue) + XCTAssertNil(connection.server) + } } #endif + +final class AidenHostConnectionLifecycleTests: XCTestCase { + private let sampleIssue = AidenConnectionIssue( + title: "Computer unavailable", + message: "Offline.", + canRetry: true + ) + + func testRevokeDuringConnectInvalidatesInFlightAttemptAndBlocksReconnect() { + var lifecycle = AidenHostConnectionLifecycle( + generation: 2, + hostGeneration: 3, + connectionGeneration: 4, + connectionState: .connected + ) + + let started = lifecycle.beginConnect(over: .interactive) + XCTAssertEqual(started, .init(attempt: 5, notifyWillConnect: true)) + XCTAssertTrue(lifecycle.isConnectInFlight) + XCTAssertTrue(lifecycle.isKnownOnline) + XCTAssertTrue(lifecycle.isCurrent(attempt: 5)) + + lifecycle.markRevoked() + + XCTAssertEqual(lifecycle.custody, .revoked(purgePending: false)) + XCTAssertTrue(lifecycle.isRevoked) + XCTAssertFalse(lifecycle.isPurgePending) + XCTAssertFalse(lifecycle.isConnectInFlight) + XCTAssertFalse(lifecycle.isCurrent(attempt: 5)) + XCTAssertEqual(lifecycle.hostGeneration, 4) + XCTAssertEqual(lifecycle.connectionGeneration, 6) + XCTAssertFalse(lifecycle.markConnected(attempt: 5)) + XCTAssertNil(lifecycle.beginConnect(over: .interactive)) + XCTAssertNil(lifecycle.beginConnect(over: .probe)) + } + + func testExpireAfterRevokeIsNoOpAndPreservesNeedsPairing() { + var lifecycle = AidenHostConnectionLifecycle() + let started = lifecycle.beginConnect(over: .probe) + XCTAssertEqual(started, .init(attempt: 1, notifyWillConnect: false)) + + let notifyNeedsPairing = lifecycle.markRevokedWithPurgePending() + XCTAssertTrue(notifyNeedsPairing) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + let generationAfterRevoke = lifecycle.connectionGeneration + + XCTAssertFalse(lifecycle.expireConnect(attempt: 1)) + XCTAssertFalse(lifecycle.recordNonRevocationFailure(isServerError: false, issue: sampleIssue)) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + XCTAssertNil(lifecycle.connectionIssue) + XCTAssertEqual(lifecycle.connectionGeneration, generationAfterRevoke) + XCTAssertFalse(lifecycle.acceptsPollError(sinceConnect: generationAfterRevoke, isRevocation: false)) + XCTAssertFalse(lifecycle.acceptsPollError(sinceConnect: generationAfterRevoke, isRevocation: true)) + } + + func testBackgroundRevokeWithPurgePendingTransitionsCleanlyThroughPurgeStarted() { + var lifecycle = AidenHostConnectionLifecycle(connectionState: .connected) + + // Active host ignores purgeStarted without changing custody. + lifecycle.purgeStarted() + XCTAssertEqual(lifecycle.custody, .active) + + XCTAssertTrue(lifecycle.markRevokedWithPurgePending()) + XCTAssertEqual(lifecycle.custody, .revoked(purgePending: true)) + XCTAssertTrue(lifecycle.isRevoked) + XCTAssertTrue(lifecycle.isPurgePending) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + XCTAssertNil(lifecycle.connectionIssue) + XCTAssertFalse(lifecycle.isKnownOnline) + XCTAssertFalse(lifecycle.isKnownOffline) + + // Subsequent markRevoked preserves pending purge until purgeStarted runs. + let hostGenBefore = lifecycle.hostGeneration + lifecycle.markRevoked() + XCTAssertEqual(lifecycle.custody, .revoked(purgePending: true)) + XCTAssertGreaterThan(lifecycle.hostGeneration, hostGenBefore) + + // Revoked host refuses non-pairing state adoptions. + XCTAssertFalse(lifecycle.adopt(connectionState: .connected)) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + XCTAssertTrue(lifecycle.adopt(connectionState: .needsPairing)) + + // Starting purge clears purgePending while keeping terminal revocation. + lifecycle.purgeStarted() + XCTAssertEqual(lifecycle.custody, .revoked(purgePending: false)) + XCTAssertTrue(lifecycle.isRevoked) + XCTAssertFalse(lifecycle.isPurgePending) + + // Disconnecting a revoked host keeps it at .needsPairing. + lifecycle.disconnect() + XCTAssertTrue(lifecycle.isRevoked) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + } + + func testGenerationMonotonicityAcrossConnectCancelExpireDisconnectAndRevoke() { + var lifecycle = AidenHostConnectionLifecycle( + generation: 10, + hostGeneration: 20, + connectionGeneration: 30 + ) + + var lastGen = lifecycle.generation + var lastHost = lifecycle.hostGeneration + var lastConn = lifecycle.connectionGeneration + + func assertMonotonic(file: StaticString = #filePath, line: UInt = #line) { + XCTAssertGreaterThanOrEqual(lifecycle.generation, lastGen, file: file, line: line) + XCTAssertGreaterThanOrEqual(lifecycle.hostGeneration, lastHost, file: file, line: line) + XCTAssertGreaterThanOrEqual(lifecycle.connectionGeneration, lastConn, file: file, line: line) + lastGen = lifecycle.generation + lastHost = lifecycle.hostGeneration + lastConn = lifecycle.connectionGeneration + } + + let first = lifecycle.beginConnect(over: .probe) + XCTAssertEqual(first?.attempt, 31) + assertMonotonic() + + // Route-filtered cancel for interactive does not cancel an in-flight probe. + XCTAssertNil(lifecycle.cancelConnect(over: .interactive)) + XCTAssertTrue(lifecycle.isConnectInFlight) + assertMonotonic() + + let cancelled = lifecycle.cancelConnect(over: .probe) + XCTAssertEqual(cancelled, .init(cancelledAttempt: 31, route: .probe)) + XCTAssertGreaterThan(lifecycle.connectionGeneration, lastConn) + assertMonotonic() + + let second = lifecycle.beginConnect(over: .interactive) + XCTAssertEqual(second?.attempt, 33) + assertMonotonic() + + XCTAssertTrue(lifecycle.expireConnect(attempt: 33)) + XCTAssertGreaterThan(lifecycle.connectionGeneration, lastConn) + assertMonotonic() + + XCTAssertTrue(lifecycle.recordNonRevocationFailure(isServerError: false, issue: sampleIssue)) + XCTAssertTrue(lifecycle.isKnownOffline) + assertMonotonic() + + // Reconnect from offline stays isKnownOffline and restores offline on cancel. + let third = lifecycle.beginConnect(over: .probe) + XCTAssertEqual(third?.attempt, 35) + XCTAssertTrue(lifecycle.isKnownOffline) + XCTAssertNotNil(lifecycle.cancelConnect(over: .probe)) + XCTAssertEqual(lifecycle.connectionState, .offline(message: sampleIssue.message)) + XCTAssertEqual(lifecycle.connectionIssue, sampleIssue) + assertMonotonic() + + // Connecting and settling keeps .connected if cancelled during negotiation. + let fourth = lifecycle.beginConnect(over: .interactive) + XCTAssertEqual(fourth?.attempt, 37) + XCTAssertTrue(lifecycle.markConnected(attempt: 37)) + XCTAssertNotNil(lifecycle.cancelConnect(over: .interactive)) + XCTAssertEqual(lifecycle.connectionState, .connected) + assertMonotonic() + + lifecycle.disconnect() + XCTAssertGreaterThan(lifecycle.generation, lastGen) + XCTAssertGreaterThan(lifecycle.hostGeneration, lastHost) + XCTAssertGreaterThan(lifecycle.connectionGeneration, lastConn) + XCTAssertEqual(lifecycle.connectionState, .connecting) + assertMonotonic() + + lifecycle.revokeStandalone() + XCTAssertGreaterThan(lifecycle.generation, lastGen) + XCTAssertGreaterThan(lifecycle.hostGeneration, lastHost) + XCTAssertGreaterThan(lifecycle.connectionGeneration, lastConn) + XCTAssertTrue(lifecycle.isRevoked) + XCTAssertEqual(lifecycle.connectionState, .needsPairing) + assertMonotonic() + } +} diff --git a/ios/AidenOnTheGoTests/AidenPendingSendCoordinatorTests.swift b/ios/AidenOnTheGoTests/AidenPendingSendCoordinatorTests.swift new file mode 100644 index 0000000000..2eb3506af8 --- /dev/null +++ b/ios/AidenOnTheGoTests/AidenPendingSendCoordinatorTests.swift @@ -0,0 +1,228 @@ +import Foundation +import XCTest +@testable import AidenOnTheGo + +@MainActor +final class AidenPendingSendCoordinatorTests: XCTestCase { + @MainActor + private final class DelayRecorder { + var delays: [Duration] = [] + func append(_ delay: Duration) { delays.append(delay) } + } + + private func makeDraftStore() -> AidenChatDraftStore { + let root = FileManager.default.temporaryDirectory + .appending(path: "aiden-pending-send-tests-\(UUID().uuidString)", directoryHint: .isDirectory) + return AidenChatDraftStore(root: root, excludeFromBackup: { _ in }) + } + + private func rateLimitError(retryAfterSeconds: Int? = nil) throws -> AidenRemoteClientError { + let details = retryAfterSeconds.map { #","details":{"retryAfterSeconds":\#($0)}"# } ?? "" + let json = #"{"code":"rate_limited","message":"Busy.","requestId":"req-429","retryable":true\#(details)}"# + let body = try AidenRemoteJSONDecoder.decode(AidenRemoteErrorEnvelope.Body.self, from: Data(json.utf8)) + return .server(statusCode: 429, body: body) + } + + func testNineTermCanRetryPredicateGuardsEveryCondition() async throws { + let store = makeDraftStore() + let coordinator = AidenPendingSendCoordinator(draftStore: store) + let session = await store.beginSession(instanceId: "inst-1", chatId: "chat-1") + let now = Date(timeIntervalSince1970: 100_000) + + let baseline = AidenPendingSendCoordinator.RetryEligibilityInputs( + isConnected: true, + isOwnerLive: true, + isStarting: false, + isSubmittingRunInput: false, + isRestoringStream: false, + hasActiveStream: false, + isStreaming: false + ) + + // 1. No pendingSend -> false + XCTAssertFalse(coordinator.canRetry(inputs: baseline, now: now)) + + let attempt = coordinator.makeTurnAttempt( + deviceId: "dev-1", + request: AidenTurnStart(text: "Hello"), + attachments: [], + now: now + ) + try await coordinator.persistBeforeSend(attempt, session: session) + coordinator.adoptPersistedAttempt(attempt) + + XCTAssertTrue(coordinator.canRetry(inputs: baseline, now: now)) + + // 2. Expired retry window (>= 24h) -> false + XCTAssertFalse(coordinator.canRetry(inputs: baseline, now: now.addingTimeInterval(24 * 60 * 60))) + // 3. Disconnected -> false + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: false, isOwnerLive: true, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: false, isStreaming: false + ), now: now)) + // 4. Owner not live -> false + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: false, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: false, isStreaming: false + ), now: now)) + // 5. Starting -> false + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: true, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: false, isStreaming: false + ), now: now)) + // 6. Submitting run input -> false + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: false, isSubmittingRunInput: true, + isRestoringStream: false, hasActiveStream: false, isStreaming: false + ), now: now)) + // 7. Restoring stream -> false + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: true, hasActiveStream: false, isStreaming: false + ), now: now)) + // 8. Active stream blocks a fresh turn retry + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: true, isStreaming: false + ), now: now)) + // 9. Streaming blocks a fresh turn retry + XCTAssertFalse(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: false, isStreaming: true + ), now: now)) + + // Run-input pending send (streamId != nil) IS retryable while streaming/activeStream. + try await coordinator.discard(session: session) + let runInputAttempt = AidenChatDraftStore.PendingSend( + deviceId: "dev-1", + request: AidenTurnStart(text: "Steer"), + key: UUID(), + createdAt: now, + attachments: [], + streamId: "stream-1", + inputMode: .steer + ) + try await coordinator.persistBeforeSend(runInputAttempt, session: session) + coordinator.adoptPersistedAttempt(runInputAttempt) + XCTAssertTrue(coordinator.canRetry(inputs: .init( + isConnected: true, isOwnerLive: true, isStarting: false, isSubmittingRunInput: false, + isRestoringStream: false, hasActiveStream: true, isStreaming: true + ), now: now)) + } + + func testScheduleRateLimitedSendRetryEnforcesMaxBudgetOfThreeAndRotatesKeys() async throws { + let store = makeDraftStore() + let coordinator = AidenPendingSendCoordinator(draftStore: store) + let session = await store.beginSession(instanceId: "inst-1", chatId: "chat-1") + let error = try rateLimitError(retryAfterSeconds: 2) + + let recorder = DelayRecorder() + coordinator.rateLimitedSendRetrySleep = { delay in + await recorder.append(delay) + } + + let initial = coordinator.makeTurnAttempt( + deviceId: "dev-1", + request: AidenTurnStart(text: "Hello"), + attachments: [] + ) + try await coordinator.persistBeforeSend(initial, session: session) + coordinator.adoptPersistedAttempt(initial) + + var current = initial + var seenKeys: Set = [initial.key] + var automaticTriggers = 0 + + for expectedRetryNumber in 1...AidenPendingSendCoordinator.maxRateLimitedSendRetries { + let triggered = expectation(description: "automatic retry \(expectedRetryNumber)") + let scheduled = await coordinator.scheduleRateLimitedSendRetry( + replacing: current, + error: error, + session: session, + isContextLive: { true }, + onRetry: { + automaticTriggers += 1 + triggered.fulfill() + } + ) + XCTAssertTrue(scheduled) + XCTAssertTrue(coordinator.isWaitingToRetryRateLimitedSend) + XCTAssertFalse(coordinator.isPendingSendRefusedBecauseBusy) + let fresh = try XCTUnwrap(coordinator.pendingSend) + XCTAssertTrue(seenKeys.insert(fresh.key).inserted, "Each 429 retry must rotate to a fresh Idempotency-Key") + current = fresh + + await fulfillment(of: [triggered], timeout: 2) + XCTAssertFalse(coordinator.isWaitingToRetryRateLimitedSend) + } + + XCTAssertEqual(automaticTriggers, AidenPendingSendCoordinator.maxRateLimitedSendRetries) + XCTAssertEqual(recorder.delays, [.seconds(2), .seconds(2), .seconds(2)]) + + // 4th 429 exhausts automatic retries and leaves Retry to the user. + var fourthTriggered = false + let fourthScheduled = await coordinator.scheduleRateLimitedSendRetry( + replacing: current, + error: error, + session: session, + isContextLive: { true }, + onRetry: { fourthTriggered = true } + ) + XCTAssertTrue(fourthScheduled) + XCTAssertFalse(coordinator.isWaitingToRetryRateLimitedSend) + XCTAssertTrue(coordinator.isPendingSendRefusedBecauseBusy) + XCTAssertFalse(fourthTriggered) + XCTAssertEqual( + coordinator.recoveryMessage(isStarting: false, isSubmittingRunInput: false), + "Aiden Agent is still busy. Your message wasn’t sent; try again in a moment." + ) + + // Manual retry clears busy state and resets the retry budget. + coordinator.cancelAutomaticRetryForManualAction() + XCTAssertFalse(coordinator.isPendingSendRefusedBecauseBusy) + XCTAssertEqual(coordinator.rateLimitedSendRetries, 0) + XCTAssertEqual( + coordinator.recoveryMessage(isStarting: false, isSubmittingRunInput: false), + "Couldn’t confirm delivery. Retry uses the same saved request within its safe retry window." + ) + } + + func testScheduleRateLimitedSendRetryStopsAutomaticallyWhenContextNotLiveOrStoreWriteFails() async throws { + let store = makeDraftStore() + let coordinator = AidenPendingSendCoordinator(draftStore: store) + let session = await store.beginSession(instanceId: "inst-1", chatId: "chat-1") + let error = try rateLimitError() + + let attempt = coordinator.makeTurnAttempt( + deviceId: "dev-1", + request: AidenTurnStart(text: "Hello"), + attachments: [] + ) + try await coordinator.persistBeforeSend(attempt, session: session) + coordinator.adoptPersistedAttempt(attempt) + + // Dead context keeps the rotated pending send on disk but does not schedule automatic resend. + let scheduledDead = await coordinator.scheduleRateLimitedSendRetry( + replacing: attempt, + error: error, + session: session, + isContextLive: { false }, + onRetry: { XCTFail("Dead context must not fire automatic retry") } + ) + XCTAssertTrue(scheduledDead) + XCTAssertFalse(coordinator.isWaitingToRetryRateLimitedSend) + XCTAssertTrue(coordinator.isPendingSendRefusedBecauseBusy) + + // Invalidated draft session causes savePendingSend to throw CancellationError -> returns false. + _ = await store.beginSession(instanceId: "inst-1", chatId: "chat-1") + let current = try XCTUnwrap(coordinator.pendingSend) + let scheduledStaleSession = await coordinator.scheduleRateLimitedSendRetry( + replacing: current, + error: error, + session: session, + isContextLive: { true }, + onRetry: { XCTFail("Failed store write must not schedule retry") } + ) + XCTAssertFalse(scheduledStaleSession) + } +} diff --git a/ios/AidenOnTheGoTests/ComposerVoiceInputControllerTests.swift b/ios/AidenOnTheGoTests/ComposerVoiceInputControllerTests.swift new file mode 100644 index 0000000000..43ce443a9d --- /dev/null +++ b/ios/AidenOnTheGoTests/ComposerVoiceInputControllerTests.swift @@ -0,0 +1,519 @@ +import AVFoundation +import Foundation +import Speech +import XCTest +@testable import AidenOnTheGo + +@MainActor +final class ComposerVoiceInputControllerTests: XCTestCase { + private final class MockAudioSessionDriver: ComposerVoiceAudioSessionDriver { + var metrics = ComposerVoiceAudioSessionInputMetrics( + isInputAvailable: true, + sampleRate: 48_000, + inputNumberOfChannels: 1 + ) + var activateError: Error? + private(set) var activateCount = 0 + private(set) var deactivateCount = 0 + private(set) var isActive = false + + func activateForRecording() throws -> ComposerVoiceAudioSessionInputMetrics { + if let activateError { throw activateError } + activateCount += 1 + isActive = true + return metrics + } + + func deactivateAfterRecording() { + deactivateCount += 1 + isActive = false + } + } + + private final class MockNativeRecognitionRequest: ComposerVoiceNativeRecognitionRequest, @unchecked Sendable { + private let lock = NSLock() + private var ended = false + + var didEndAudio: Bool { + lock.withLock { ended } + } + + func append(_ buffer: AVAudioPCMBuffer) {} + + func endAudio() { + lock.withLock { ended = true } + } + } + + private final class MockNativeRecognitionTask: ComposerVoiceNativeRecognitionTask { + private(set) var cancelCount = 0 + + func cancel() { + cancelCount += 1 + } + } + + private final class MockAudioEngineHandle: ComposerVoiceAudioEngineHandle { + var isRunning = false + var inputSampleRate: Double = 48_000 + var inputChannelCount: UInt32 = 1 + var startError: Error? + var simulatedMacPCMBuffer: AVAudioPCMBuffer? + + private(set) var tapInstallCount = 0 + private(set) var tapRemoveCount = 0 + private(set) var stopAndResetCount = 0 + private(set) var isTapInstalled = false + + func installMacTap(into accumulator: ComposerMacSpeechPCMAccumulator) { + tapInstallCount += 1 + isTapInstalled = true + if let buffer = simulatedMacPCMBuffer { + accumulator.append(buffer) + } + } + + func installNativeTap(forwardingTo request: any ComposerVoiceNativeRecognitionRequest) { + tapInstallCount += 1 + isTapInstalled = true + } + + func prepareAndStart() throws { + if let startError { throw startError } + isRunning = true + } + + func stopAndReset(removeTap: Bool) { + stopAndResetCount += 1 + isRunning = false + if removeTap { + tapRemoveCount += 1 + isTapInstalled = false + } + } + } + + private final class MockNativeSpeechDriver: ComposerVoiceNativeSpeechDriver { + var onDeviceSupported = true + private(set) var lastRequest: MockNativeRecognitionRequest? + private(set) var lastTask: MockNativeRecognitionTask? + private var onUpdate: (@MainActor (ComposerVoiceRecognitionUpdate) -> Void)? + + func prepareOnDeviceRecognizer(for locale: Locale) -> Bool { + onDeviceSupported + } + + func makeRequest() -> any ComposerVoiceNativeRecognitionRequest { + let request = MockNativeRecognitionRequest() + lastRequest = request + return request + } + + func startRecognition( + request: any ComposerVoiceNativeRecognitionRequest, + onUpdate: @escaping @MainActor (ComposerVoiceRecognitionUpdate) -> Void + ) -> (any ComposerVoiceNativeRecognitionTask)? { + self.onUpdate = onUpdate + let task = MockNativeRecognitionTask() + lastTask = task + return task + } + + func emit(_ update: ComposerVoiceRecognitionUpdate) { + onUpdate?(update) + } + } + + @MainActor + private struct Harness { + let controller: ComposerVoiceInputController + let audioSession: MockAudioSessionDriver + let engine: MockAudioEngineHandle + let nativeSpeech: MockNativeSpeechDriver + var capturingHistory: [Bool] { getCapturingHistory() } + var isCapturing: Bool { getCapturingHistory().last ?? false } + private let getCapturingHistory: @MainActor () -> [Bool] + + init( + mode: AidenVoiceInputMode = .onDevice, + isAppActive: Bool = true, + micGranted: Bool = true, + speechStatus: SFSpeechRecognizerAuthorizationStatus = .authorized, + requestMic: (@MainActor () async -> Bool)? = nil, + requestSpeech: (@MainActor () async -> SFSpeechRecognizerAuthorizationStatus)? = nil, + finalizationSleep: @escaping @Sendable (Duration) async throws -> Void = { _ in } + ) { + let audioSession = MockAudioSessionDriver() + let engine = MockAudioEngineHandle() + let nativeSpeech = MockNativeSpeechDriver() + var history: [Bool] = [] + let dependencies = ComposerVoiceInputController.Dependencies( + selectedMode: { mode }, + isAppActive: { isAppActive }, + requestMicrophonePermission: requestMic ?? { micGranted }, + requestSpeechAuthorization: requestSpeech ?? { speechStatus }, + audioSession: audioSession, + audioEngineFactory: { engine }, + nativeSpeech: nativeSpeech, + makeMacAccumulator: { ComposerMacSpeechPCMAccumulator() }, + finalizationSleep: finalizationSleep, + setCapturing: { history.append($0) } + ) + self.controller = ComposerVoiceInputController(dependencies: dependencies) + self.audioSession = audioSession + self.engine = engine + self.nativeSpeech = nativeSpeech + self.getCapturingHistory = { history } + } + } + + private func makeNonEmptyPCMBuffer() throws -> AVAudioPCMBuffer { + let format = try XCTUnwrap(AVAudioFormat( + commonFormat: .pcmFormatFloat32, + sampleRate: 16_000, + channels: 1, + interleaved: false + )) + let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4)) + buffer.frameLength = 4 + let channel = try XCTUnwrap(buffer.floatChannelData?[0]) + channel[0] = 0.25 + channel[1] = -0.25 + channel[2] = 0.5 + channel[3] = -0.5 + return buffer + } + + // MARK: - Pure Reducer Invariants + + func testReducerGuaranteesFullResourceCleanupOnEveryExitToIdle() throws { + var reducer = ComposerVoiceInputReducer() + XCTAssertEqual(reducer.state, .idle) + XCTAssertTrue(reducer.resources.isClean) + + // Start native session and acquire all capture resources. + let begun = try XCTUnwrap(reducer.beginSession(backend: .nativeOnDevice)) + XCTAssertEqual(reducer.state, .requestingPermission) + XCTAssertEqual(reducer.backend, .nativeOnDevice) + reducer.didActivateAudioSession() + reducer.didAttachAudioEngine() + reducer.didInstallAudioTap() + reducer.didCreateRecognitionRequest() + reducer.didStartRecognitionTask() + let listeningEffects = try XCTUnwrap(reducer.didStartListening(session: begun.session)) + XCTAssertEqual(listeningEffects, [.setCapturing(true)]) + XCTAssertEqual(reducer.state, .listening) + + // Failure mid-listening must tear down tap, audio session, recognition, and capturing. + let failEffects = try XCTUnwrap(reducer.fail( + session: begun.session, + message: "Boom", + logCategory: .audioStartup + )) + XCTAssertEqual(reducer.state, .idle) + XCTAssertEqual(reducer.backend, .none) + XCTAssertTrue(reducer.resources.isClean) + XCTAssertTrue(failEffects.contains(.setCapturing(false))) + XCTAssertTrue(failEffects.contains(.teardownAudioCapture(removeTap: true, deactivateAudioSession: true))) + XCTAssertTrue(failEffects.contains(.releaseRecognition(cancelTask: true))) + XCTAssertTrue(failEffects.contains(.stopAcceptingDraftUpdates)) + XCTAssertTrue(failEffects.contains(.setErrorMessage("Boom"))) + } + + func testReducerSuppressesExpectedErrorAfterNativeStopKeepingTranscript() throws { + var reducer = ComposerVoiceInputReducer() + let begun = try XCTUnwrap(reducer.beginSession(backend: .nativeOnDevice)) + reducer.didActivateAudioSession() + reducer.didAttachAudioEngine() + reducer.didInstallAudioTap() + reducer.didCreateRecognitionRequest() + reducer.didStartRecognitionTask() + _ = reducer.didStartListening(session: begun.session) + + guard case let .finalizeNative(session, stopEffects) = reducer.stopKeepingTranscript() else { + return XCTFail("Expected finalizeNative") + } + XCTAssertEqual(session, begun.session) + XCTAssertEqual(reducer.state, .transcribing) + XCTAssertTrue(reducer.suppressNextRecognitionError) + XCTAssertTrue(stopEffects.contains(.teardownAudioCapture(removeTap: true, deactivateAudioSession: true))) + XCTAssertTrue(stopEffects.contains(.endRecognitionAudio)) + XCTAssertTrue(stopEffects.contains(.scheduleNativeFinalizationTimeout(session: begun.session))) + + // Recognition error after stopKeepingTranscript is suppressed, and finalization task is cancelled. + let termEffects = try XCTUnwrap(reducer.nativeRecognitionTerminated( + session: begun.session, + errorDescription: "Cancelled by endAudio" + )) + XCTAssertEqual(reducer.state, .idle) + XCTAssertTrue(reducer.resources.isClean) + XCTAssertFalse(reducer.suppressNextRecognitionError) + XCTAssertTrue(termEffects.contains(.cancelNativeFinalizationTask)) + XCTAssertTrue(termEffects.contains(.releaseRecognition(cancelTask: false))) + XCTAssertFalse(termEffects.contains { + if case .setErrorMessage = $0 { return true } + return false + }) + } + + // MARK: - Native On-Device Controller Flows + + func testNativeDictationStreamsPartialAndFinalTranscriptAndCleansUpResources() async { + let harness = Harness(mode: .onDevice) + var drafts: [String] = [] + + await harness.controller.toggle( + currentDraft: "Hello", + updateDraft: { drafts.append($0) }, + macTranscriber: { _ in XCTFail("On-device mode must not call macTranscriber"); return "" } + ) + + XCTAssertEqual(harness.controller.state, .listening) + XCTAssertTrue(harness.controller.isListening) + XCTAssertTrue(harness.audioSession.isActive) + XCTAssertTrue(harness.engine.isTapInstalled) + XCTAssertTrue(harness.isCapturing) + + harness.nativeSpeech.emit(.init(transcript: "world", isFinal: false, errorDescription: nil)) + XCTAssertEqual(harness.controller.liveTranscript, "world") + XCTAssertEqual(drafts, ["Hello world"]) + + harness.nativeSpeech.emit(.init(transcript: "world!", isFinal: true, errorDescription: nil)) + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertFalse(harness.controller.isBusy) + XCTAssertNil(harness.controller.errorMessage) + XCTAssertEqual(drafts, ["Hello world", "Hello world!"]) + XCTAssertFalse(harness.audioSession.isActive) + XCTAssertEqual(harness.audioSession.deactivateCount, 1) + XCTAssertFalse(harness.engine.isTapInstalled) + XCTAssertEqual(harness.engine.tapRemoveCount, 1) + XCTAssertFalse(harness.isCapturing) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + } + + func testNativeStopKeepingTranscriptFinalizesViaTimeoutWhenRecognizerNeverCompletes() async throws { + let harness = Harness( + mode: .onDevice, + finalizationSleep: { _ in } + ) + var drafts: [String] = [] + + await harness.controller.toggle( + currentDraft: "", + updateDraft: { drafts.append($0) }, + macTranscriber: { _ in "" } + ) + XCTAssertEqual(harness.controller.state, .listening) + + harness.nativeSpeech.emit(.init(transcript: "Draft text", isFinal: false, errorDescription: nil)) + // Toggling while listening invokes stopKeepingTranscript(). + await harness.controller.toggle( + currentDraft: "Draft text", + updateDraft: { drafts.append($0) }, + macTranscriber: { _ in "" } + ) + + // Audio capture stops immediately before timeout finishes. + XCTAssertFalse(harness.audioSession.isActive) + XCTAssertFalse(harness.engine.isTapInstalled) + XCTAssertTrue(harness.nativeSpeech.lastRequest?.didEndAudio == true) + + let deadline = ContinuousClock.now + .seconds(2) + while harness.controller.state != .idle, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertEqual(harness.nativeSpeech.lastTask?.cancelCount, 1) + XCTAssertNil(harness.controller.errorMessage) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + + // Late recognition callback after timeout must not mutate draft. + harness.nativeSpeech.emit(.init(transcript: "Late text", isFinal: true, errorDescription: nil)) + XCTAssertEqual(drafts, ["Draft text"]) + } + + func testNativeEngineStartFailureCleansUpTapAndAudioSessionOnExitToIdle() async { + let harness = Harness(mode: .onDevice) + harness.engine.startError = NSError( + domain: "TestAudio", + code: 42, + userInfo: [NSLocalizedDescriptionKey: "Engine failed to start."] + ) + + await harness.controller.toggle( + currentDraft: "", + updateDraft: { _ in XCTFail("Failed start must not update draft") }, + macTranscriber: { _ in "" } + ) + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertEqual(harness.controller.errorMessage, "Engine failed to start.") + XCTAssertEqual(harness.engine.tapInstallCount, 1) + XCTAssertEqual(harness.engine.tapRemoveCount, 1) + XCTAssertFalse(harness.engine.isTapInstalled) + XCTAssertEqual(harness.audioSession.activateCount, 1) + XCTAssertEqual(harness.audioSession.deactivateCount, 1) + XCTAssertFalse(harness.audioSession.isActive) + XCTAssertEqual(harness.nativeSpeech.lastTask?.cancelCount, 1) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + } + + func testNativePermissionAndPreflightFailuresReturnToIdleWithoutActivatingAudio() async { + let deniedSpeech = Harness(mode: .onDevice, speechStatus: .denied) + await deniedSpeech.controller.toggle(currentDraft: "", updateDraft: { _ in }, macTranscriber: { _ in "" }) + XCTAssertEqual(deniedSpeech.controller.state, .idle) + XCTAssertNotNil(deniedSpeech.controller.errorMessage) + XCTAssertEqual(deniedSpeech.audioSession.activateCount, 0) + XCTAssertTrue(deniedSpeech.controller.reducer.resources.isClean) + + let inactiveApp = Harness(mode: .onDevice, isAppActive: false) + await inactiveApp.controller.toggle(currentDraft: "", updateDraft: { _ in }, macTranscriber: { _ in "" }) + XCTAssertEqual(inactiveApp.controller.state, .idle) + XCTAssertEqual(inactiveApp.controller.errorMessage, ComposerVoiceInputError.appNotActive.localizedDescription) + XCTAssertEqual(inactiveApp.audioSession.activateCount, 0) + XCTAssertTrue(inactiveApp.controller.reducer.resources.isClean) + } + + // MARK: - Paired Mac Controller Flows + + func testPairedMacDictationCapturesAudioStopsSessionBeforeTranscribingAndUpdatesDraft() async throws { + let harness = Harness(mode: .pairedMac) + harness.engine.simulatedMacPCMBuffer = try makeNonEmptyPCMBuffer() + + var drafts: [String] = [] + var receivedPCMBytes = 0 + var sessionWasInactiveDuringTranscription = false + + await harness.controller.toggle( + currentDraft: "Note:", + updateDraft: { drafts.append($0) }, + macTranscriber: { pcm in + receivedPCMBytes = pcm.count + sessionWasInactiveDuringTranscription = !harness.audioSession.isActive && !harness.engine.isTapInstalled + return "ship it" + } + ) + + XCTAssertEqual(harness.controller.state, .listening) + XCTAssertTrue(harness.audioSession.isActive) + XCTAssertTrue(harness.engine.isTapInstalled) + XCTAssertTrue(harness.isCapturing) + + harness.controller.stopKeepingTranscript() + + let deadline = ContinuousClock.now + .seconds(2) + while harness.controller.state != .idle, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertGreaterThan(receivedPCMBytes, 0) + XCTAssertTrue(sessionWasInactiveDuringTranscription, "Audio session and tap must be torn down before remote transcription") + XCTAssertEqual(drafts, ["Note: ship it"]) + XCTAssertEqual(harness.controller.liveTranscript, "ship it") + XCTAssertNil(harness.controller.errorMessage) + XCTAssertFalse(harness.isCapturing) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + } + + func testPairedMacEmptyRecordingFailsCleanlyAndLeavesIdle() async { + let harness = Harness(mode: .pairedMac) + harness.engine.simulatedMacPCMBuffer = nil + + await harness.controller.toggle( + currentDraft: "", + updateDraft: { _ in XCTFail("Empty recording must not update draft") }, + macTranscriber: { _ in XCTFail("Empty recording must not call macTranscriber"); return "" } + ) + XCTAssertEqual(harness.controller.state, .listening) + + harness.controller.stopKeepingTranscript() + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertEqual(harness.controller.errorMessage, "No speech was recorded.") + XCTAssertFalse(harness.audioSession.isActive) + XCTAssertFalse(harness.engine.isTapInstalled) + XCTAssertFalse(harness.isCapturing) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + } + + func testCancelDiscardingRecordingDuringMacTranscriptionDropsLateResultAndCleansUp() async throws { + let harness = Harness(mode: .pairedMac) + harness.engine.simulatedMacPCMBuffer = try makeNonEmptyPCMBuffer() + + var drafts: [String] = [] + var transcriptionStarted = false + var releaseTranscription = false + + await harness.controller.toggle( + currentDraft: "Keep", + updateDraft: { drafts.append($0) }, + macTranscriber: { _ in + transcriptionStarted = true + while !releaseTranscription, !Task.isCancelled { + try? await Task.sleep(for: .milliseconds(5)) + } + return "discarded transcript" + } + ) + XCTAssertEqual(harness.controller.state, .listening) + + harness.controller.stopKeepingTranscript() + let deadline = ContinuousClock.now + .seconds(2) + while !transcriptionStarted, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + XCTAssertEqual(harness.controller.state, .transcribing) + + harness.controller.cancelDiscardingRecording() + releaseTranscription = true + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertFalse(harness.controller.isBusy) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + + // Allow any cancelled task unwinding to settle. + try await Task.sleep(for: .milliseconds(25)) + XCTAssertTrue(drafts.isEmpty, "Cancelled transcription must not write to the draft") + XCTAssertNil(harness.controller.errorMessage) + } + + func testCancelDuringPermissionPromptPreventsStartingAudioCapture() async throws { + var releasePermission = false + var permissionEntered = false + let harness = Harness( + mode: .pairedMac, + requestMic: { + permissionEntered = true + while !releasePermission, !Task.isCancelled { + try? await Task.sleep(for: .milliseconds(5)) + } + return true + } + ) + + let startTask = Task { + await harness.controller.toggle( + currentDraft: "", + updateDraft: { _ in XCTFail("Cancelled permission flow must not update draft") }, + macTranscriber: { _ in "" } + ) + } + + let deadline = ContinuousClock.now + .seconds(2) + while !permissionEntered, ContinuousClock.now < deadline { + try await Task.sleep(for: .milliseconds(5)) + } + XCTAssertEqual(harness.controller.state, .requestingPermission) + + harness.controller.cancelDiscardingRecording() + releasePermission = true + await startTask.value + + XCTAssertEqual(harness.controller.state, .idle) + XCTAssertEqual(harness.audioSession.activateCount, 0) + XCTAssertEqual(harness.engine.tapInstallCount, 0) + XCTAssertTrue(harness.controller.reducer.resources.isClean) + } +} diff --git a/packages/cli/tests/server-visuals.test.mjs b/packages/cli/tests/server-visuals.test.mjs index e9c2a92fb7..1ab9d58238 100644 --- a/packages/cli/tests/server-visuals.test.mjs +++ b/packages/cli/tests/server-visuals.test.mjs @@ -173,6 +173,10 @@ test("an installed browser draws a chart offline into a picture and leaves no pr const dir = mkdtempSync(join(tmpdir(), "aiden-server-visuals-")); t.after(() => rmSync(dir, { recursive: true, force: true })); const previous = process.env.AIDEN_CLI_ENTRY; process.env.AIDEN_CLI_ENTRY = join(pkg, "dist/app/cli.js"); t.after(() => { if (previous === undefined) delete process.env.AIDEN_CLI_ENTRY; else process.env.AIDEN_CLI_ENTRY = previous; }); + // The first launch of Chrome on a fresh CI machine reads the browser from a + // cold disk and has taken 8-14 s to answer; later launches answer in under + // 200 ms. Draw once without the limit, so the limit below times the drawing. + await api.renderServerVisualImage({ browserPath: browser.path, hostPage: api.serverVisualHostPage("

Warm-up

", "Warm-up", 720, () => ""), width: 720, timeoutMs: 120_000 }); const profiles = () => readdirSync(tmpdir()).filter((name) => name.startsWith("aiden-visual-")).length; const before = profiles(); const visuals = api.createServerVisualCollector(); diff --git a/scripts/check-ios-shipping-target.test.mjs b/scripts/check-ios-shipping-target.test.mjs index b87e1f77d6..8745f05be3 100644 --- a/scripts/check-ios-shipping-target.test.mjs +++ b/scripts/check-ios-shipping-target.test.mjs @@ -102,6 +102,9 @@ const appSourcePaths = [ "AidenOnTheGo/Features/Chat/AidenChatViewModel+Recordings.swift", "AidenOnTheGo/Features/Chat/AidenChatViewModel+ComposerPower.swift", "AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift", + "AidenOnTheGo/Features/Chat/AidenForeignRunObserver.swift", + "AidenOnTheGo/Features/Chat/AidenPendingSendCoordinator.swift", + "AidenOnTheGo/Features/Chat/AidenChatMutationSubMachines.swift", "AidenOnTheGo/Features/Chat/AidenChatCards.swift", "AidenOnTheGo/Features/Chat/AidenTypedApprovalCard.swift", "AidenOnTheGo/Features/Chat/AidenChronologicalTranscript.swift", @@ -147,6 +150,7 @@ const appSourcePaths = [ "AidenOnTheGo/Features/Shell/AidenSearchTabView.swift", "AidenOnTheGo/Features/Shell/AidenWorkspacesTabView.swift", "AidenOnTheGo/Features/Remote/Hosts/AidenHostConnection.swift", + "AidenOnTheGo/Features/Remote/Hosts/AidenHostConnectionLifecycle.swift", "AidenOnTheGo/Features/Remote/Hosts/AidenHostRegistry.swift", "AidenOnTheGo/Features/Remote/AidenInboxViews.swift", "AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift", @@ -247,6 +251,9 @@ const chatFeatureSourcePaths = [ "AidenOnTheGo/Features/Conversation/AidenTranscriptScaffold.swift", "AidenOnTheGo/Features/Chat/AidenReadAloud.swift", "AidenOnTheGo/Features/Chat/AidenChatViewModel+ForeignRuns.swift", + "AidenOnTheGo/Features/Chat/AidenForeignRunObserver.swift", + "AidenOnTheGo/Features/Chat/AidenPendingSendCoordinator.swift", + "AidenOnTheGo/Features/Chat/AidenChatMutationSubMachines.swift", ]; async function readChatFeatureSources() { @@ -322,8 +329,12 @@ const testSources = [ "AidenBotWatchTests.swift", "AidenActivityMarkTests.swift", "AidenChatDockTests.swift", + "AidenChatMutationSubMachinesTests.swift", "AidenChatTests.swift", "AidenComposerSurfaceTests.swift", + "AidenForeignRunObserverTests.swift", + "AidenPendingSendCoordinatorTests.swift", + "ComposerVoiceInputControllerTests.swift", "AidenInboxTests.swift", "AidenNativeIntegrationTests.swift", "AidenHomeActionsTests.swift",