fix(mobile): keep agent widgets updated in the background #14861
Closedjakeleventhal(GitHub profile, opens in a new tab)wants to merge 8 commits into
main fromrefs/pull/14861/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/mobile/src/features/agent-awareness/remoteRegistration.ts line 1388OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -1156,15 +1382,7 @@11561382 }),1157- }).pipe(1158- Effect.catch((error) =>1159- Effect.sync(() => {1160- logRegistrationError("live activity priming failed", error);1161- return null;1162- }),1163- ),1164- );1165- if (primed) {1166- logRegistrationDebug("live activity card primed", {1167- activeCount: aggregate.activeCount,1168- });1169- activities = [primed];1170- }1383+ }).pipe(Effect.orElseSucceed(() => null))1384+ : null;1385+ if (expectedDeviceGeneration !== deviceRegistrationGeneration || !relayTokenProvider) return;1386+1387+ // Home-screen widgets update independently of the Live Activity toggle.1388+ const snapshot = yield* refreshAgentActivityWidget();apps/mobile/src/features/agent-awareness/remoteRegistration.ts line 656OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -494,0 +636,21 @@636+ liveWidgetSubscription = appAtomRegistry.subscribe(637+ liveWidgetActivitiesAtom,638+ (activities) => {639+ const previousScope = [...observedWidgetActivities.keys()];640+ liveWidgetActivities = activities;641+ const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);642+ const observed = new Map(observedWidgetActivities);643+ for (const environmentId of observed.keys()) {644+ if (catalog.entries.get(environmentId)?.enabled !== true) {645+ observed.delete(environmentId);646+ widgetShellObservations.delete(environmentId);647+ widgetShellConfirmedAt.delete(environmentId);648+ }649+ }650+ for (const [environmentId, rows] of activities) {651+ const shell = appAtomRegistry.get(environmentShell.stateValueAtom(environmentId));652+ if (widgetShellObservations.get(environmentId) !== shell) {653+ widgetShellObservations.set(environmentId, shell);654+ // Coalesce streaming shell updates within a minute. Timer-driven655+ // atom recomputations alone cannot confirm an unchanged shell.656+ widgetShellConfirmedAt.set(environmentId, Math.floor(Date.now() / 60_000) * 60_000);
- apps/mobile/fingerprint.config.cjs lines 1 to 9OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,9 @@1+// These Swift sources are copied by a dangerous config mod, so Expo's config2+// loader cannot discover them. Include them in native-client and OTA compatibility.3+module.exports = {4+ extraSources: [5+ "plugins/withAgentWidgetRefresh.cjs",6+ "plugins/widget/AgentWidgetTimelineProvider.swift",7+ "plugins/widget/AgentWidgetState.swift",8+ ].map((filePath) => ({ type: "file", filePath, reasons: ["agentWidgetRefresh"] })),9+};apps/mobile/modules/t3-native-controls/ios/AgentWidgetCredential.swift lines 27 to 32OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +12,21 @@12+ kSecAttrAccount as String: "read-capability",13+ kSecAttrAccessGroup as String: group,14+ ]15+ }16+17+ static func read() -> String? {18+ guard var query else { return nil }19+ query[kSecReturnData as String] = true20+ query[kSecMatchLimit as String] = kSecMatchLimitOne21+ var result: CFTypeRef?22+ guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,23+ let data = result as? Data else { return nil }24+ return String(data: data, encoding: .utf8)25+ }26+27+ static func store(_ token: String) -> Bool {28+ guard var query else { return false }29+ query[kSecValueData as String] = Data(token.utf8)30+ query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly31+ return SecItemAdd(query as CFDictionary, nil) == errSecSuccess32+ }infra/relay/src/agentActivity/AgentWidgetRefresh.ts lines 210 to 238Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+ .set({ widgetPushToken: null })215+ .where(216+ and(217+ eq(relayMobileDevices.userId, device.userId),218+ eq(relayMobileDevices.deviceId, device.deviceId),219+ eq(relayMobileDevices.widgetPushToken, job.target.token),220+ ),221+ )222+ .pipe(persistenceError("invalidate-push-token"));223+ } else if (!result.ok) {224+ return yield* new ApnsClient.ApnsHttpRequestError({225+ requestKind: "push-notification",226+ event: null,227+ environment: device.apsEnvironment ?? config.apns.environment,228+ bundleId: device.bundleId ?? config.apns.bundleId,229+ tokenSuffix: job.target.token.slice(-8),230+ stage: "send",231+ status: result.status,232+ cause: result.reason,233+ });234+ }
- apps/mobile/src/features/agent-awareness/remoteRegistration.ts line 596OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -494,0 +576,21 @@576+577+function publishRegularWidget(props: AgentActivityProps): void {578+ // Streaming text changes shell timestamps without changing widget content.579+ const content = JSON.stringify({580+ activeCount: props.activeCount,581+ isStale: props.isStale,582+ expiresAt: props.expiresAt,583+ activities: props.activities.map(({ updatedAt: _updatedAt, ...row }) => row),584+ });585+ if (content === publishedWidgetContent) return;586+ if (publishAgentActivityWidget(props)) publishedWidgetContent = content;587+}588+589+function publishReconciledWidget(): void {590+ if (!relayTokenProvider) return;591+ if (relayWidgetSnapshot === null && observedWidgetActivities.size === 0) return;592+ const result = reconcileWidgetActivity(observedWidgetActivities, relayWidgetSnapshot);593+ const confirmations = [...observedWidgetActivities.keys()].map(594+ (id) => widgetShellConfirmedAt.get(id) ?? 0,595+ );596+ if (relayWidgetConfirmedAt !== null) confirmations.push(relayWidgetConfirmedAt);infra/relay/migrations/postgres/20261006011848_agent_widget_refresh/snapshot.json line 907OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +887,21 @@887+ "identity": null,888+ "name": "recovery_enabled_at",889+ "entityType": "columns",890+ "schema": "public",891+ "table": "relay_managed_endpoint_allocations"892+ },893+ {894+ "type": "text",895+ "typeSchema": null,896+ "notNull": false,897+ "dimensions": 0,898+ "default": null,899+ "generated": null,900+ "identity": null,901+ "name": "recovery_environment_public_key",902+ "entityType": "columns",903+ "schema": "public",904+ "table": "relay_managed_endpoint_allocations"905+ },906+ {907+ "type": "jsonb",
- apps/mobile/plugins/widget/AgentWidgetState.swift line 33OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +13,21 @@13+ base["isExpired"] = false14+ base["isStale"] = false15+ base["expiresAt"] = freshnessDeadline.timeIntervalSince1970 * 100016+ let covered = Set(environmentIds)17+ let relayRows = base["activities"] as? [[String: Any]] ?? []18+ let localRows = (localObservation?["activities"] as? [[String: Any]] ?? []).filter {19+ guard let environmentId = $0["environmentId"] as? String else { return false }20+ return !covered.contains(environmentId)21+ }22+ let localDeadline = (localObservation?["expiresAt"] as? NSNumber).map {23+ Date(timeIntervalSince1970: $0.doubleValue / 1000)24+ }25+ func merged(at date: Date) -> [String: Any] {26+ var props = base27+ let directRows = localRows.map { row in28+ localDeadline.map { $0 > date } == true ? row : stale(row)29+ }30+ props["activities"] = relayRows + directRows31+ let unavailable = directRows.contains { $0["phase"] as? String == "stale" }32+ let directCount = directRows.filter { isUnfinished($0) }.count33+ props["activeCount"] = unavailable ? -1 : (base["activeCount"] as? Int ?? 0) + directCount
- apps/mobile/plugins/widget/AgentWidgetState.swift lines 20 to 24OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+// app's original deadline; an empty relay never claims that they finished.5+enum AgentWidgetState {6+ static func timeline(aggregate: [String: Any]?, environmentIds: [String], localObservation: [String: Any]?, now: Date) -> [[String: Any]] {7+ let freshnessDeadline = now.addingTimeInterval(60 * 60)8+ var base = aggregate ?? [9+ "title": "T3 Code", "subtitle": "No active agents", "activeCount": 0,10+ "updatedAt": ISO8601DateFormatter().string(from: now), "activities": [[String: Any]]()11+ ]12+ base = base.filter { !($0.value is NSNull) }13+ base["isExpired"] = false14+ base["isStale"] = false15+ base["expiresAt"] = freshnessDeadline.timeIntervalSince1970 * 100016+ let covered = Set(environmentIds)17+ let relayRows = base["activities"] as? [[String: Any]] ?? []18+ let allLocalRows = localObservation?["activities"] as? [[String: Any]] ?? []19+ let localCount = localObservation?["activeCount"] as? Int20+ let countUnavailable = localObservation != nil && (localCount == nil || localCount! < 0 || localCount! > allLocalRows.filter { isUnfinished($0) }.count)21+ let localRows = allLocalRows.filter {22+ guard let environmentId = $0["environmentId"] as? String else { return false }23+ return !covered.contains(environmentId)24+ }apps/mobile/src/features/agent-awareness/liveWidgetActivity.ts lines 112 to 119OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +99,21 @@99+ readStartedWith: LiveWidgetActivities,100+ snapshot: RelayAgentActivitySnapshotResponse,101+): LiveWidgetActivities {102+ if ((snapshot.excludedEnvironmentIds?.length ?? 0) > 0) return observed;103+ const relayRows = snapshot.aggregate?.activities ?? [];104+ const complete = (snapshot.aggregate?.activeCount ?? 0) === relayRows.filter(isActive).length;105+ const retained = new Map(observed);106+ for (const [environmentId, rows] of observed) {107+ if (live.has(environmentId) || readStartedWith.get(environmentId) !== rows) continue;108+ const environmentRows = relayRows.filter((row) => row.environmentId === environmentId);109+ const confirmed =110+ rows.length === 0111+ ? complete && environmentRows.every((row) => !isActive(row))112+ : rows.every((row) =>113+ environmentRows.some(114+ (remote) =>115+ remote.threadId === row.threadId &&116+ (remote.updatedAt > row.updatedAt ||117+ (remote.updatedAt === row.updatedAt && remote.phase === row.phase)),118+ ),119+ );
- apps/mobile/src/features/agent-awareness/remoteRegistration.ts lines 567 to 569OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -469,0 +549,21 @@549+}550+551+function publishRegularWidget(props: AgentActivityProps): void {552+ // Streaming text changes shell timestamps without changing widget content.553+ const content = JSON.stringify({554+ activeCount: props.activeCount,555+ isStale: props.isStale,556+ expiresAt: props.expiresAt === undefined ? undefined : Math.floor(props.expiresAt / 60_000),557+ activities: props.activities.map(({ updatedAt: _updatedAt, ...row }) => row),558+ });559+ if (content === publishedWidgetContent) return;560+ if (publishAgentActivityWidget(props)) publishedWidgetContent = content;561+}562+563+function publishReconciledWidget(): void {564+ if (!relayTokenProvider) return;565+ if (relayWidgetSnapshot === null && observedWidgetActivities.size === 0) return;566+ const result = reconcileWidgetActivity(observedWidgetActivities, relayWidgetSnapshot);567+ const confirmations = [...observedWidgetActivities.keys()].map(568+ (id) => widgetShellConfirmedAt.get(id) ?? 0,569+ );
- infra/relay/src/agentActivity/MobileRegistrations.ts lines 97 to 100OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -92,4 +94,7 @@9294 ),9395 getAgentActivitySnapshot: Effect.fn("relay.mobile_registrations.get_agent_activity_snapshot")(9496 function* (input) {95- const activeStates = yield* rows.listForUser({ userId: input.userId });97+ const activeStates = yield* rows.listForUser({98+ userId: input.userId,99+ includeLiveActivitiesDisabled: true,100+ });
- apps/mobile/src/widgets/AgentActivity.tsx line 215OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -132,10 +201,15 @@201+ : hasRows202+ ? "Agent work completed"203+ : "No active agents";132204133- const agentWord = props.activeCount === 1 ? "agent" : "agents";134- const agentsLabel = allDone205+ const countLabel = allDone135206 ? outcomeLabel136- : environment.isStale207+ : props.isExpired || isSystemStale137208 ? "Agent status out of date"138- : `${props.activeCount} active ${agentWord}`;209+ : workingCount === null210+ ? "Working count unavailable"211+ : `${workingCount} working`;212+ const agentsLabel =213+ props.isStale && !props.isExpired ? `Last observed: ${countLabel}` : countLabel;139214 const attentionSuffix =140- attentionRows.length > 0141- ? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`215+ attentionCount !== null && attentionCount > 0apps/server/src/relay/AgentAwarenessRelay.ts line 615Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -533,3 +536,4 @@533536 threadId,534537 thread,535538 project,539+ now: (yield* DateTime.now).epochMilliseconds,apps/mobile/src/features/agent-awareness/liveWidgetActivity.ts lines 98 to 100OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+ left: ReadonlyArray<string>,81+ right: ReadonlyArray<string>,82+): boolean {83+ const leftSet = new Set(left);84+ const rightSet = new Set(right);85+ return leftSet.size === rightSet.size && [...leftSet].every((id) => rightSet.has(id));86+}87+88+/** A disconnect is not a newer observation. Omitted capped rows cannot confirm completion. */89+export function retainUnconfirmedWidgetActivities(90+ observed: LiveWidgetActivities,91+ live: LiveWidgetActivities,92+ readStartedWith: LiveWidgetActivities,93+ snapshot: RelayAgentActivitySnapshotResponse,94+): LiveWidgetActivities {95+ if ((snapshot.excludedEnvironmentIds?.length ?? 0) > 0) return observed;96+ const relayRows = snapshot.aggregate?.activities ?? [];97+ const complete =98+ (snapshot.aggregate?.activeCount ?? 0) === relayRows.filter(isActive).length &&99+ (snapshot.aggregate?.totalCount === undefined ||100+ snapshot.aggregate.totalCount === relayRows.length);
- apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentActivityPresentation.kt line 142OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -137,4 +139,4 @@137139 builder.setSubText(138140 listOfNotNull(139141 hero!!.project.takeIf { singleProject && it.isNotBlank() },140- if (activeCount > 0) "$activeCount active" else "$threadCount threads"142+ if (activeCount > 0) "$workingCount working" else "$threadCount threads"apps/mobile/src/widgets/AgentActivity.tsx line 645OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -360,4 +642,4 @@360642 <HStack spacing={5} alignment="center" modifiers={[padding({ leading: 4, vertical: 4 })]}>361643 {renderLogo(15, tint)}362644 <Text modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(tint)]}>363- {allDone ? doneLabel : `${props.activeCount}`}645+ {workingCount === null ? "?" : allDone ? doneLabel : `${workingCount}`}apps/server/src/relay/AgentAwarenessRelay.ts line 355OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -348,3 +352,4 @@348352 environmentId: input.environmentId,349353 project,350354 thread,355+ now: input.startedAt,
- infra/relay/src/agentActivity/AgentActivityPublisher.ts line 70OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -57,9 +59,12 @@5759 const liveActivities = yield* LiveActivities.LiveActivities;5860 const apnsDeliveries = yield* ApnsDeliveries.ApnsDeliveries;5961 const fcmDeliveries = yield* FcmDeliveries.FcmDeliveries;62+ const widgets = yield* AgentWidgetRefresh.AgentWidgetRefresh;60636164 const publishForDeliveryUser = Effect.fnUntraced(function* (input: {6265 readonly deliveryUser: EnvironmentLinks.AgentAwarenessDeliveryUserRecord;6366 readonly state: RelayAgentActivityState | null;6467 readonly nowMs: number;68+ readonly replay?: boolean;6569 }) {70+ const widgetDeliveries = yield* widgets.notify({ userId: input.deliveryUser.userId }).pipe(apps/mobile/src/features/agent-awareness/liveWidgetActivity.ts lines 108 to 108OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -0,0 +88,21 @@88+/** A disconnect is not a newer observation. Omitted capped rows cannot confirm completion. */89+export function retainUnconfirmedWidgetActivities(90+ observed: LiveWidgetActivities,91+ live: LiveWidgetActivities,92+ readStartedWith: LiveWidgetActivities,93+ snapshot: RelayAgentActivitySnapshotResponse,94+): LiveWidgetActivities {95+ if ((snapshot.excludedEnvironmentIds?.length ?? 0) > 0) return observed;96+ const relayRows = snapshot.aggregate?.activities ?? [];97+ const complete =98+ snapshot.aggregate === null ||99+ (snapshot.aggregate.activeCount === relayRows.filter(isActive).length &&100+ snapshot.aggregate.totalCount !== undefined &&101+ snapshot.aggregate.totalCount === relayRows.length);102+ const retained = new Map(observed);103+ for (const [environmentId, rows] of observed) {104+ if (live.has(environmentId) || readStartedWith.get(environmentId) !== rows) continue;105+ const environmentRows = relayRows.filter((row) => row.environmentId === environmentId);106+ const confirmed =107+ rows.length === 0108+ ? complete && environmentRows.every((row) => !isActive(row))apps/server/src/relay/AgentAwarenessRelay.ts line 615Resolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -531,3 +534,4 @@531534 environmentId,532535 thread,533536 project,537+ now: (yield* DateTime.now).epochMilliseconds,
- infra/relay/src/agentActivity/Devices.ts lines 136 to 138OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -131,3 +133,6 @@131133 apsEnvironment: registration.apsEnvironment ?? null,132134 pushToken: registration.pushToken ?? null,133135 pushToStartToken: registration.pushToStartToken ?? null,136+ widgetAccessTokenHash: registration.widgetAccessToken137+ ? NodeCrypto.createHash("sha256").update(registration.widgetAccessToken).digest("hex")138+ : null,
- apps/server/src/relay/AgentAwarenessRelay.ts line 575OutdatedResolvedby jakeleventhal(GitHub profile, opens in a new tab)@@ -531,12 +564,12 @@531564 environmentId,532565 thread,533566 project,567+ now: (yield* DateTime.now).epochMilliseconds,534568 });535569 const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);536570 const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);537- if (571+ const replay =538572 (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") &&539- !publishedStateByThread.has(threadId)540- ) {541- if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return;542- }573+ !publishedStateByThread.has(threadId) &&574+ Option.isSome(thread) &&575+ !terminalWorkSinceStart(thread.value, startedAt);
- apps/server/src/relay/AgentAwarenessRelay.ts lines 757 to 762Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -635,4 +678,11 @@635678 projectId: snapshot.projectId,636679 state: snapshot.state,637680 reason: snapshot.reason,681+ replay,638682 }).pipe(withRelayClientTracing);683+ if (684+ completedAt !== undefined &&685+ (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed")686+ ) {687+ publishedTerminalWork.set(threadId, { phase: snapshot.state.phase, completedAt });688+ }
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed