diff --git a/AGENTS.md b/AGENTS.md index db0da21a..9b0b26de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1180,6 +1180,10 @@ Helpful, never a pile to clear (`BighelpNotificationGrouping`): "Sending your message" row under the chat's own opaque ID): iOS starts a Live Activity only for an app in front, and a turn with a file starts once the file is up, often after the person left, so it got no card. A turn that starts later joins the card as an update and takes that row's place; a row no turn takes goes after two minutes. +- A card is the computer's to update (pushes, sealed detail) only once the phone has matched it to the computer's + turn (`BighelpManagedActivityBridge`, the plugin's `work` route). The phone asks as the turn starts, which is + before the plugin has seen the turn, so it asks again a few times (`snapshotRetryWaits`) while the turn runs. + Asked once, a card whose first answer named no work moved only while bighelp was open and never got detail. - The Live Activity uses the app's palette and real host phases, never a guessed percentage. Titles stay in the phone's App Group; only opaque row IDs and bounded status reach the push service. Stale rows say Paused. - The card's first chat shows its work (#960, `BighelpActivityHeroView`): the step in progress, the last steps, a diff --git a/Bighelp/Notifications/BighelpManagedNotificationFactory.swift b/Bighelp/Notifications/BighelpManagedNotificationFactory.swift index 77416d99..c8ab9982 100644 --- a/Bighelp/Notifications/BighelpManagedNotificationFactory.swift +++ b/Bighelp/Notifications/BighelpManagedNotificationFactory.swift @@ -222,13 +222,114 @@ enum BighelpManagedActivityBridge { return nil } } - private final class Binding { + @MainActor private final class Binding { var previous: Task? var ticket = UUID() var selections: [SelectionKey: Selection] = [:] + /// Turns still asking the computer which work they are (`snapshotRetryWaits`). + var retries: [SelectionKey: Task] = [:] + /// Each running turn's newest event, for the ask that takes its card later. + var latest: [SelectionKey: ChatActivityEvent] = [:] + + /// Runs `work` after everything queued before it, so the admitted stream keeps its order. + @discardableResult + func enqueue(_ work: @escaping @MainActor () async -> Void) -> Task { + let before = previous + let ticket = UUID(); self.ticket = ticket + let task = Task { @MainActor in + await before?.value + await work() + if self.ticket == ticket { self.previous = nil } + } + previous = task + return task + } + } + /// The chat, connection and registry a queued step was made for. Every step checks it after each wait. + private struct Scope { + let host: BighelpConfiguredHost + let chatID: String + let profile: String + let session: String + let epoch: String + let generation: UUID + + @MainActor func isCurrent(_ service: BighelpManagedNotificationService, _ client: DirectHermesConversationClient) -> Bool { + !Task.isCancelled && client.connected && client.profile == profile && client.storedID == session + && client.projection.epoch == epoch && service.registry.generation == generation + && service.ownsChat(host: host, client: client) + } + func key(_ localTurn: String) -> SelectionKey { + .init(profile: profile, session: session, epoch: epoch, localTurn: localTurn) + } + } + + /// How long to wait before each further ask about a turn the computer didn't know at its start. + /// The phone asks the moment a turn starts; the computer learns of the turn at its first model + /// request, once its memory and context are ready. That is usually a second or two later, and + /// longer for a chat that was idle. Most asks come early, while bighelp is likely still open. + static let snapshotRetryWaits: [Duration] = [.seconds(1), .seconds(2), .seconds(4), .seconds(8), + .seconds(15), .seconds(30), .seconds(60)] + + /// Asks the computer which work a turn is, and gives the turn's card to that work: at once, then + /// after each of `waits` while the turn runs and nothing has taken its card. + /// + /// The computer learns of a turn at its first model request, which comes after the first ask. + /// Asked only once, the card stayed this phone's for the whole turn: it got no update with bighelp + /// away, and no detail. The read runs beside the stream, never in it: the computer may hold its + /// answer for a turn that is starting, and the card's own updates must not wait behind that. + /// Taking the card runs in the stream's order. A waiting ask holds neither the chat nor its model. + private static func ask(_ scope: Scope, _ binding: Binding, service: BighelpManagedNotificationService, + chat: DirectHermesChat, turnID: String, waits: [Duration]) { + let key = scope.key(turnID) + binding.retries[key]?.cancel() + binding.retries[key] = Task { @MainActor [weak service, weak client = chat.client, weak model = chat.model] in + for wait in [.zero] + waits { + if wait > .zero { try? await Task.sleep(for: wait) } + guard !Task.isCancelled else { return } + // Done once the card went to the computer's turn, the turn is over, or notifications are off here. + guard let service, let client, case .local = binding.selections[key], + client.projection.running, client.projection.turnID == turnID, + (try? service.credentials(for: scope.host)) != nil else { break } + // A chat between connections waits for its next ask. + guard scope.isCurrent(service, client) else { continue } + let isCurrent: @MainActor () -> Bool = { [weak service, weak client] in + guard let service, let client else { return false } + return scope.isCurrent(service, client) + } + let snapshot: BighelpManagedWorkSnapshot + do { + // No answer at all: this chat's agent has no Live Activity setup to ask. + guard let answer = try await service.workSnapshot(host: scope.host, profile: scope.profile, + storedSessionID: scope.session, isCurrent: isCurrent) else { break } + snapshot = answer + } catch { continue } + // No work, or only the chat's last turn: the computer hasn't seen this one yet. + guard snapshot.work?.terminal == false else { continue } + await binding.enqueue { [weak service, weak client, weak model] in + guard let service, let client, let model, scope.isCurrent(service, client), + case .local = binding.selections[key], client.projection.turnID == turnID, + let event = binding.latest[key] else { return } + let chat = DirectHermesChat(id: scope.chatID, client: client, model: model) + do { + if try await service.activityRuntime?.promote(host: scope.host, chat: chat, + localTurn: turnID, snapshot: snapshot) != true { + try await service.activityRuntime?.receive(host: scope.host, chat: chat, event: event, + canonicalHostTurnID: snapshot.work?.turnId, workSnapshot: snapshot) + } + guard scope.isCurrent(service, client) else { return } + binding.selections[key] = .observed(snapshot) + } catch { + // Keep the admitted local row; a later ask must not guess a new host turn. + } + }.value + } + if !Task.isCancelled { binding.retries[key] = nil } + } } - static func bind(service: BighelpManagedNotificationService, host: BighelpConfiguredHost, chat: DirectHermesChat) { + static func bind(service: BighelpManagedNotificationService, host: BighelpConfiguredHost, chat: DirectHermesChat, + snapshotRetryWaits: [Duration] = BighelpManagedActivityBridge.snapshotRetryWaits) { // Serial task ownership preserves the admitted stream's callback order. // The callback owns neither its client nor its model; queued work checks // the exact captured session/epoch/registry generation after every await. @@ -241,63 +342,44 @@ enum BighelpManagedActivityBridge { chat.client.onAdmittedActivity = { [weak service, weak client = chat.client, weak model = chat.model] change, turn, failed in guard let service, let client, model != nil, !change.activities.isEmpty || change.terminal else { return } - let profile = client.profile; let session = client.storedID - let epoch = client.projection.epoch; let generation = service.registry.generation - let before = binding.previous - let ticket = UUID(); binding.ticket = ticket - binding.previous = Task { @MainActor [weak service, weak client, weak model] in - await before?.value - defer { if binding.ticket == ticket { binding.previous = nil } } - guard let service, let client, let model else { return } - @MainActor func isCurrent() -> Bool { - !Task.isCancelled && client.connected && client.profile == profile && client.storedID == session - && client.projection.epoch == epoch && service.registry.generation == generation - && service.ownsChat(host: host, client: client) - } - guard isCurrent() else { return } + let scope = Scope(host: host, chatID: chatID, profile: client.profile, session: client.storedID, + epoch: client.projection.epoch, generation: service.registry.generation) + binding.enqueue { [weak service, weak client, weak model] in + guard let service, let client, let model, scope.isCurrent(service, client) else { return } let currentChat = DirectHermesChat(id: chatID, client: client, model: model) for event in change.activities { - guard isCurrent() else { return } - let key = SelectionKey(profile: profile, session: session, epoch: epoch, localTurn: event.turnID) + guard scope.isCurrent(service, client) else { return } + let key = scope.key(event.turnID) if binding.selections[key] == nil, !event.lifecycle.isTerminal { - // A null/failed read is a LOCAL fallback for this segment, - // not permission to guess a turn or query again per token. + // The card starts as this phone's. `ask` gives it to the computer's turn once the + // computer names one; nothing here guesses a turn, and no event asks again. guard binding.selections.count < 512 else { continue } binding.selections[key] = .local + binding.latest[key] = event // Start while the confirmed live turn is foregrounded. // Token registration can wait for its exact host snapshot. try? await service.activityRuntime?.receive(host: host, chat: currentChat, event: event, canonicalHostTurnID: nil) - guard isCurrent() else { return } - if let snapshot = try? await service.workSnapshot(host: host, profile: profile, - storedSessionID: session, isCurrent: isCurrent) { - guard isCurrent() else { return } - if snapshot.work?.terminal == false, client.projection.turnID == event.turnID { - do { - if try await service.activityRuntime?.promote(host: host, chat: currentChat, - localTurn: event.turnID, snapshot: snapshot) != true { - try await service.activityRuntime?.receive(host: host, chat: currentChat, event: event, - canonicalHostTurnID: snapshot.work?.turnId, workSnapshot: snapshot) - } - guard isCurrent() else { return } - binding.selections[key] = .observed(snapshot) - } catch { - // Keep the admitted local row; retrying must not guess a new host turn. - } - } - } + guard scope.isCurrent(service, client) else { return } + ask(scope, binding, service: service, chat: currentChat, turnID: event.turnID, waits: snapshotRetryWaits) } - guard isCurrent(), let selection = binding.selections[key] else { continue } + guard scope.isCurrent(service, client), let selection = binding.selections[key] else { continue } + if !event.lifecycle.isTerminal { binding.latest[key] = event } let snapshot = selection.snapshot // Track the authoritative CURRENT work explicitly; no claim // that its ID equals the projection segment's synthetic ID. try? await service.activityRuntime?.receive(host: host, chat: currentChat, event: event, canonicalHostTurnID: snapshot?.work?.turnId, workSnapshot: snapshot) } - guard isCurrent() else { return } + guard scope.isCurrent(service, client) else { return } if change.terminal { - try? await service.activityRuntime?.finish(host: host, profile: profile, - storedSessionID: session, originalLocalTurnID: turn, + // The turn ended: nothing is left to ask the computer about. + for key in binding.selections.keys where key.localTurn == turn { + binding.retries.removeValue(forKey: key)?.cancel() + binding.latest[key] = nil + } + try? await service.activityRuntime?.finish(host: host, profile: scope.profile, + storedSessionID: scope.session, originalLocalTurnID: turn, outcome: failed ? .failed : .succeeded) } } diff --git a/BighelpTests/ManagedNotificationServiceTests.swift b/BighelpTests/ManagedNotificationServiceTests.swift index 515878f1..a0be8055 100644 --- a/BighelpTests/ManagedNotificationServiceTests.swift +++ b/BighelpTests/ManagedNotificationServiceTests.swift @@ -575,6 +575,47 @@ import UserNotifications await runtime.resetForAccountBoundary() } + /// The phone asks which work a turn is the moment the turn starts. The computer learns of the turn a + /// little later, at its first model request, so that first answer can name no work. Asked only once, + /// the card then stayed this phone's for the whole turn: no update with bighelp away, and no detail. + @Test(arguments: [1, Int.max]) + func aTurnTheComputerHadNotSeenYetIsAskedAboutAgain(knownAfterReads: Int) async throws { + let fixture = try Fixture() + defer { fixture.cleanup() } + _ = try await fixture.service.enroll(host: fixture.host, connection: fixture.connection, isCurrent: { true }) + let runtime = BighelpManagedNativeActivityRuntime(service: fixture.service, driver: NativeActivityDriver(), + environment: .sandbox, topic: "app.loopdy.mobile", now: { Date(timeIntervalSince1970: 1_800_000_100) }) + fixture.service.activityRuntime = runtime + let client = try DirectHermesConversationClient(rpc: UnenrolledChatRPC(), hostIdentity: fixture.host.principalIdentity, + profile: "default", runtimeID: "runtime", storedID: "saved", title: "Chat", epoch: "epoch", + drafts: .init(root: fixture.root.appending(path: "drafts"))) + defer { client.suspend() } + let model = ChatModel(conversationID: client.conversationID, client: client, initialItems: []) + client.model = model + fixture.hostAPI.runningWorkAfterReads = knownAfterReads + client.receive(.init(type: "message.start", sessionID: "runtime", payload: [:], sequence: 1)) + let waits: [Duration] = [.milliseconds(5), .milliseconds(5), .milliseconds(5)] + BighelpManagedActivityBridge.bind(service: fixture.service, host: fixture.host, + chat: DirectHermesChat(id: "saved", client: client, model: model), snapshotRetryWaits: waits) + let known = knownAfterReads < Int.max + func settled() -> Bool { + known ? fixture.ledger.activities.contains { $0.canonicalTurnID == "canonical-turn" && !$0.retired } + : fixture.hostAPI.workReads > waits.count + } + for _ in 0..<400 where !settled() { try await Task.sleep(for: .milliseconds(5)) } + try await Task.sleep(for: .milliseconds(40)) + if known { + #expect(fixture.ledger.activities.contains { $0.canonicalTurnID == "canonical-turn" && !$0.retired }, + "The card goes to the computer's turn once the computer knows it") + #expect(fixture.hostAPI.workReads == 2, "It stops asking once the turn is known") + } else { + #expect(fixture.hostAPI.workReads == 1 + waits.count, "It asks a few more times, then stops") + #expect(!fixture.ledger.activities.contains { $0.canonicalTurnID != nil }) + } + client.suspend() + await runtime.resetForAccountBoundary() + } + /// iOS starts a Live Activity only for an app in front, and a turn with a file starts once the file /// is up, often after the person left: that turn got no card. Armed at Send (T3 Code's playbook), the /// card exists, and the turn's row takes the armed row's place as an update. @@ -1620,6 +1661,9 @@ import UserNotifications var offline = false var holdWorkSnapshot = false var workContinuation: CheckedContinuation? + /// How many times the phone asked about a chat's work, and after how many the computer knows the turn. + var workReads = 0 + var runningWorkAfterReads: Int? var enrollRejection: DirectHostNotificationError? var removedGrants: [String] = [] /// The agent each client was made for (`?profile=`), in order. @@ -1631,7 +1675,16 @@ import UserNotifications guard isCurrent() else { throw DirectHermesError.secureStorageChanged } if offline { throw DirectHermesError.notConnected } if suffix.hasSuffix("/work"), method == "POST" { + workReads += 1 if holdWorkSnapshot { await withCheckedContinuation { workContinuation = $0 } } + // Like the plugin: it knows a turn from the turn's first model request on, not before. + if let after = runningWorkAfterReads, workReads > after, + let profile = body?["profile"]?.string, let session = body?["sessionId"]?.string { + return .object(["version": .integer(1), "grantId": .string(account.template.grantId), "work": .object([ + "profile": .string(profile), "sessionId": .string(session), "turnId": .string("canonical-turn"), + "phase": .string("thinking"), "activeSubagentCount": .integer(0), "terminal": .boolean(false), + "outcome": .null, "observedAt": .integer(Int(Date().timeIntervalSince1970))])]) + } return .object(["version": .integer(1), "grantId": .string(account.template.grantId), "work": .null]) } if method == "DELETE", suffix.hasPrefix("/enrollments/"), !suffix.dropFirst(13).contains("/") { diff --git a/docs/LIVE_ACTIVITY_GROUPS.md b/docs/LIVE_ACTIVITY_GROUPS.md index 9637e5bc..317d2a85 100644 --- a/docs/LIVE_ACTIVITY_GROUPS.md +++ b/docs/LIVE_ACTIVITY_GROUPS.md @@ -32,6 +32,8 @@ Text-only turns did not emit a reasoning/tool activity, so they never reached th Confirmed live turn starts now reach the notification bridge without adding a transcript row. The bridge starts locally before the snapshot request, and binding an already-running, connected chat admits that live state too. Failed starts retain a pending event for a later live opportunity. An authenticated snapshot can promote the exact captured row to canonical host ownership. Canonical status then comes from that host, not local message-segment endings. +A card gets updates with bighelp away, and its detail, only after the phone gives it to the computer's turn. The phone asks the computer which work a turn is (`POST …/work`) the moment the turn starts. Hermes sends that start before it prepares the turn, and the plugin learns of the turn at the turn's first model request, so the first answer can name no work or only the chat's last, finished turn. The phone asked once: such a card stayed its own for the whole turn, moved only while bighelp was open, and showed no detail. Now the phone asks again after 1, 2, 4, 8, 15, 30 and 60 seconds (`BighelpManagedActivityBridge.snapshotRetryWaits`) while that turn runs and nothing has taken its card. The read runs beside the card's own updates, and taking the card runs in their order. A plugin with the wait (`WORK_WAIT_SECONDS`) also holds its answer up to 8 seconds for running work to show, which helps app builds that ask once. + ActivityKit still controls whether a request may start. This change does not introduce remote push-to-start or promise that work first discovered while the app is suspended will create a card. A denied request is logged and remains retryable; stale content is shown honestly. ## Ownership and updates