Make phone Send follow the paired desktop setting (#37315)

* Make phone follow-up delivery follow paired desktop

* Keep the paired desktop's follow-up setting live through a server outage

The phone now keeps listening to the paired desktop's Queue follow-ups
setting while a chat is open, even when the workspace's server relay
drops, so a desktop toggle during the outage is used by the next Send.
The chat reuses the route's existing paired-host connection instead of
acquiring it again per chat, and the follow-up tests load and typecheck.

* Keep the chat lock-reason helper out of modules the desktop tests import

The overlay lock-reason helper moves to its own file so the shared
eligibility module no longer reaches the chat view, which pulled the
phone's UI types into the desktop end-to-end typecheck. The reconnect
test now drops and restores the client's own connection, and checks the
preference stream closes with it and reopens with one fresh read.
This commit is contained in:
Brennan Benson
2026-11-01 21:40:47 -08:00
committed by GitHub
parent 5d3dfe943e
commit f9a4ba6225
34 changed files with 459 additions and 39 deletions
@@ -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,
@@ -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) => {
@@ -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<RpcClient['subscribe']>((_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<RpcClient['sendRequest']>(
async (_method, _params, options) => reply(options?.envelope?.executionHost !== undefined)
)
other.client.sendRequest = vi.fn<RpcClient['sendRequest']>(async () => reply(false))
const server = scopeRpcClientToExecutionHost(desktop.client, 'runtime:s')
const renders = new Map<string, number>()
const values = new Map<string, boolean>()
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) => (
<Chat key={index} id={`d${index}`} client={server} paired={desktop.client} />
))}
<Chat id="other" client={other.client} paired={other.client} />
</>
)
)
})
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<string, number>()
const values = new Map<string, boolean>()
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<string, boolean>()
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
@@ -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) {
@@ -150,6 +150,7 @@ export function mobileQueuedEditHarness() {
state.bottomText = useMobileNativeChatDraft('original-bottom')
state.hook = useMobileStructuredAgentSession({
client: transport,
pairedHostClient: transport,
sessionId,
sourceIdentity: 'host-a',
enabled,
@@ -60,6 +60,8 @@ export type StructuredMobileSession = ReturnType<typeof useMobileStructuredAgent
export type MobileStructuredAgentSessionArgs = {
client: RpcClient | null
/** The route's paired host owns follow-up behavior even when another host executes the chat. */
pairedHostClient: RpcClient | null
sessionId: string | null
/** Host/workspace scope used to keep same provider ids isolated. */
sourceIdentity?: string
@@ -179,6 +179,7 @@ describe('MobileNativeChatComposer on a structured chat', () => {
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,
@@ -196,6 +196,7 @@ async function mountPhone(): Promise<Phone> {
function Harness(): ReturnType<typeof createElement> {
const session = useMobileStructuredAgentSession({
client,
pairedHostClient: client,
sessionId: STOP_JOURNAL_SESSION,
sourceIdentity: 'host\0workspace',
enabled: true,
@@ -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')
}
@@ -116,6 +116,7 @@ describe('MobileNativeChatMessage', () => {
function Transcript() {
const structured = useMobileStructuredAgentSession({
client,
pairedHostClient: client,
sessionId: 'session-1',
agent: 'claude',
enabled: true,
@@ -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',
@@ -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
@@ -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,
@@ -159,6 +159,7 @@ async function mounted(initial: ReturnType<typeof peer>, sessionId: string, conn
useMobileSessionTabReconciliation(reconciliationScope)
const lane = useMobileNativeChatSessionLane({
client: props.peer.client,
pairedHostClient: null,
hostId: props.hostId,
structured: true,
resolution: resolveMobileNativeChat({
@@ -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)
}
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -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,
@@ -112,6 +112,7 @@ function Harness({
}): null {
hook = useMobileStructuredAgentSession({
client,
pairedHostClient: client,
sessionId: 'session-1',
sourceIdentity: 'host-a\0workspace-a',
enabled: true,
@@ -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<string, boolean | undefined>([
['a', false],
['b', true]
])
const desktopEvents = new Map<string, (event: unknown) => void>()
let refuseDesktopRead = false
let holdDesktopRead: Promise<void> | null = null
const desktops = new Map<string, RpcClient>()
for (const id of ['a', 'b']) {
desktops.set(id, {
...client,
sendRequest: vi.fn<RpcClient['sendRequest']>(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<RpcClient['subscribe']>((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<void>((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) => {
@@ -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,
@@ -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,
@@ -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',
@@ -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,
@@ -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])
@@ -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
@@ -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,
@@ -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,
@@ -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(
@@ -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<unknown, 'follow-up-behavior', boolean> = (
// Missing reports let the caller preserve the older host's existing preference source.
const followUpBehaviorReader: RpcCompatibleReader<unknown, 'follow-up-behavior', boolean | null> = (
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 }
}
}
+8 -2
View File
@@ -25,8 +25,14 @@ export function useRouteCapability(capability: string): boolean {
)
}
export function useWorkspaceClient(hostId: string | undefined): ReturnType<typeof useHostClient> {
export function useWorkspaceClient(hostId: string | undefined): ReturnType<typeof useHostClient> & {
/** 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 }
}