diff --git a/mobile/src/session/__mocks__/mobile-prompt-controller.ts b/mobile/src/session/__mocks__/mobile-prompt-controller.ts index b1d56ed0546..a6be2e577e7 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-controller.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-controller.ts @@ -139,6 +139,7 @@ function Harness(props: HarnessProps) { const { tab = baseTab, tabId = 'tab-1', connState = 'connected', hostId = 'host' } = props const current = useMobileNativeChatController({ client, + pairedHostClient: client, hostId, worktreeId: 'folder:work', activeSessionTab: tab, diff --git a/mobile/src/session/mobile-dictation-agent-chat-start.test.tsx b/mobile/src/session/mobile-dictation-agent-chat-start.test.tsx index 3fa5bcf2945..4fc63b94191 100644 --- a/mobile/src/session/mobile-dictation-agent-chat-start.test.tsx +++ b/mobile/src/session/mobile-dictation-agent-chat-start.test.tsx @@ -96,6 +96,7 @@ type SessionScope = Pick< | 'hostId' | 'worktreeId' | 'client' + | 'pairedHostClient' | 'connState' | 'agentSessionHostSupport' | 'setInput' @@ -158,6 +159,7 @@ function Probe({ client, tab, connState, dictationEnabled }: ProbeOptions): null hostId: 'h1', worktreeId: 'w1', client, + pairedHostClient: client, connState, agentSessionHostSupport: structuredAgentSessionHostSupport([]), setInput: (next) => { diff --git a/mobile/src/session/mobile-follow-up-preference.test.tsx b/mobile/src/session/mobile-follow-up-preference.test.tsx index 11c8ffaa48c..0fcb1e8694f 100644 --- a/mobile/src/session/mobile-follow-up-preference.test.tsx +++ b/mobile/src/session/mobile-follow-up-preference.test.tsx @@ -11,6 +11,7 @@ function connection() { let state: ConnectionState = 'connected' let generation = 0 const callbacks: ((event: unknown) => void)[] = [] + const routedCallbacks: { host: string | undefined; callback: (event: unknown) => void }[] = [] const states = new Set<(state: ConnectionState) => void>() const stops = vi.fn() const replies: ((reply: RpcResponse) => void)[] = [] @@ -24,8 +25,10 @@ function connection() { ) const client: RpcClient = { sendRequest, - subscribe: vi.fn((_method, _params, callback) => { + subscribe: vi.fn((_method, _params, callback, options) => { callbacks.push(callback) + const host = options?.envelope?.executionHost + routedCallbacks.push({ host: typeof host === 'string' ? host : undefined, callback }) return stops }), onStateChange: (callback) => { @@ -50,6 +53,8 @@ function connection() { callbacks, states, emit: (event: unknown) => callbacks.at(-1)?.(event), + emitAt: (host: string | undefined, event: unknown) => + routedCallbacks.findLast((entry) => entry.host === host)?.callback(event), change: (next: ConnectionState, migrate = false) => { state = next if (migrate) { @@ -78,13 +83,93 @@ afterEach(() => { renderers.clear() }) +it.each([1, 10])( + 'shares paired/server reads and isolates selected renders for %i server chats', + async (count) => { + const desktop = connection(), + other = connection() + desktop.client.sendRequest = vi.fn( + async (_method, _params, options) => reply(options?.envelope?.executionHost !== undefined) + ) + other.client.sendRequest = vi.fn(async () => reply(false)) + const server = scopeRpcClientToExecutionHost(desktop.client, 'runtime:s') + const renders = new Map() + const values = new Map() + function Chat({ id, client, paired }: { id: string; client: RpcClient; paired: RpcClient }) { + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id, paired, true)) + renders.set(id, (renders.get(id) ?? 0) + 1) + return null + } + await act(async () => { + renderers.add( + create( + <> + {Array.from({ length: count }, (_, index) => ( + + ))} + + + ) + ) + }) + const initial = new Map(renders) + const desktopRenders = () => + Array.from({ length: count }, (_, index) => renders.get(`d${index}`)) + const initialDesktopRenders = desktopRenders() + expect(Array.from({ length: count }, (_, index) => values.get(`d${index}`))).toEqual( + Array(count).fill(false) + ) + for (const host of [undefined, 'runtime:s']) { + expect( + vi + .mocked(desktop.client.sendRequest) + .mock.calls.filter( + ([method, , options]) => + method === 'settings.get' && options?.envelope?.executionHost === host + ) + ).toHaveLength(1) + expect( + vi + .mocked(desktop.client.subscribe) + .mock.calls.filter( + ([method, , , options]) => + method === 'runtime.clientEvents.subscribe' && + options?.envelope?.executionHost === host + ) + ).toHaveLength(1) + } + expect(desktop.stops).not.toHaveBeenCalled() + await act(async () => desktop.emitAt(undefined, { type: 'unrelated' })) + expect(desktopRenders()).toEqual(initialDesktopRenders) + await act(async () => + desktop.emitAt('runtime:s', { + type: 'nativeChatQueueFollowUpsChanged', + queueFollowUps: false + }) + ) + expect(desktopRenders()).toEqual(initialDesktopRenders) + await act(async () => + other.emitAt(undefined, { type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(desktopRenders()).toEqual(initialDesktopRenders) + expect(renders.get('other')).toBe(initial.get('other')! + 1) + const otherRenders = renders.get('other') + await act(async () => + desktop.emitAt(undefined, { type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(desktopRenders()).toEqual(initialDesktopRenders.map((renders) => renders! + 1)) + expect(renders.get('other')).toBe(otherRenders) + expect(desktop.stops).not.toHaveBeenCalled() + } +) + it('shares one live scalar per connection, fences late reads/events, and isolates real hook renders', async () => { const a = connection(), b = connection() const renders = new Map() const values = new Map() function Chat({ id, client }: { id: string; client: RpcClient }) { - values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id, client, true)) renders.set(id, (renders.get(id) ?? 0) + 1) return null } @@ -216,7 +301,7 @@ it('keeps known OFF across real direct/relay migrations and failed reads, while const logical = createStableLogicalRpcClient(direct.client, 'lan') const values = new Map() function Chat({ id, client }: { id: string; client: RpcClient | null }) { - values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id, client, true)) return null } let mounted!: ReactTestRenderer diff --git a/mobile/src/session/mobile-native-chat-follow-up-preference.ts b/mobile/src/session/mobile-native-chat-follow-up-preference.ts index af701c73b3d..4da6d8c5e7c 100644 --- a/mobile/src/session/mobile-native-chat-follow-up-preference.ts +++ b/mobile/src/session/mobile-native-chat-follow-up-preference.ts @@ -17,7 +17,7 @@ export function mobileNativeChatFollowUpPreference( } class MobileNativeChatFollowUpPreference { - private value = nativeChatQueueFollowUps(null) + private value: boolean | null = null private readonly listeners = new Set<() => void>() private stopState?: () => void private stopStream?: () => void @@ -26,7 +26,8 @@ class MobileNativeChatFollowUpPreference { constructor(private readonly client: RpcClient) {} - getSnapshot = (): boolean => this.value + getSnapshot = (): boolean => this.value ?? nativeChatQueueFollowUps(null) + getReportedSnapshot = (): boolean | null => this.value subscribe = (listener: () => void): (() => void) => { this.listeners.add(listener) @@ -47,7 +48,7 @@ class MobileNativeChatFollowUpPreference { } } - private publish(value: boolean): void { + private publish(value: boolean | null): void { if (value !== this.value) { this.value = value for (const listener of this.listeners) { diff --git a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx index 08949dcf373..f5863efd655 100644 --- a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx +++ b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx @@ -150,6 +150,7 @@ export function mobileQueuedEditHarness() { state.bottomText = useMobileNativeChatDraft('original-bottom') state.hook = useMobileStructuredAgentSession({ client: transport, + pairedHostClient: transport, sessionId, sourceIdentity: 'host-a', enabled, diff --git a/mobile/src/session/mobile-structured-agent-session-contract.ts b/mobile/src/session/mobile-structured-agent-session-contract.ts index 8d4c1beab2f..867fa7c4513 100644 --- a/mobile/src/session/mobile-structured-agent-session-contract.ts +++ b/mobile/src/session/mobile-structured-agent-session-contract.ts @@ -60,6 +60,8 @@ export type StructuredMobileSession = ReturnType { function Conversation() { const session = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host', enabled: true, @@ -277,6 +278,7 @@ describe('MobileNativeChatComposer on a structured chat', () => { function Conversation() { const session = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host', enabled: true, @@ -504,6 +506,7 @@ describe('MobileNativeChatComposer on a structured chat', () => { function Conversation() { const session = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host', enabled: true, diff --git a/mobile/src/session/native-chat/mobile-native-chat-merged-snapshot-parity-hooks.test.tsx b/mobile/src/session/native-chat/mobile-native-chat-merged-snapshot-parity-hooks.test.tsx index f2e24f480f9..0bac8f60d5a 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-merged-snapshot-parity-hooks.test.tsx +++ b/mobile/src/session/native-chat/mobile-native-chat-merged-snapshot-parity-hooks.test.tsx @@ -196,6 +196,7 @@ async function mountPhone(): Promise { function Harness(): ReturnType { const session = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: STOP_JOURNAL_SESSION, sourceIdentity: 'host\0workspace', enabled: true, diff --git a/mobile/src/session/native-chat/mobile-native-chat-overlay-lock-reason.ts b/mobile/src/session/native-chat/mobile-native-chat-overlay-lock-reason.ts new file mode 100644 index 00000000000..3d8b2324617 --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-overlay-lock-reason.ts @@ -0,0 +1,18 @@ +import type { ConnectionState } from '../../transport/types' +import { + isMobileNativeChatAgentConfirmed, + type MobileNativeChatTab +} from './mobile-native-chat-eligibility' +import type { MobileNativeChatInputLockReason } from './MobileNativeChatView' + +export function mobileNativeChatOverlayInputLockReason( + tab: MobileNativeChatTab | null, + connState: ConnectionState, + leaseLockReason: MobileNativeChatInputLockReason | null +): MobileNativeChatInputLockReason | null { + if (tab?.type === 'agent-session') { + return connState === 'connected' ? null : 'disconnected' + } + // Why: a chat only this phone remembers may sit on a bare shell; never type into it. + return leaseLockReason ?? (isMobileNativeChatAgentConfirmed(tab) ? null : 'waiting') +} diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts index b3c1961df9c..df01835ef2c 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.test.ts @@ -116,6 +116,7 @@ describe('MobileNativeChatMessage', () => { function Transcript() { const structured = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', agent: 'claude', enabled: true, diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts b/mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts index 456e43a2814..13032b110a5 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts @@ -209,6 +209,7 @@ describe('useMobileNativeChatController handleNativeChatSend', () => { }): null { controller = useMobileNativeChatController({ client: clientStub as unknown as RpcClient, + pairedHostClient: null, connState, hostId: 'h', worktreeId: 'w', @@ -389,6 +390,7 @@ describe('useMobileNativeChatController ask dismissal across a transcript reload function Harness(): null { controller = useMobileNativeChatController({ client: clientStub as unknown as RpcClient, + pairedHostClient: null, connState: 'connected', hostId: 'h', worktreeId: 'w', @@ -610,6 +612,7 @@ describe('useMobileNativeChatController terminal turn', () => { function Harness(): null { controller = useMobileNativeChatController({ client: clientStub as unknown as RpcClient, + pairedHostClient: null, connState: 'connected', hostId: 'h', worktreeId: 'w', diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts b/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts index 5ad07771488..2dfd8cd924c 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-controller.ts @@ -19,6 +19,8 @@ import { mobileNativeChatScopeKey } from './mobile-native-chat-scope-key' export function useMobileNativeChatController(args: { client: RpcClient | null + /** The route's paired host; differs from `client` only when a server executes the workspace. */ + pairedHostClient: RpcClient | null hostId: string worktreeId: string activeSessionTab: MobileNativeChatTab | null diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts index 20b6d67e0fa..961678713a6 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session-lane.ts @@ -11,6 +11,7 @@ import type { MobileNativeChatSendErrorReporter } from './use-mobile-native-chat // Run both hooks in fixed order and starve the inactive lane’s identity so flips preserve cached transcripts. export function useMobileNativeChatSessionLane({ client, + pairedHostClient, hostId, composerScopeKey, structured, @@ -25,6 +26,7 @@ export function useMobileNativeChatSessionLane({ onActionResolved }: { client: RpcClient | null + pairedHostClient: RpcClient | null hostId: string composerScopeKey?: string | null structured: boolean @@ -66,6 +68,7 @@ export function useMobileNativeChatSessionLane({ }) const structuredSession = useMobileStructuredAgentSession({ client, + pairedHostClient, sessionId: structured ? sessionId : null, sourceIdentity, hostSupport, diff --git a/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx b/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx index ae0a42b173a..f9d595d68e0 100644 --- a/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx +++ b/mobile/src/session/use-mobile-native-chat-capability-demand.test.tsx @@ -159,6 +159,7 @@ async function mounted(initial: ReturnType, sessionId: string, conn useMobileSessionTabReconciliation(reconciliationScope) const lane = useMobileNativeChatSessionLane({ client: props.peer.client, + pairedHostClient: null, hostId: props.hostId, structured: true, resolution: resolveMobileNativeChat({ diff --git a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts index 64f30207552..22e98ee5b80 100644 --- a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts +++ b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts @@ -8,17 +8,30 @@ const defaultSnapshot = (): boolean => nativeChatQueueFollowUps(null) export function useMobileNativeChatQueueFollowUps( client: RpcClient | null, connected: boolean, - sessionId: string | null + sessionId: string | null, + pairedHostClient: RpcClient | null, + active: boolean ): boolean { const preference = client ? mobileNativeChatFollowUpPreference(client) : null + const pairedPreference = pairedHostClient + ? mobileNativeChatFollowUpPreference(pairedHostClient) + : null + // The paired host's stream outlives an execution-server outage; the projection follows its own connection. + const subscribePaired = useCallback( + (listener: () => void) => + pairedPreference && active && sessionId ? pairedPreference.subscribe(listener) : () => {}, + [pairedPreference, active, sessionId] + ) const subscribe = useCallback( (listener: () => void) => preference && connected && sessionId ? preference.subscribe(listener) : () => {}, [preference, connected, sessionId] ) - return useSyncExternalStore( - subscribe, - preference?.getSnapshot ?? defaultSnapshot, - defaultSnapshot + const getSnapshot = useCallback( + () => pairedPreference?.getReportedSnapshot() ?? preference?.getSnapshot() ?? defaultSnapshot(), + [pairedPreference, preference] ) + // Both stores read the combined value, so only a change to what Send uses re-renders. + useSyncExternalStore(subscribePaired, getSnapshot, defaultSnapshot) + return useSyncExternalStore(subscribe, getSnapshot, defaultSnapshot) } diff --git a/mobile/src/session/use-mobile-session-foundation.ts b/mobile/src/session/use-mobile-session-foundation.ts index 9e474bed22d..9dfaa1c7cf3 100644 --- a/mobile/src/session/use-mobile-session-foundation.ts +++ b/mobile/src/session/use-mobile-session-foundation.ts @@ -36,7 +36,7 @@ export function useMobileSessionFoundation() { const isFloatingWorkspaceRoute = isFloatingWorkspaceWorktreeId(worktreeId) const router = useRouteHandoff() const insets = useSafeAreaInsets() - const { client, clientId, state: connState } = useWorkspaceClient(hostId) + const { client, clientId, state: connState, pairedHostClient } = useWorkspaceClient(hostId) const { hostCapabilities } = useHostProtocolGates() const reconnectAttempts = useReconnectAttempt(hostId) const lastConnectedAt = useLastConnectedAt(hostId) @@ -102,6 +102,7 @@ export function useMobileSessionFoundation() { client, clientId, connState, + pairedHostClient, hostCapabilities, reconnectAttempts, lastConnectedAt, diff --git a/mobile/src/session/use-mobile-session-native-chat-dictation.ts b/mobile/src/session/use-mobile-session-native-chat-dictation.ts index c9acf5bc472..ac69d40aef1 100644 --- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts +++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts @@ -26,7 +26,7 @@ import { useMobileNativeChatReadability } from './native-chat/transcript/use-mob import { useMobileNativeChatInputLease } from './native-chat/use-mobile-native-chat-input-lease' import { useMobileNativeChatSendError } from './native-chat/use-mobile-native-chat-send-error' import { mobileNativeChatScopeKey } from './native-chat/mobile-native-chat-scope-key' -import { isMobileNativeChatAgentConfirmed } from './native-chat/mobile-native-chat-eligibility' +import { mobileNativeChatOverlayInputLockReason } from './native-chat/mobile-native-chat-overlay-lock-reason' import { useMobileSendCompletionGeneration } from './use-mobile-send-completion-generation' import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy' import type { MobileSessionFeedbackCapabilitiesModel } from './use-mobile-session-feedback-capabilities' @@ -39,6 +39,7 @@ export function useMobileSessionNativeChatDictation( hostId, worktreeId, client, + pairedHostClient, connState, agentSessionHostSupport, setInput, @@ -81,6 +82,7 @@ export function useMobileSessionNativeChatDictation( }) const nativeChatController = useMobileNativeChatController({ client, + pairedHostClient, hostId, worktreeId, activeSessionTab, @@ -98,14 +100,11 @@ export function useMobileSessionNativeChatDictation( const { toggleTabChatView, showNativeChat, showNativeChatRef } = nativeChatController nativeChatSendError.bannerMountedRef.current = showNativeChat nativeChatSendError.keepWhile(nativeChatController.nativeChatCommandRefusalCauses) - const nativeChatOverlayInputLockReason = - activeSessionTab?.type === 'agent-session' - ? connState === 'connected' - ? null - : 'disconnected' - : // Why: a chat only this phone remembers may sit on a bare shell; never type into it. - (nativeChatInputLockReason ?? - (isMobileNativeChatAgentConfirmed(activeSessionTab) ? null : 'waiting')) + const nativeChatOverlayInputLockReason = mobileNativeChatOverlayInputLockReason( + activeSessionTab, + connState, + nativeChatInputLockReason + ) const routeKey = nativeChatScopeKey ?? `${hostId}\0${worktreeId}` const getSendCompletionGeneration = useMobileSendCompletionGeneration({ onBlur: resetLiveInputFocus, diff --git a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx index 08bffce4e21..245468d4a71 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx @@ -78,6 +78,7 @@ describe('mobile structured session background tasks', () => { function Harness({ connected }: { connected: boolean }): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-hold-refused.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-hold-refused.test.tsx index 5a0744e2e26..613c3aaf878 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-hold-refused.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-hold-refused.test.tsx @@ -82,6 +82,7 @@ it('subscribes when an older host refuses the hold, and shows the transcript (P2 // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook's options, of which this test supplies the ones it reads. hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx index c1177bc92c9..71c013e49ff 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx @@ -47,6 +47,7 @@ const client: RpcClient = { function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-options-restart.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-options-restart.test.tsx index 9945701b5f8..bf43803f115 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-options-restart.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-options-restart.test.tsx @@ -69,6 +69,7 @@ async function hostAnswer(method: string) { function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-prompt-cancel.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-prompt-cancel.test.tsx index d6eee70f11d..df84b554f7d 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-prompt-cancel.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-prompt-cancel.test.tsx @@ -112,6 +112,7 @@ function Harness({ }): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx index 431b9873d18..63681f29970 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx @@ -6,10 +6,15 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentSessionSubscribeEvent } from '../../../src/shared/agent-session/agent-session-wire' import type { RpcClient } from '../transport/rpc-client' -import type { RpcResponse } from '../transport/types' +import type { ConnectionState, RpcResponse } from '../transport/types' import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' +import { useMobileNativeChatSessionLane } from './native-chat/use-mobile-native-chat-session-lane' +import { useHostClient } from '../transport/host-client-hooks' +import { useWorkspaceClient, WorkspaceServerContext } from '../transport/use-workspace-client' +import { scopeRpcClientToExecutionHost } from '../transport/execution-host-scoped-rpc-client' +import type { RpcClientContextValue } from '../transport/rpc-client-context-contract' import { CAPABLE, @@ -32,6 +37,29 @@ const asyncStorage = vi.hoisted(() => ({ vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) +const pairedContext = vi.hoisted( + (): { + value: Pick< + RpcClientContextValue, + | 'acquire' + | 'release' + | 'getKnownState' + | 'getClientId' + | 'getAllClients' + | 'subscribeHostState' + > | null + } => ({ value: null }) +) +// The native context module loads react-native, so only its hook is replaced. +vi.mock('../transport/client-context', () => ({ + useRpcClientContext: () => { + if (!pairedContext.value) { + throw new Error('No paired-host fixture') + } + return pairedContext.value + } +})) + function normalReply(method: string): RpcResponse { // Queue is the default; explicit OFF is covered below. if (method === 'settings.get') { @@ -90,6 +118,7 @@ describe('mobile structured queued messages', () => { }): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId, sourceIdentity: 'host-a\0workspace-a', enabled: true, @@ -204,6 +233,217 @@ describe('mobile structured queued messages', () => { }) describe('capability-gated delivery', () => { + it('routes preference reads to the paired desktop and sends to the workspace server', async () => { + let serverValue: boolean | undefined = true + const desktopValues = new Map([ + ['a', false], + ['b', true] + ]) + const desktopEvents = new Map void>() + let refuseDesktopRead = false + let holdDesktopRead: Promise | null = null + const desktops = new Map() + for (const id of ['a', 'b']) { + desktops.set(id, { + ...client, + sendRequest: vi.fn(async (method, params, options) => { + if (options?.envelope?.executionHost) { + return client.sendRequest(method, params, options) + } + if (method === 'settings.get') { + if (holdDesktopRead) { + await holdDesktopRead + } + return refuseDesktopRead + ? { + id: 'old', + ok: false, + error: { code: 'method_not_found', message: 'Unavailable' } + } + : ok({ settings: { nativeChatQueueFollowUps: desktopValues.get(id) } }) + } + return normalReply(method) + }), + subscribe: vi.fn((method, params, callback, options) => { + if (options?.envelope?.executionHost) { + return client.subscribe(method, params, callback, options) + } + if (method === 'runtime.clientEvents.subscribe') { + desktopEvents.set(id, callback) + } + return () => { + desktopEvents.delete(id) + } + }) + }) + } + pairedContext.value = { + acquire: (id) => desktops.get(id) ?? null, + release: () => {}, + getKnownState: () => 'connected', + getClientId: () => 'phone', + getAllClients: () => [...desktops].map(([hostId, client]) => ({ hostId, client })), + subscribeHostState: () => () => {} + } + sendRequest.mockImplementation(async (method) => { + if (method === 'settings.get') { + return ok({ settings: { nativeChatQueueFollowUps: serverValue } }) + } + if (method === 'agentSession.send') { + return mutationOk({ + clientMessageId: 'client-1', + submission: acceptedSubmission('client-1') + }) + } + return normalReply(method) + }) + function Chat({ hostId }: { hostId: string }) { + const workspace = useWorkspaceClient(hostId) + hook = useMobileNativeChatSessionLane({ + client: workspace.client, + pairedHostClient: workspace.pairedHostClient, + hostId, + connState: workspace.state, + structured: true, + resolution: { + agent: 'claude', + sessionId: SESSION_ID, + transcriptPath: null, + agentConfirmed: true, + sessionLive: true + }, + sourceIdentity: hostId, + hostSupport: CAPABLE, + appendComposerTextRef: { current: appendText }, + enabled: true, + onSendError + }).structuredSession + return null + } + function Route({ + hostId, + serverState = 'connected' + }: { + hostId: string + serverState?: ConnectionState + }) { + const desktop = useHostClient(hostId) + return createElement( + WorkspaceServerContext.Provider, + { + value: { + client: desktop.client + ? scopeRpcClientToExecutionHost(desktop.client, 'runtime:server') + : null, + state: desktop.client ? serverState : 'connecting', + desktopCapabilities: [] + } + }, + createElement(Chat, { hostId }) + ) + } + const working = { + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + } + await act(async () => { + renderer = create(createElement(Route, { hostId: 'a' })) + }) + await act(async () => listener?.(working)) + expect(hook!.sendFollowUp).toEqual({ action: 'steer', offersChoice: true }) + await act(async () => { + await hook!.sendWithOutcome('follow desktop OFF') + }) + expect(requestOf('agentSession.send').params.delivery).toBeUndefined() + expect( + sendRequest.mock.calls.find(([method]) => method === 'agentSession.send')?.[2]?.envelope + ?.executionHost + ).toBe('runtime:server') + const desktop = desktops.get('a')! + expect( + vi + .mocked(desktop.sendRequest) + .mock.calls.some( + ([method, , options]) => + method === 'settings.get' && options?.envelope?.executionHost === undefined + ) + ).toBe(true) + expect( + vi + .mocked(desktop.subscribe) + .mock.calls.some( + ([method, , , options]) => + method === 'runtime.clientEvents.subscribe' && + options?.envelope?.executionHost === undefined + ) + ).toBe(true) + + await act(async () => + desktopEvents.get('a')?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + await act(async () => { + await hook!.sendWithOutcome('follow desktop ON') + }) + expect(requestOf('agentSession.send', 1).params.delivery).toBe('queue-if-active') + await act(async () => + preferenceListener?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(hook!.sendFollowUp?.action).toBe('queue') + + // A refusal retains the desktop answer; an accepted missing field restores the old host path. + refuseDesktopRead = true + await act(async () => desktopEvents.get('a')?.({ type: 'ready', snapshot: {} })) + expect(hook!.sendFollowUp?.action).toBe('queue') + refuseDesktopRead = false + desktopValues.set('a', undefined) + await act(async () => desktopEvents.get('a')?.({ type: 'ready', snapshot: {} })) + expect(hook!.sendFollowUp?.action).toBe('steer') + serverValue = undefined + await act(async () => preferenceListener?.({ type: 'ready', snapshot: {} })) + expect(hook!.sendFollowUp?.action).toBe('queue') + + desktopValues.set('a', false) + await act(async () => + desktopEvents.get('a')?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(hook!.sendFollowUp?.action).toBe('steer') + + // A server relay outage leaves the desktop stream open, so its toggle is current at recovery. + await act(async () => + renderer!.update(createElement(Route, { hostId: 'a', serverState: 'disconnected' })) + ) + expect(desktopEvents.has('a')).toBe(true) + desktopValues.set('a', true) + await act(async () => + desktopEvents.get('a')?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + // Held desktop reads mean recovery can't repair a toggle the phone missed. + let releaseDesktopRead = () => {} + holdDesktopRead = new Promise((resolve) => { + releaseDesktopRead = () => resolve() + }) + const outageListener = listener + await act(async () => renderer!.update(createElement(Route, { hostId: 'a' }))) + await vi.waitFor(() => expect(listener).not.toBe(outageListener)) + await act(async () => listener?.(working)) + await act(async () => { + await hook!.sendWithOutcome('follow desktop toggled during the outage') + }) + expect(requestOf('agentSession.send', 2).params.delivery).toBe('queue-if-active') + holdDesktopRead = null + await act(async () => releaseDesktopRead()) + expect(hook!.sendFollowUp?.action).toBe('queue') + + await act(async () => renderer!.update(createElement(Route, { hostId: 'b' }))) + await act(async () => listener?.(working)) + expect(hook!.sendFollowUp?.action).toBe('queue') + }) + it.each(['steer', 'queue'] as const)( 'pre-turn host Working honors default and explicit choice (%s)', async (behavior) => { diff --git a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx index e81bd5fb790..05877652bd3 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx @@ -39,6 +39,7 @@ const client: RpcClient = { function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: SESSION_ID, sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx index ac03aae1127..3a9da8261bf 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx @@ -73,6 +73,7 @@ it('draws one row for a run of provider retries, with what failed on its second function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx index 440856b1af3..f8fb7a09d24 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx @@ -113,6 +113,7 @@ describe('mobile structured send actions', () => { banner.bannerMountedRef.current = true hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', composerScopeKey: 'ordinary-draft', diff --git a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx index d9eb14bdde5..fde42ef75c7 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx @@ -84,6 +84,7 @@ describe('useMobileStructuredAgentSession transcript', () => { rendered.hook = useMobileStructuredAgentSession({ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook's request, subscription and connection members are provided. client: client as RpcClient, + pairedHostClient: null, sessionId: 'session-1', enabled: true, connected: true, diff --git a/mobile/src/session/use-mobile-structured-agent-session.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.test.tsx index 4e95daa2b51..4a7e8ea8e51 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.test.tsx @@ -13,6 +13,7 @@ import type { } from '../../../src/shared/agent-session/journal/agent-session-journal-types' import type { SessionOptionDescriptor } from '../../../src/shared/native-chat/input/native-chat-session-options' import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState } from '../transport/types' import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' import { formatQuestionFreeTextAnswer } from './native-chat/input/mobile-native-chat-question' import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' @@ -204,11 +205,22 @@ describe('useMobileStructuredAgentSession', () => { } return unsubscribePreference }) + let clientState: ConnectionState = 'connected' + const stateListeners = new Set<(state: ConnectionState) => void>() + function setClientState(next: ConnectionState): void { + clientState = next + for (const stateListener of stateListeners) { + stateListener(next) + } + } const client: RpcClient = { sendRequest, subscribe, - getState: () => 'connected', - onStateChange: () => () => {}, + getState: () => clientState, + onStateChange: (stateListener) => { + stateListeners.add(stateListener) + return () => stateListeners.delete(stateListener) + }, getReconnectAttempt: () => 0, getLastConnectedAt: () => null, updateTerminalSubscriptionViewport: () => {}, @@ -230,13 +242,15 @@ describe('useMobileStructuredAgentSession', () => { }): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId, sourceIdentity, enabled: true, connected, + hostSupport: null, agent, onSendError - } as never) + }) return null } @@ -255,6 +269,7 @@ describe('useMobileStructuredAgentSession', () => { }) sendRequest.mockImplementation(defaultSendRequest) listener = null + clientState = 'connected' }) afterEach(() => { @@ -322,11 +337,14 @@ describe('useMobileStructuredAgentSession', () => { ) // Reconnect must acquire the connection-scoped hold before replaying the stream. + // The client reports its own drop before the route's connection prop follows. await act(async () => { + setClientState('disconnected') renderer?.update(createElement(Harness, { connected: false })) }) expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([1, 1]) await act(async () => { + setClientState('connected') renderer?.update(createElement(Harness, { connected: true })) }) @@ -354,6 +372,11 @@ describe('useMobileStructuredAgentSession', () => { throw new Error('reconnect calls were not recorded') } expect(secondHoldOrder).toBeLessThan(secondSubscribeOrder) + // The shared preference stream reopens with its client: one read at mount, one after reconnect. + expect(sendRequest.mock.calls.filter(([method]) => method === 'settings.get')).toHaveLength(2) + expect( + subscribe.mock.calls.filter(([method]) => method === 'runtime.clientEvents.subscribe') + ).toHaveLength(2) await act(async () => renderer?.unmount()) renderer = null expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([2, 2]) diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index 66e97e02815..9d7c2b768f9 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -42,7 +42,7 @@ import { useMobileStructuredSendWithOutcome } from './use-mobile-structured-send import { useMobileStructuredQueuedMessageControls } from './use-mobile-structured-queued-message-controls' import { useMobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' import { useMobileStructuredSends } from './use-mobile-structured-sends' -import { useMobileNativeChatQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' +import { useMobileNativeChatQueueFollowUps as useQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' import { useMobileStructuredStopOffer } from './use-mobile-structured-stop-offer' import { useMobileStructuredTurnIndicator } from './use-mobile-structured-turn-indicator' @@ -56,6 +56,7 @@ export function useMobileStructuredAgentSession( const { agent, client, + pairedHostClient: paired, connected, sessionId, sourceIdentity = '', @@ -68,7 +69,7 @@ export function useMobileStructuredAgentSession( // Gate queueing by capability while accepting published cards from every host. const queueCapable = hostSupport?.queuedMessages === true const commandsWait = queueCapable && hostSupport?.queuedCommands === true - const queueFollowUps = useMobileNativeChatQueueFollowUps(client, connected && enabled, sessionId) + const queueFollowUps = useQueueFollowUps(client, connected && enabled, sessionId, paired, enabled) const promptCancelSupported = hostSupport?.promptCancel ?? null const hostAnswersRepeatedStops = hostSupport?.quietRepeatedStop ?? null const hostStopsConversation = hostSupport?.conversationStop ?? null diff --git a/mobile/src/session/use-mobile-structured-sends.test.tsx b/mobile/src/session/use-mobile-structured-sends.test.tsx index 0075ddec9dc..afe8d9e76b4 100644 --- a/mobile/src/session/use-mobile-structured-sends.test.tsx +++ b/mobile/src/session/use-mobile-structured-sends.test.tsx @@ -81,6 +81,7 @@ describe('a structured send in the open chat', () => { function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx index 2692ef585da..203df092054 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx +++ b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx @@ -67,13 +67,15 @@ describe('useMobileStructuredAgentSession turn indicator', () => { function Harness(): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, connected: true, + hostSupport: null, agent: 'codex', onSendError - } as never) + }) return null } @@ -246,6 +248,7 @@ describe("useMobileStructuredAgentSession and the host's Stopping", () => { function Harness({ statusFeed }: { statusFeed: boolean }): null { hook = useMobileStructuredAgentSession({ client, + pairedHostClient: client, sessionId: 'session-1', sourceIdentity: 'host-a\0workspace-a', enabled: true, diff --git a/mobile/src/transport/settings-read-operations.test.ts b/mobile/src/transport/settings-read-operations.test.ts index b0e8a9ec02f..10ffe047343 100644 --- a/mobile/src/transport/settings-read-operations.test.ts +++ b/mobile/src/transport/settings-read-operations.test.ts @@ -59,12 +59,15 @@ describe('settings historical acceptance', () => { { nativeChatQueueFollowUps: false }, { nativeChatQueueFollowUps: 'false' } ])( - 'reads the existing queue boolean without treating false as missing (%j)', + 'distinguishes an explicit queue boolean from a missing older-host report (%j)', async (settings) => { const response = await nativeChatQueueFollowUpsRead.request(replyWith(success({ settings }))) expect(nativeChatQueueFollowUpsRead.interpret(response)).toEqual({ accepted: true, - value: settings?.nativeChatQueueFollowUps !== false + value: + typeof settings?.nativeChatQueueFollowUps === 'boolean' + ? settings.nativeChatQueueFollowUps + : null }) expect( nativeChatQueueFollowUpsRead.interpret( diff --git a/mobile/src/transport/settings-read-operations.ts b/mobile/src/transport/settings-read-operations.ts index c51c91470c7..004020a7b41 100644 --- a/mobile/src/transport/settings-read-operations.ts +++ b/mobile/src/transport/settings-read-operations.ts @@ -2,7 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from './rpc-operation' import type { RpcCompatibleReader } from './rpc-operation-contract' import { normalizeSourceControlGroupOrder } from '../../../src/shared/source-control-group-order' import type { SourceControlGroupOrder } from '../../../src/shared/ui-chrome-types' -import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' function settingsMember(raw: unknown): unknown { const boxed: { readonly settings?: unknown } | null | undefined = raw == null ? raw : Object(raw) @@ -118,18 +117,16 @@ export const terminalCopyTrimsGutterRead = bindDeferredRpcOperation( }) ) -// Absent settings default ON; delivery still depends on host capability. -const followUpBehaviorReader: RpcCompatibleReader = ( +// Missing reports let the caller preserve the older host's existing preference source. +const followUpBehaviorReader: RpcCompatibleReader = ( raw ) => { const settings = raw == null ? undefined : settingsMember(raw) + const value = settings == null ? undefined : settingsField(settings, 'nativeChatQueueFollowUps') return { compatible: true, variant: 'follow-up-behavior', - value: nativeChatQueueFollowUps({ - nativeChatQueueFollowUps: - settings == null ? undefined : settingsField(settings, 'nativeChatQueueFollowUps') - }), + value: typeof value === 'boolean' ? value : null, salvage: { droppedPaths: [], droppedCount: 0 } } } diff --git a/mobile/src/transport/use-workspace-client.ts b/mobile/src/transport/use-workspace-client.ts index 634648b3f0d..455d5e8ff58 100644 --- a/mobile/src/transport/use-workspace-client.ts +++ b/mobile/src/transport/use-workspace-client.ts @@ -25,8 +25,14 @@ export function useRouteCapability(capability: string): boolean { ) } -export function useWorkspaceClient(hostId: string | undefined): ReturnType { +export function useWorkspaceClient(hostId: string | undefined): ReturnType & { + /** The route's own paired host, which stays the phone's peer when a server executes the workspace. */ + pairedHostClient: RpcClient | null +} { const host = useHostClient(hostId) const server = useContext(WorkspaceServerContext) - return server === undefined ? host : { ...host, client: server.client, state: server.state } + const pairedHostClient = host.client + return server === undefined + ? { ...host, pairedHostClient } + : { ...host, client: server.client, state: server.state, pairedHostClient } }