From dd86ff22e6db3f1ef960e8dc6685c3c869b43a32 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:20:55 +0000 Subject: [PATCH] feat(mobile): save the chat when the app leaves the foreground A swipe-kill from the app switcher can end the app before the page is hidden: iOS fires visibilitychange only at background, and Android Recents leaves the activity resumed. The shell now sends an appInactive frame on iOS inactive and Android window blur, to pages that declare they read it, and the page saves any chat rows the store doesn't hold yet. --- .../mobile-web-shell/MobileWebShellScreen.tsx | 2 + .../src/mobile-web-shell/bridge-host-back.ts | 2 + .../mobile-web-shell/bridge-host-contract.ts | 2 + .../mobile-web-shell/bridge-host-init.test.ts | 13 ++++ mobile/src/mobile-web-shell/bridge-host.ts | 9 +++ .../bridge/bridge-app-inactive.ts | 22 ++++++ .../bridge/bridge-client-inbound-frames.ts | 5 ++ .../bridge/bridge-client-init-handshake.ts | 3 +- .../bridge/bridge-envelope.ts | 7 +- .../bridge/bridge-rpc-client.ts | 2 + .../use-app-leaves-foreground.ts | 39 ++++++++++ .../use-mobile-web-shell-bridge.ts | 6 ++ ...bile-native-chat-transcript-writer.test.ts | 73 +++++++++++++++++++ .../mobile-native-chat-transcript-writer.ts | 44 +++++++---- 14 files changed, 214 insertions(+), 15 deletions(-) create mode 100644 mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts create mode 100644 mobile/src/mobile-web-shell/use-app-leaves-foreground.ts create mode 100644 mobile/src/session/native-chat/mobile-native-chat-transcript-writer.test.ts diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 362ef475933..11e05d21660 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -27,6 +27,7 @@ import { useNativeImageActions } from '../platform/native-image-actions' import { processDeviceStore } from '../device-store/device-store' import { serveDeviceStoreVerb } from './device-store-verb-server' import { BRIDGE_STORE_VERB } from './bridge/bridge-store-verb' +import { useAppLeavesForeground } from './use-app-leaves-foreground' import { useShellPageBack } from './use-shell-page-back' import { useShellStackPop } from './use-shell-stack-pop' import { usePageLocationOnFold } from './page-location-on-fold' @@ -263,6 +264,7 @@ export function MobileWebShellScreen({ // The stream survives dropped frames; keep a count because diagnostics print only once per host. onBinaryFramesDropped: reportDroppedBinaryFrames }) + useAppLeavesForeground(bridge.sendAppInactive) // paneKey changes keep the session mounted; the host deduplicates routes and preserves in-flight frames. useShellPageStorageRefresh(refreshStorage, bridge.publishStorage) diff --git a/mobile/src/mobile-web-shell/bridge-host-back.ts b/mobile/src/mobile-web-shell/bridge-host-back.ts index c7bfdc7c1ee..26a49beb452 100644 --- a/mobile/src/mobile-web-shell/bridge-host-back.ts +++ b/mobile/src/mobile-web-shell/bridge-host-back.ts @@ -8,6 +8,8 @@ export type BridgeSessionBack = { readonly storageKeys?: readonly string[] /** The page's `ready` said it reads `connectionPath` frames. */ readonly connectionPathFrames?: true + /** The page's `ready` said it reads `appInactive` frames. */ + readonly appInactiveFrames?: true readonly terminalKeyRailClaim?: { readonly inputOwner?: string } } diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index efa1f1aca21..aa31263a3e6 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -168,6 +168,8 @@ export type BridgeHost = { * every page older than the frame; the caller then leaves the key to the navigator. */ sendBack: () => boolean + /** Tells a page that reads it that the app is leaving the foreground; nothing for older pages. */ + sendAppInactive: () => void // Transfer the session’s Back state on client-driven host rebuild; the mounted page never reclaims it. Ending sessions simply discard it. readSessionBack: () => BridgeSessionBack dispose: () => void diff --git a/mobile/src/mobile-web-shell/bridge-host-init.test.ts b/mobile/src/mobile-web-shell/bridge-host-init.test.ts index 24ac5913f79..0a64fd9585f 100644 --- a/mobile/src/mobile-web-shell/bridge-host-init.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-init.test.ts @@ -249,6 +249,19 @@ describe('init and state', () => { }) }) + it('tells only a page that reads them that the app is leaving the foreground', () => { + const reads = harness() + reads.host.receive(clientFrame({ type: 'ready', appInactiveFrames: true })) + reads.host.sendAppInactive() + expect(reads.last().type).toBe('appInactive') + + const older = harness() + older.host.receive(clientFrame({ type: 'ready' })) + const sent = older.frames().length + older.host.sendAppInactive() + expect(older.frames()).toHaveLength(sent) + }) + it('sends no path frame to a page that never said it reads them', () => { let notifyPath = () => {} const client = createFakeRpcClient({ diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index 5fb65c9c340..914b25c9b70 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -1,4 +1,5 @@ import type { ConnectionState } from '../transport/connection/connection-state' +import { BRIDGE_APP_INACTIVE_FRAME } from './bridge/bridge-app-inactive' import { BridgeCapExceededError } from './bridge-host-errors' import { createNativeVerbServer } from './bridge-host-native-verbs' @@ -67,6 +68,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { // re-handshake. Null is a page older than `storageKeys`, which gets the legacy keys only. let pageStorageKeys: readonly string[] | null = options.sessionBack?.storageKeys ?? null let pageReadsConnectionPath = options.sessionBack?.connectionPathFrames === true + let pageReadsAppInactive = options.sessionBack?.appInactiveFrames === true const frames = createBridgeHostFrames({ post: options.post, @@ -218,6 +220,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { serving = true pageStorageKeys = message.storageKeys ?? null pageReadsConnectionPath = message.connectionPathFrames === true + pageReadsAppInactive = message.appInactiveFrames === true back.readReady() // Dropped like the Back claim: a page still showing a terminal claims again on this `init`. reportRailClaim(false) @@ -331,11 +334,17 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { publishUiLocale: (next) => { routes.publishUiLocale(next, deliverable()) }, + sendAppInactive: () => { + if (pageReadsAppInactive && deliverable()) { + send({ v: BRIDGE_PROTOCOL_VERSION, type: BRIDGE_APP_INACTIVE_FRAME }) + } + }, sendBack: back.send, readSessionBack: () => ({ ...back.read(), ...(pageStorageKeys === null ? {} : { storageKeys: pageStorageKeys }), ...(pageReadsConnectionPath ? { connectionPathFrames: true as const } : {}), + ...(pageReadsAppInactive ? { appInactiveFrames: true as const } : {}), ...(railClaimed ? { terminalKeyRailClaim: { inputOwner: railOwner } } : {}) }), dispose diff --git a/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts b/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts new file mode 100644 index 00000000000..da8d00eecf0 --- /dev/null +++ b/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts @@ -0,0 +1,22 @@ +/** + * Shell to page, a frame: the app is leaving the foreground. iOS sends a page `visibilitychange` + * only once the app reaches the background, and a swipe-kill from the app switcher can stop it + * while it is merely inactive, so the page saves what it would save on hide when this arrives. + * Pages that read it say so in `ready`; older pages never receive one, and older shells never + * send one, so the page keeps saving on hide alone. + */ +export const BRIDGE_APP_INACTIVE_FRAME = 'appInactive' + +const listeners = new Set<() => void>() + +/** Page side: runs `listener` each time the shell says the app is leaving the foreground. */ +export function onPageAppInactive(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function emitPageAppInactive(): void { + for (const listener of listeners) { + listener() + } +} diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts index 57c5300af27..84c5a156be0 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts @@ -11,6 +11,7 @@ import { type BridgeHostMessage } from './bridge-envelope' import { reconstructBridgeError } from './bridge-error-capture' +import { BRIDGE_APP_INACTIVE_FRAME } from './bridge-app-inactive' export type BridgeInboundFramePort = { requests: BridgeClientRequests @@ -21,6 +22,7 @@ export type BridgeInboundFramePort = { acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void acceptBack: () => void acceptParked: () => void + acceptAppInactive: () => void acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void } @@ -70,6 +72,9 @@ export function createBridgeInboundFrameReader( case 'parked': port.acceptParked() return + case BRIDGE_APP_INACTIVE_FRAME: + port.acceptAppInactive() + return case 'terminalKey': port.acceptTerminalKey(message.key, message.inputOwner) return diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index cf8f09e1382..818fd030288 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -46,6 +46,7 @@ export function createPageReadyFrame(): Extract terminalKeys.accept(key, inputOwner) }) diff --git a/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts new file mode 100644 index 00000000000..e99bbd2e485 --- /dev/null +++ b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts @@ -0,0 +1,39 @@ +import { useEffect, useRef } from 'react' +import { AppState } from 'react-native' + +/** + * Calls `onLeave` once each time the app leaves the foreground, before the system can kill it from the app + * switcher. iOS: `inactive` (the app switcher, Notification Centre, Face ID); a page is hidden only once the app + * reaches the background, which a swipe-kill can skip. Android: window `blur` (Recents, the notification shade, and + * the app's own dialogs and sheets), because Recents leaves the activity resumed until the swipe kills the process. + * Callers must keep the work cheap and idempotent: it runs on every such flap. + * Not covered: on Android, Recents opened over one of the app's own sheets sends nothing more (the sheet's blur + * already did), so rows streamed in while the sheet was open wait for the next save. + */ +export function useAppLeavesForeground(onLeave: () => void): void { + const onLeaveRef = useRef(onLeave) + onLeaveRef.current = onLeave + useEffect(() => { + let away = AppState.currentState !== 'active' + const leave = (): void => { + if (!away) { + away = true + onLeaveRef.current() + } + } + const back = (): void => { + away = false + } + const change = AppState.addEventListener('change', (next) => + next === 'active' ? back() : leave() + ) + // Window focus events come from Android only. + const blur = AppState.addEventListener('blur', leave) + const focus = AppState.addEventListener('focus', back) + return () => { + change.remove() + blur.remove() + focus.remove() + } + }, []) +} diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 07a5f2cba67..9c4d2637936 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -69,6 +69,8 @@ export type MobileWebShellBridgeView = { * serves never said it takes one — the caller then leaves the key to the navigator. */ readonly sendBack: () => boolean + /** Tells the mounted page the app is leaving the foreground; nothing with no host or an older page. */ + readonly sendAppInactive: () => void } export type MobileWebShellBridgeArgs = { @@ -342,6 +344,10 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW sendBack: useCallback(() => { const mounted = hostRef.current return mounted !== null && mounted.sessionId === sessionId && mounted.host.sendBack() + }, [sessionId]), + sendAppInactive: useCallback(() => { + const mounted = hostRef.current + return mounted?.sessionId === sessionId ? mounted.host.sendAppInactive() : undefined }, [sessionId]) } } diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.test.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.test.ts new file mode 100644 index 00000000000..37f76f3a574 --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.test.ts @@ -0,0 +1,73 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { emitPageAppInactive } from '../../mobile-web-shell/bridge/bridge-app-inactive' +import { noteChatTranscript } from './mobile-native-chat-transcript-writer' + +function message(id: string): NativeChatMessage { + return { + id, + role: 'assistant', + blocks: [{ type: 'text', text: id }], + timestamp: 1, + source: 'transcript' + } +} + +describe('chat copies when the app leaves the foreground', () => { + const writes: string[] = [] + + beforeEach(() => { + writes.length = 0 + publishPageDeviceStore({ + available: () => true, + read: async (_table, keys) => ({ status: 'ok', values: keys.map(() => null) }), + write: async (_table, ops) => { + writes.push(...ops.map((op) => op.key)) + return { written: true } + } + }) + }) + + afterEach(() => { + vi.useRealTimers() + publishPageDeviceStore(null) + }) + + function note(rows: NativeChatMessage[]): void { + noteChatTranscript( + 'chat-leaving', + rows, + () => true, + (savedAt) => ({ + kind: 'terminal', + savedAt, + messages: rows, + hasMore: false, + beforeOffset: null + }) + ) + } + + it('saves new rows on leaving and writes nothing when a flap brings none', async () => { + vi.useFakeTimers() + note([message('m1'), message('m2')]) + emitPageAppInactive() + await vi.runAllTimersAsync() + expect(writes).toHaveLength(1) + + // Two minutes later, Notification Centre and back: the rows on screen are a new list with the same rows. + vi.setSystemTime(Date.now() + 120_000) + note([message('m1'), message('m2')]) + emitPageAppInactive() + note([message('m1'), message('m2')]) + emitPageAppInactive() + await vi.runAllTimersAsync() + expect(writes).toHaveLength(1) + + note([message('m1'), message('m2'), message('m3')]) + emitPageAppInactive() + await vi.runAllTimersAsync() + expect(writes).toHaveLength(2) + }) +}) diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts index 595ba9a4e9f..cc4d9c82945 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts @@ -1,4 +1,5 @@ import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import { onPageAppInactive } from '../../mobile-web-shell/bridge/bridge-app-inactive' import { EMPTY_STRUCTURED_AGENT_SESSION, reduceStructuredAgentSession, @@ -88,10 +89,16 @@ function yieldToPage(): Promise { } /** - * Writes a chat's noted copy unless the store already holds it. A turn settle or a close encodes in slices, - * so even a big chat costs no long task; a hide (`now`) encodes in one go, since the app may stop right after. + * When a copy is written. `settle` (a turn settles, a chat closes) and `leave` (the app leaving the foreground, which + * also fires for Notification Centre, Face ID or an Android dialog) encode in slices, so even a big chat costs no long + * task; a swipe-kill from the app switcher comes a beat later. `leave` writes only rows the store doesn't hold yet and + * otherwise keeps the copy noted for the next hide. `hide` encodes in one go, since the app may stop right after. */ -export function flushChatTranscript(identity: string, now = false): void { +type FlushWhen = 'settle' | 'hide' | 'leave' + +/** Writes a chat's noted copy unless the store already holds it. */ +export function flushChatTranscript(identity: string, when: FlushWhen = 'settle'): void { + const now = when === 'hide' const next = pending.get(identity) ?? (now ? encoding.get(identity) : undefined) pending.delete(identity) const store = readPageDeviceStore() @@ -100,9 +107,15 @@ export function flushChatTranscript(identity: string, now = false): void { } const stored = next.build(next.isLive() ? Date.now() : next.notedAt) const kept = peekStoredChatTranscript(identity) - if (kept && sameRows(kept, stored) && stored.savedAt - kept.savedAt < SAME_COPY_REWRITE_MS) { - written.add(next.source) - return + if (kept && sameRows(kept, stored)) { + if (when === 'leave') { + pending.set(identity, next) + return + } + if (stored.savedAt - kept.savedAt < SAME_COPY_REWRITE_MS) { + written.add(next.source) + return + } } const write = ++writes latestWrite.set(identity, write) @@ -142,25 +155,30 @@ export function flushChatTranscript(identity: string, now = false): void { .catch(retry) } -function flushAll(): void { +function flushAll(when: Exclude): void { for (const identity of new Set([...pending.keys(), ...encoding.keys()])) { - flushChatTranscript(identity, true) + flushChatTranscript(identity, when) } } -let hiddenListener = false +let listening = false function listenForHidden(): void { - if (hiddenListener || typeof document === 'undefined') { + if (listening) { + return + } + listening = true + // iOS hides the page only once the app is in the background; a swipe-kill from the app switcher comes sooner. + onPageAppInactive(() => flushAll('leave')) + if (typeof document === 'undefined') { return } - hiddenListener = true document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { - flushAll() + flushAll('hide') } }) // A document torn down while visible fires no hidden and runs no unmount cleanups. - window.addEventListener('pagehide', flushAll) + window.addEventListener('pagehide', () => flushAll('hide')) } // Reducer states that still show a stored copy no live read has confirmed, with when it was saved.