Observe retained Chat option owners through held session snapshots

Publish compatible binding enrichment to each live holder and reconcile actions against the original entry before canonical metadata. Keep desktop and phone observations immutable, recover late targets on publication, and route late option errors only to the current matching session.
This commit is contained in:
Brennan Benson
2026-11-12 07:11:37 -08:00
parent ebdd216339
commit 3fcda407aa
19 changed files with 1039 additions and 370 deletions
@@ -0,0 +1,106 @@
import { getAgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog'
import type { CatalogModel } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types'
import {
createNativeChatPtySessionOptions,
type NativeChatPtySessionOptionsSurface
} from '../../../../../src/shared/native-chat/input/native-chat-pty-session-options'
import type { NativeChatSessionOptionSettingsMutation } from '../../../../../src/shared/native-chat/input/native-chat-session-options'
import type {
NativeChatSessionOptionDispatchOptions,
NativeChatSessionOptionDispatchResult
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-dispatch'
import type { NativeChatSessionOptionOwner } from '../../../../../src/shared/native-chat/input/native-chat-session-option-owner'
import type { MobileNativeChatSendOutcome } from '../mobile-native-chat-send'
import { sayMobileNativeChatSessionOption } from './native-chat-session-option-copy'
type SurfaceEntry = {
agent: string
canSwitchOmpModel: boolean
surface: NativeChatPtySessionOptionsSurface
/** The discovered list last handed to the surface. */
models: readonly CatalogModel[] | null
}
export type MobileNativeChatSessionOptionsArgs = {
agent: string | null
owner?: NativeChatSessionOptionOwner
isDispatchTargetCurrent?: () => boolean
scopeKey: string | null
reportedModel: string | null
discoveredModels?: CatalogModel[] | null
modelSwitchCommand?: string
dispatchCommand: (
command: string,
options?: NativeChatSessionOptionDispatchOptions
) => Promise<MobileNativeChatSendOutcome | NativeChatSessionOptionDispatchResult>
onAgentPicker?: () => void
onControlError?: (message: string) => void
/** Saves picks as the host's launch defaults, as desktop does. */
writeSettings?: (mutation: NativeChatSessionOptionSettingsMutation) => void
}
export function createMobileSurfaceEntry(args: {
agent: string
scopeKey: string
identity: string
canSwitchOmpModel: boolean
latest: { readonly current: MobileNativeChatSessionOptionsArgs }
activeIdentity: { readonly current: string | null }
captured: MobileNativeChatSessionOptionsArgs
}): SurfaceEntry | null {
const { agent, identity, latest, activeIdentity } = args
const midSession = getAgentSessionOptionCatalog(agent)?.modelApply.midSession
// Phone-only: desktop confirms a Claude model switch on its terminal screen; the phone cannot, so it never saves one as a launch default.
const modelSwitchUnconfirmable =
midSession?.kind === 'command' && midSession.detectAgentInteraction !== undefined
const surface = createNativeChatPtySessionOptions({
agent,
owner: args.captured.owner,
scopeKey: args.scopeKey,
mode: 'live',
modelLabel: sayMobileNativeChatSessionOption('model'),
canSwitchOmpModel: args.canSwitchOmpModel,
dispatchCommand: async (command, options) => {
// One controller serves every tab: a queued pick must not reach the tab opened since.
if (
activeIdentity.current !== identity ||
args.captured.isDispatchTargetCurrent?.() === false
) {
throw new Error('The chat changed before the command was sent.')
}
const outcome = await args.captured.dispatchCommand(command, options)
if (typeof outcome === 'object') {
return outcome
}
// Desktop commits a pick only after the terminal confirms the write.
if (outcome === 'rejected' || outcome === 'unknown') {
throw new Error('The terminal did not accept the command.')
}
},
onAgentPicker: () => {
if (activeIdentity.current === identity) {
latest.current.onAgentPicker?.()
}
},
persistSelection: (pick) => {
// A pick that lands after the phone moved to another host's chat must not become that host's default.
if (modelSwitchUnconfirmable && pick.optionId === 'model') {
return
}
args.captured.writeSettings?.({
type: 'apply-picks',
agent,
picks: [modelSwitchUnconfirmable ? { ...pick, adoptModelAsLaunchDefault: false } : pick]
})
}
})
if (!surface) {
return null
}
const entry: SurfaceEntry = {
agent,
canSwitchOmpModel: args.canSwitchOmpModel,
models: null,
surface
}
return entry
}
@@ -1,6 +1,7 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { clearNativeChatSessionOptionCacheForTests } from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache'
import type { RpcClient } from '../../../transport/rpc/rpc-client-contract'
import type { MobileSessionTab } from '../../tabs/mobile-session-tabs'
import { useMobileNativeChatSessionOptionController } from './use-mobile-native-chat-session-option-controller'
@@ -14,6 +15,7 @@ vi.mock('./mobile-native-chat-session-option-persistence', () => ({
describe('useMobileNativeChatSessionOptionController on a structured chat', () => {
let renderer: ReactTestRenderer | null = null
beforeEach(clearNativeChatSessionOptionCacheForTests)
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
@@ -52,84 +54,88 @@ describe('useMobileNativeChatSessionOptionController on a structured chat', () =
'compact'
])
})
it('keeps a capable blocked model pick away from message send and stale-draft healing', async () => {
const dispatchCommand = vi.fn()
const toggleTabChatView = vi.fn()
const onSendError = vi.fn()
const sendRequest = vi
.fn<RpcClient['sendRequest']>()
.mockImplementation(async (method, _params, options) => {
options?.beforeSend?.()
return {
ok: true,
id: 'reply',
result:
method === 'status.get'
? { capabilities: ['terminal.model-control.v1'] }
: { control: { outcome: 'blocked', reason: 'foreign-draft', agent: 'codex' } }
}
it.each([false, true])(
'keeps a capable blocked model pick away from message send and healing with late handle=%s',
async (lateHandle) => {
const dispatchCommand = vi.fn()
const toggleTabChatView = vi.fn()
const onSendError = vi.fn()
const sendRequest = vi
.fn<RpcClient['sendRequest']>()
.mockImplementation(async (method, _params, options) => {
options?.beforeSend?.()
return {
ok: true,
id: 'reply',
result:
method === 'status.get'
? { capabilities: ['terminal.model-control.v1'] }
: { control: { outcome: 'blocked', reason: 'foreign-draft', agent: 'codex' } }
}
})
const client: RpcClient = {
sendRequest,
subscribe: () => () => {},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => 1,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
const tab: MobileSessionTab = {
type: 'terminal',
id: 'codex-tab',
terminal: 'handle',
ptyId: 'pty',
title: 'Codex',
isActive: true,
launchAgent: 'codex'
}
const seen: {
current: ReturnType<typeof useMobileNativeChatSessionOptionController> | null
} = { current: null }
function Harness(): null {
seen.current = useMobileNativeChatSessionOptionController({
client,
activeChatStructured: false,
activeSessionTab: lateHandle ? { ...tab, terminal: undefined } : tab,
readSessionTab: () => tab,
activeHandleRef: { current: 'handle' },
activeSessionTabId: 'codex-tab',
agent: 'codex',
dispatchCommand,
onSendError,
deviceTokenRef: { current: 'device' },
terminalInputEnabled: true,
hostId: 'host',
isTabChatView: () => true,
isWorking: false,
reportedModel: null,
structured: { snapshot: [], pendingId: null, setOption: vi.fn(), invokeAction: vi.fn() },
toggleTabChatView,
worktreeId: 'worktree'
})
return null
}
act(() => {
renderer = create(createElement(Harness))
})
const client: RpcClient = {
sendRequest,
subscribe: () => () => {},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => 1,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
const tab: MobileSessionTab = {
type: 'terminal',
id: 'codex-tab',
terminal: 'handle',
ptyId: 'pty',
title: 'Codex',
isActive: true,
launchAgent: 'codex'
}
const seen: { current: ReturnType<typeof useMobileNativeChatSessionOptionController> | null } =
{ current: null }
function Harness(): null {
seen.current = useMobileNativeChatSessionOptionController({
client,
activeChatStructured: false,
activeSessionTab: tab,
readSessionTab: () => tab,
activeHandleRef: { current: 'handle' },
activeSessionTabId: 'codex-tab',
agent: 'codex',
dispatchCommand,
onSendError,
deviceTokenRef: { current: 'device' },
terminalInputEnabled: true,
hostId: 'host',
isTabChatView: () => true,
isWorking: false,
reportedModel: null,
structured: { snapshot: [], pendingId: null, setOption: vi.fn(), invokeAction: vi.fn() },
toggleTabChatView,
worktreeId: 'worktree'
await act(async () => {
expect(await seen.current!.nativeChatSessionOptions!.controller.invokeAction('model')).toBe(
false
)
})
return null
}
act(() => {
renderer = create(createElement(Harness))
})
await act(async () => {
expect(await seen.current!.nativeChatSessionOptions!.controller.invokeAction('model')).toBe(
false
expect(sendRequest.mock.calls.map(([method]) => method)).toEqual([
'status.get',
'terminal.model-control'
])
expect(dispatchCommand).not.toHaveBeenCalled()
expect(toggleTabChatView).not.toHaveBeenCalled()
expect(onSendError).toHaveBeenCalledExactlyOnceWith(
"Codex can't change options from Chat in this session."
)
})
expect(sendRequest.mock.calls.map(([method]) => method)).toEqual([
'status.get',
'terminal.model-control'
])
expect(dispatchCommand).not.toHaveBeenCalled()
expect(toggleTabChatView).not.toHaveBeenCalled()
expect(onSendError).toHaveBeenCalledExactlyOnceWith(
"Codex can't change options from Chat in this session."
)
})
}
)
})
@@ -1,6 +1,8 @@
import type { MobileNativeChatTab } from '../mobile-native-chat-eligibility'
import type { MobileSessionTab } from '../../tabs/mobile-session-tabs'
import type { NativeChatSessionOptionOwner } from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache'
import { readNativeChatSessionOptionSeedBinding } from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache'
import { createNativeChatSessionOptionOwner } from '../../../../../src/shared/native-chat/input/native-chat-session-option-owner'
import type { NativeChatSessionOptionBinding } from '../../../../../src/shared/native-chat/input/native-chat-session-option-binding'
import type { MutableRefObject } from 'react'
import type { RpcClient } from '../../../transport/rpc/rpc-client-contract'
@@ -119,6 +121,7 @@ export function useMobileNativeChatSessionOptionController(args: {
[client]
)
const selectedTab = args.activeSessionTab
const optionScopeKey = mobileNativeChatScopeKey(hostId, worktreeId, activeSessionTabId)
const owner = useMemo<NativeChatSessionOptionOwner | undefined>(() => {
if (!args.readSessionTab || !activeSessionTabId || !agent || selectedTab?.type !== 'terminal') {
return undefined
@@ -132,19 +135,21 @@ export function useMobileNativeChatSessionOptionController(args: {
incarnationId: tab.incarnationId,
providerSession: tab.agentStatus?.providerSession
})
return {
binding: { ...bindingFor(selectedTab), agent },
readCurrentBinding: () => {
const binding = { ...bindingFor(selectedTab), agent }
return createNativeChatSessionOptionOwner(
optionScopeKey ? readNativeChatSessionOptionSeedBinding(optionScopeKey, binding) : binding,
() => {
const tab = args.readSessionTab?.(activeSessionTabId)
return tab?.type === 'terminal' ? bindingFor(tab) : null
}
}
)
}, [
args.readSessionTab,
activeSessionTabId,
agent,
hostId,
worktreeId,
optionScopeKey,
selectedTab?.type,
selectedTab?.terminal,
selectedTab?.ptyId,
@@ -161,7 +166,10 @@ export function useMobileNativeChatSessionOptionController(args: {
if (args.terminalInputEnabled === false) {
return 'rejected' as const
}
const binding = owner?.binding
const binding = owner?.currentBinding()
if (owner && !binding) {
return 'rejected' as const
}
const clientId = args.deviceTokenRef?.current
if (
client &&
@@ -190,7 +198,7 @@ export function useMobileNativeChatSessionOptionController(args: {
}
},
isCurrent: () => {
const current = owner.readCurrentBinding()
const current = owner.currentBinding()
return (
current !== null &&
sameNativeChatSessionOptionBinding(binding, current) &&
@@ -219,14 +227,20 @@ export function useMobileNativeChatSessionOptionController(args: {
)
const sessionOptions = useMobileNativeChatSessionOptions({
owner,
isDispatchTargetCurrent: () =>
!owner ||
!args.activeHandleRef ||
args.activeHandleRef.current === owner.binding.terminalHandle,
isDispatchTargetCurrent: () => {
if (!owner) {
return true
}
const current = owner.currentBinding()
return (
current !== null &&
(!args.activeHandleRef || args.activeHandleRef.current === current.terminalHandle)
)
},
discoveredModels,
modelSwitchCommand: args.modelSwitchCommand,
agent: activeChatStructured ? null : agent,
scopeKey: mobileNativeChatScopeKey(hostId, worktreeId, activeSessionTabId),
scopeKey: optionScopeKey,
reportedModel,
dispatchCommand: dispatchOptionCommand,
onAgentPicker: handleAgentPicker,
@@ -1,3 +1,8 @@
import { createNativeChatSessionOptionOwner } from '../../../../../src/shared/native-chat/input/native-chat-session-option-owner'
import {
acquireNativeChatSessionOptionLease,
readNativeChatSessionOptionSeedBinding
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache'
import type { NativeChatSessionOptionBinding } from '../../../../../src/shared/native-chat/input/native-chat-session-option-binding'
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
@@ -47,7 +52,10 @@ describe('useMobileNativeChatSessionOptions', () => {
}
liveBindings.set(scopeKey, binding)
}
return { binding, readCurrentBinding: () => liveBindings.get(scopeKey) ?? null }
return createNativeChatSessionOptionOwner(
readNativeChatSessionOptionSeedBinding(scopeKey, binding),
() => liveBindings.get(scopeKey) ?? null
)
}
const mount = (overrides: Partial<HookArgs> = {}): void => {
@@ -221,9 +229,15 @@ describe('useMobileNativeChatSessionOptions', () => {
expect(effort?.kind).not.toMatchObject({ currentValue: 'low' })
})
it.each(['grok', 'codex'] as const)(
'isolates a same-agent %s successor from old pending UI and picker effects',
async (agent) => {
it.each([
['grok', 'known'],
['codex', 'known'],
['codex', 'canonical'],
['codex', 'selected'],
['codex', 'entry']
] as const)(
'isolates a same-agent %s successor from old pending UI and picker effects after %s identity',
async (agent, identitySource) => {
let accept!: (outcome: MobileNativeChatSendOutcome) => void
dispatchCommand.mockImplementationOnce(
() =>
@@ -239,7 +253,32 @@ describe('useMobileNativeChatSessionOptions', () => {
agent === 'grok'
? [initialModel, successorModel].map((id) => ({ id, label: id, options: [] }))
: undefined
mount({ agent, reportedModel: initialModel, writeSettings: writeOriginal, discoveredModels })
const scope = 'host\0worktree\0tab'
const identityA = {
agent,
terminalHandle: scope,
providerSession: { key: 'session_id' as const, id: 'A' }
}
liveBindings.set(
scope,
identitySource === 'selected' || identitySource === 'entry'
? { ...identityA, providerSession: undefined }
: identityA
)
const owner =
identitySource === 'known'
? undefined
: createNativeChatSessionOptionOwner(
{ agent, terminalHandle: scope },
() => liveBindings.get(scope) ?? null
)
mount({
agent,
owner,
reportedModel: initialModel,
writeSettings: writeOriginal,
discoveredModels
})
let accepted!: Promise<boolean>
await act(async () => {
accepted =
@@ -247,7 +286,23 @@ describe('useMobileNativeChatSessionOptions', () => {
await Promise.resolve()
})
expect(api!.pendingId).toBe('model')
const scope = hookArgs.scopeKey!
if (identitySource === 'entry') {
act(() => {
acquireNativeChatSessionOptionLease(
scope,
createNativeChatSessionOptionOwner(identityA, () => identityA)
)?.release()
})
expect(api!.pendingId).toBe('model')
}
if (identitySource === 'selected') {
liveBindings.set(scope, identityA)
update({ reportedModel: initialModel })
expect(api!.pendingId).toBe('model')
liveBindings.set(scope, { ...identityA, providerSession: undefined })
update({ reportedModel: initialModel })
expect(api!.pendingId).toBe('model')
}
liveBindings.set(scope, {
...liveBindings.get(scope)!,
providerSession: { key: 'session_id', id: 'successor' }
@@ -272,6 +327,55 @@ describe('useMobileNativeChatSessionOptions', () => {
}
)
it('routes a blocked action error only to its original active provider session', async () => {
const scope = 'host\0worktree\0tab'
const original = {
agent: 'codex',
terminalHandle: scope,
providerSession: { key: 'session_id' as const, id: 'A' }
}
liveBindings.set(scope, original)
const onControlError = vi.fn()
let reply!: (value: Awaited<ReturnType<HookArgs['dispatchCommand']>>) => void
dispatchCommand.mockImplementation(
() =>
new Promise((resolve) => {
reply = resolve
})
)
const owner = createNativeChatSessionOptionOwner(
{ agent: 'codex', terminalHandle: scope },
() => liveBindings.get(scope) ?? null
)
mount({ agent: 'codex', owner, onControlError })
let first!: Promise<boolean>
await act(async () => {
first = api!.invokeAction('model')
await Promise.resolve()
})
await act(async () => {
reply({ outcome: 'blocked', reason: 'foreign-draft', agent: 'codex' })
expect(await first).toBe(false)
})
expect(onControlError).toHaveBeenCalledOnce()
onControlError.mockClear()
let second!: Promise<boolean>
await act(async () => {
second = api!.invokeAction('model')
await Promise.resolve()
})
liveBindings.set(scope, { ...original, providerSession: { key: 'session_id', id: 'B' } })
update({})
expect(api!.pendingId).toBeNull()
liveBindings.set(scope, { agent: 'codex', terminalHandle: scope })
await act(async () => {
reply({ outcome: 'blocked', reason: 'foreign-draft', agent: 'codex' })
expect(await second).toBe(false)
})
expect(onControlError).not.toHaveBeenCalled()
expect(api!.pendingId).toBeNull()
})
it('does not revive a stale session-start report over a newer local pick', async () => {
mount({ reportedModel: 'claude-sonnet-5' })
await act(async () => {
@@ -285,6 +389,33 @@ describe('useMobileNativeChatSessionOptions', () => {
expect(api!.snapshot[0]!.kind).toMatchObject({ currentValue: 'opus' })
})
it('retains known report identity without replaying an unchanged model', async () => {
const scope = 'host\0worktree\0tab'
const unknown = { agent: 'claude', terminalHandle: scope }
liveBindings.set(scope, unknown)
mount({ reportedModel: 'claude-sonnet-5' })
await act(async () => {
await api!.setOption('model', 'opus')
})
act(() => {
const known = { ...unknown, providerSession: { key: 'session_id' as const, id: 'A' } }
acquireNativeChatSessionOptionLease(
scope,
createNativeChatSessionOptionOwner(known, () => known)
)?.release()
})
expect(api!.snapshot[0].kind).toMatchObject({ currentValue: 'opus' })
liveBindings.set(scope, { ...unknown, providerSession: { key: 'session_id', id: 'A' } })
update({ reportedModel: 'claude-sonnet-5' })
expect(api!.snapshot[0].kind).toMatchObject({ currentValue: 'opus' })
liveBindings.set(scope, unknown)
update({ reportedModel: 'claude-sonnet-5' })
expect(api!.snapshot[0].kind).toMatchObject({ currentValue: 'opus' })
liveBindings.set(scope, { ...unknown, providerSession: { key: 'session_id', id: 'B' } })
update({ reportedModel: 'claude-sonnet-5' })
expect(api!.snapshot[0].kind).toMatchObject({ currentValue: 'sonnet' })
})
it('keeps the live tab’s tracked model when other tabs overflow the record cap', async () => {
mount()
await act(async () => {
@@ -5,6 +5,8 @@ import {
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-apply-failure'
import {
sameNativeChatSessionOptionBinding,
enrichNativeChatSessionOptionBinding,
nativeChatSessionOptionBindingObservationsEqual,
type NativeChatSessionOptionBinding
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-binding'
import type { AgentSessionConversationCommand } from '../../../../../src/shared/agent-session/agent-session-conversation-command'
@@ -18,29 +20,23 @@ import {
useSyncExternalStore
} from 'react'
import { getAgentSessionOptionCatalog } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog'
import type { CatalogModel } from '../../../../../src/shared/agent-session/options/agent-session-option-catalog-types'
import type {
NativeChatSessionOptionSettingsMutation,
SessionOptionsSurface,
SessionOptionDescriptor,
SessionOptionValue
} from '../../../../../src/shared/native-chat/input/native-chat-session-options'
import type { MobileNativeChatSendOutcome } from '../mobile-native-chat-send'
import type {
NativeChatSessionOptionDispatchOptions,
NativeChatSessionOptionDispatchResult
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-dispatch'
import {
createNativeChatPtySessionOptions,
type NativeChatPtySessionOptionsSurface
} from '../../../../../src/shared/native-chat/input/native-chat-pty-session-options'
import type { NativeChatPtySessionOptionsSurface } from '../../../../../src/shared/native-chat/input/native-chat-pty-session-options'
import {
clearNativeChatSessionOptionCacheForTests,
readNativeChatSessionOptionSeedBinding,
type NativeChatSessionOptionOwner
} from '../../../../../src/shared/native-chat/input/native-chat-session-option-cache'
import { matchNativeChatCatalogModelId } from '../../../../../src/shared/native-chat/input/native-chat-session-option-state'
import { setBoundedScopeCacheEntry } from '../../../../../src/shared/native-chat/native-chat-scope-cache'
import { sayMobileNativeChatSessionOption } from './native-chat-session-option-copy'
import {
createMobileSurfaceEntry,
type MobileNativeChatSessionOptionsArgs as HookArgs
} from './mobile-native-chat-session-option-surface'
export type MobileNativeChatSessionOptionsController = {
optionSurface?: SessionOptionsSurface
@@ -64,34 +60,15 @@ type PendingOperation = {
owner?: NativeChatSessionOptionOwner
id: string
}
type SurfaceEntry = {
agent: string
canSwitchOmpModel: boolean
surface: NativeChatPtySessionOptionsSurface
/** The discovered list last handed to the surface. */
models: readonly CatalogModel[] | null
}
type HookArgs = {
agent: string | null
owner?: NativeChatSessionOptionOwner
isDispatchTargetCurrent?: () => boolean
scopeKey: string | null
reportedModel: string | null
discoveredModels?: CatalogModel[] | null
modelSwitchCommand?: string
dispatchCommand: (
command: string,
options?: NativeChatSessionOptionDispatchOptions
) => Promise<MobileNativeChatSendOutcome | NativeChatSessionOptionDispatchResult>
onAgentPicker?: () => void
onControlError?: (message: string) => void
/** Saves picks as the host's launch defaults, as desktop does. */
writeSettings?: (mutation: NativeChatSessionOptionSettingsMutation) => void
type PendingObservation = {
operation: PendingOperation
binding?: NativeChatSessionOptionBinding
}
const EMPTY_SNAPSHOT: SessionOptionDescriptor[] = []
const subscribeEmpty = (): (() => void) => () => {}
const getEmptySnapshot = (): SessionOptionDescriptor[] => EMPTY_SNAPSHOT
const getEmptyBinding = (): undefined => undefined
// Kept across remounts: a repeated hook model is not fresh evidence, and reapplying it would revert a newer pick.
const appliedReportByScope = new Map<
@@ -104,73 +81,6 @@ export function clearMobileSessionOptionRecordsForTests(): void {
appliedReportByScope.clear()
}
function createMobileSurfaceEntry(args: {
agent: string
scopeKey: string
identity: string
canSwitchOmpModel: boolean
latest: { readonly current: HookArgs }
activeIdentity: { readonly current: string | null }
captured: HookArgs
}): SurfaceEntry | null {
const { agent, identity, latest, activeIdentity } = args
const midSession = getAgentSessionOptionCatalog(agent)?.modelApply.midSession
// Phone-only: desktop confirms a Claude model switch on its terminal screen; the phone cannot, so it never saves one as a launch default.
const modelSwitchUnconfirmable =
midSession?.kind === 'command' && midSession.detectAgentInteraction !== undefined
const surface = createNativeChatPtySessionOptions({
agent,
owner: args.captured.owner,
scopeKey: args.scopeKey,
mode: 'live',
modelLabel: sayMobileNativeChatSessionOption('model'),
canSwitchOmpModel: args.canSwitchOmpModel,
dispatchCommand: async (command, options) => {
// One controller serves every tab: a queued pick must not reach the tab opened since.
if (
activeIdentity.current !== identity ||
args.captured.isDispatchTargetCurrent?.() === false
) {
throw new Error('The chat changed before the command was sent.')
}
const outcome = await args.captured.dispatchCommand(command, options)
if (typeof outcome === 'object') {
return outcome
}
// Desktop commits a pick only after the terminal confirms the write.
if (outcome === 'rejected' || outcome === 'unknown') {
throw new Error('The terminal did not accept the command.')
}
},
onAgentPicker: () => {
if (activeIdentity.current === identity) {
latest.current.onAgentPicker?.()
}
},
persistSelection: (pick) => {
// A pick that lands after the phone moved to another host's chat must not become that host's default.
if (modelSwitchUnconfirmable && pick.optionId === 'model') {
return
}
args.captured.writeSettings?.({
type: 'apply-picks',
agent,
picks: [modelSwitchUnconfirmable ? { ...pick, adoptModelAsLaunchDefault: false } : pick]
})
}
})
if (!surface) {
return null
}
const entry: SurfaceEntry = {
agent,
canSwitchOmpModel: args.canSwitchOmpModel,
models: null,
surface
}
return entry
}
export function useMobileNativeChatSessionOptions(
args: HookArgs
): MobileNativeChatSessionOptionsController {
@@ -180,7 +90,34 @@ export function useMobileNativeChatSessionOptions(
const canSwitchOmpModel = args.modelSwitchCommand === 'orca-model'
const latest = useRef(args)
const activeIdentityRef = useRef(identity)
const [pending, setPending] = useState<PendingOperation | null>(null)
const [pending, setPending] = useState<PendingObservation | null>(null)
const ownerObservation = useSyncExternalStore(
args.owner?.subscribe ?? subscribeEmpty,
args.owner?.getSnapshot ?? getEmptyBinding,
args.owner?.getSnapshot ?? getEmptyBinding
)
const pendingOwner = pending?.operation.owner
const pendingObservation = useSyncExternalStore(
pendingOwner?.subscribe ?? subscribeEmpty,
pendingOwner?.getSnapshot ?? getEmptyBinding,
pendingOwner?.getSnapshot ?? getEmptyBinding
)
let selectedPending = pending
if (pending?.binding && pendingObservation) {
if (sameNativeChatSessionOptionBinding(pending.binding, pendingObservation)) {
const binding = enrichNativeChatSessionOptionBinding(pending.binding, pendingObservation)
if (!nativeChatSessionOptionBindingObservationsEqual(pending.binding, binding)) {
selectedPending = { ...pending, binding }
setPending(selectedPending)
}
}
}
useLayoutEffect(() => {
if (selectedPending?.binding) {
selectedPending.operation.owner?.captureBinding(selectedPending.binding)
}
}, [selectedPending])
useLayoutEffect(() => {
latest.current = args
@@ -216,6 +153,9 @@ export function useMobileNativeChatSessionOptions(
args.writeSettings
])
const surface = entry?.surface ?? null
useLayoutEffect(() => {
surface?.reconcileOwner()
}, [surface, ownerObservation])
useEffect(() => {
if (entry && discoveredModels && entry.models !== discoveredModels) {
@@ -239,19 +179,47 @@ export function useMobileNativeChatSessionOptions(
{ allowUnlisted: agent === 'codex' }
)
const previous = appliedReportByScope.get(scopeKey)
const captured = args.owner?.currentBinding()
if (args.owner && !captured) {
return
}
const observed = captured ?? undefined
const sameOwner =
!previous?.binding ||
!args.owner ||
sameNativeChatSessionOptionBinding(previous.binding, args.owner.binding)
if (!matched || (sameOwner && previous?.model === matched)) {
!observed ||
sameNativeChatSessionOptionBinding(previous.binding, observed)
if (!matched) {
return
}
const binding =
sameOwner && previous?.binding && observed
? enrichNativeChatSessionOptionBinding(previous.binding, observed)
: observed
if (sameOwner && previous?.model === matched) {
if (
binding &&
(!previous.binding ||
!nativeChatSessionOptionBindingObservationsEqual(previous.binding, binding))
) {
setBoundedScopeCacheEntry(appliedReportByScope, scopeKey, { model: matched, binding })
}
return
}
setBoundedScopeCacheEntry(appliedReportByScope, scopeKey, {
model: matched,
binding: args.owner?.binding
binding
})
surface.reportSessionOptions({ model: matched })
}, [agent, catalog, discoveredModels, reportedModel, scopeKey, surface, args.owner])
}, [
agent,
catalog,
discoveredModels,
reportedModel,
scopeKey,
surface,
args.owner,
ownerObservation
])
const snapshot = useSyncExternalStore(
surface?.subscribe ?? subscribeEmpty,
@@ -265,20 +233,30 @@ export function useMobileNativeChatSessionOptions(
return Promise.resolve(false)
}
const operation = { identity, surface, owner: args.owner, id }
setPending(operation)
setPending({
operation,
binding:
args.owner?.currentBinding() ??
(args.owner && scopeKey
? readNativeChatSessionOptionSeedBinding(scopeKey, args.owner.binding)
: undefined)
})
return run(surface)
.then(
() => true,
(error: unknown) => {
const currentBinding = operation.owner?.readCurrentBinding()
const currentBinding = latest.current.owner?.currentBinding()
if (
error instanceof SessionOptionApplyError &&
(error.code === 'controlUnavailable' || error.code === 'controlNotSent') &&
activeIdentityRef.current === operation.identity &&
args.isDispatchTargetCurrent?.() !== false &&
latest.current.isDispatchTargetCurrent?.() !== false &&
(!operation.owner ||
(currentBinding &&
sameNativeChatSessionOptionBinding(operation.owner.binding, currentBinding)))
sameNativeChatSessionOptionBinding(
operation.owner.getSnapshot(),
currentBinding
)))
) {
latest.current.onControlError?.(
translate(
@@ -292,10 +270,10 @@ export function useMobileNativeChatSessionOptions(
}
)
.finally(() => {
setPending((current) => (current === operation ? null : current))
setPending((current) => (current?.operation === operation ? null : current))
})
},
[identity, surface, args.owner]
[identity, surface, args.owner, scopeKey]
)
const setOption = useCallback(
(id: string, value: SessionOptionValue) => track(id, (target) => target.setOption(id, value)),
@@ -310,12 +288,12 @@ export function useMobileNativeChatSessionOptions(
[surface]
)
const pendingId =
pending &&
pending.identity === identity &&
(pending.owner && args.owner
? sameNativeChatSessionOptionBinding(pending.owner.binding, args.owner.binding)
: pending.surface === surface)
? pending.id
selectedPending &&
selectedPending.operation.identity === identity &&
(selectedPending.binding && ownerObservation
? sameNativeChatSessionOptionBinding(selectedPending.binding, ownerObservation)
: selectedPending.operation.surface === surface)
? selectedPending.operation.id
: null
return useMemo(
@@ -144,7 +144,7 @@ export function useNativeChatPtyComposerSend(args: {
onEvidenceMode: (source) => {
sourceEvidence = source
if (pendingId) {
args.optimisticSendOutcome?.useSourceEvidence?.(pendingId, source)
args.optimisticSendOutcome?.setSourceEvidence?.(pendingId, source)
}
}
})
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { createElement } from 'react'
import { createElement, useLayoutEffect } from 'react'
import { act, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store/index'
@@ -9,6 +9,12 @@ import type { Worktree } from '../../../../../../../shared/worktree/types'
import { createGlobalSettingsFixture } from '../../../../../../../shared/global-settings-test-fixture'
import { makeTab } from '../../../../../store/terminals/terminal-tab.test-fixture'
import { useNativeChatSessionOptionOwner } from './native-chat-session-option-owner'
import { createNativeChatPtySessionOptions } from '../../../../../../../shared/native-chat/input/native-chat-pty-session-options'
import { createNativeChatSessionOptionOwner } from '../../../../../../../shared/native-chat/input/native-chat-session-option-owner'
import {
acquireNativeChatSessionOptionLease,
clearNativeChatSessionOptionCacheForTests
} from '../../../../../../../shared/native-chat/input/native-chat-session-option-cache'
// The sidebar's separate catalog index is outside the owner-index measurement.
vi.mock('@/store/slices/ui/settled-sort-epoch', () => ({ installSettledSortEpoch: vi.fn() }))
@@ -48,7 +54,10 @@ function worktree(index: number): Worktree {
}
describe('terminal option owner catalog invalidation', () => {
afterEach(() => useAppStore.setState(initialState, true))
afterEach(() => {
useAppStore.setState(initialState, true)
clearNativeChatSessionOptionCacheForTests()
})
it.each([10, 100])(
'shares catalog indexing across %i mounted panes and updates only the changed owner',
@@ -68,14 +77,47 @@ describe('terminal option owner catalog invalidation', () => {
})
const renders = Array.from({ length: count }, () => 0)
const connections: (string | null | undefined)[] = []
const sessions: (string | undefined)[] = []
const bindingReads = Array.from({ length: count }, () => 0)
function Probe({ index }: { index: number }): null {
renders[index]++
const owner = useNativeChatSessionOptionOwner({
const { owner } = useNativeChatSessionOptionOwner({
agent: 'grok',
terminalTabId: `tab-${index}`,
targetPtyId: `pty-${index}`
})
connections[index] = owner?.binding.connectionId
useLayoutEffect(() => {
connections[index] = owner?.currentBinding()?.connectionId
sessions[index] = owner?.getSnapshot().providerSession?.id
})
useLayoutEffect(() => {
if (!owner) {
return
}
const attach = owner.attach
const observed = vi.spyOn(owner, 'attach').mockImplementation((source) =>
attach({
...source,
getBindingSnapshot: () => {
bindingReads[index]++
return source.getBindingSnapshot()
}
})
)
const surface = createNativeChatPtySessionOptions({
agent: 'grok',
owner,
scopeKey: `pty-${index}`,
mode: 'live',
modelLabel: 'Model',
dispatchCommand: () => undefined
})!
const release = surface.subscribe(() => {})
return () => {
release()
observed.mockRestore()
}
}, [owner, index])
return null
}
const mounted = render(
@@ -145,6 +187,30 @@ describe('terminal option owner catalog invalidation', () => {
expect(renders[0]).toBeGreaterThan(0)
expect(connections[0]).toBe('ssh-owner')
expect(renders.slice(1)).toEqual(Array.from({ length: count - 1 }, () => 0))
renders.fill(0)
bindingReads.fill(0)
const known = {
agent: 'grok',
connectionId: 'ssh-owner',
worktreeId: rows[0].id,
ptyId: 'pty-0',
providerSession: { key: 'session_id' as const, id: 'A' }
}
const source = createNativeChatSessionOptionOwner(known, () => known)
act(() => acquireNativeChatSessionOptionLease('pty-0', source)?.release())
expect(sessions[0]).toBe('A')
expect(renders[0]).toBeGreaterThan(0)
expect(renders.slice(1)).toEqual(Array.from({ length: count - 1 }, () => 0))
expect(bindingReads[0]).toBeGreaterThan(0)
// One source notification and up to two commit reads; unrelated entries are never read.
expect(bindingReads[0]).toBeLessThanOrEqual(3)
expect(bindingReads.slice(1)).toEqual(Array.from({ length: count - 1 }, () => 0))
renders.fill(0)
bindingReads.fill(0)
act(() => acquireNativeChatSessionOptionLease('pty-0', source)?.release())
expect(renders).toEqual(Array.from({ length: count }, () => 0))
expect(bindingReads).toEqual(Array.from({ length: count }, () => 0))
mounted.unmount()
}
)
@@ -1,10 +1,15 @@
import { useLayoutEffect, useMemo, useRef } from 'react'
import { useLayoutEffect, useMemo, useState, useSyncExternalStore } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { useAppStore } from '../../../../../store/index'
import type { NativeChatSessionOptionOwner } from '../../../../../../../shared/native-chat/input/native-chat-session-option-cache'
import { readNativeChatSessionOptionSeedBinding } from '../../../../../../../shared/native-chat/input/native-chat-session-option-cache'
import {
createNativeChatSessionOptionOwner,
type NativeChatSessionOptionOwner
} from '../../../../../../../shared/native-chat/input/native-chat-session-option-owner'
import {
sameNativeChatSessionOptionBinding,
enrichNativeChatSessionOptionBinding
enrichNativeChatSessionOptionBinding,
nativeChatSessionOptionBindingObservationsEqual
} from '../../../../../../../shared/native-chat/input/native-chat-session-option-binding'
import type { AppState } from '../../../../../store/types'
import type { NativeChatSessionOptionBinding } from '../../../../../../../shared/native-chat/input/native-chat-session-option-binding'
@@ -12,6 +17,9 @@ import { parsePaneKey } from '../../../../../../../shared/workspace-layout/stabl
import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution'
import { getTerminalTabOwnerWorktreeId } from '@/store/terminals/terminal-tab-owner-index'
const subscribeEmpty = (): (() => void) => () => {}
const getEmptySnapshot = (): undefined => undefined
export function readNativeChatSessionOptionBinding(
state: AppState,
target: { agent: string; terminalTabId: string; worktreeId: string; paneKey?: string }
@@ -45,8 +53,9 @@ export function useNativeChatSessionOptionOwner(args: {
terminalTabId: string
targetPtyId: string | null
paneKey?: string
}): NativeChatSessionOptionOwner | undefined {
}): { owner: NativeChatSessionOptionOwner | undefined; targetAvailable: boolean } {
const { agent, terminalTabId, targetPtyId, paneKey } = args
const leaf = paneKey ? parsePaneKey(paneKey) : null
const fields = useAppStore(
useShallow((state) => {
const worktreeId = getTerminalTabOwnerWorktreeId(state.tabsByWorktree, terminalTabId)
@@ -58,39 +67,80 @@ export function useNativeChatSessionOptionOwner(args: {
status?.providerSession?.key,
status?.providerSession?.id,
status?.providerSession?.transcriptPath,
worktreeId
worktreeId,
leaf
? state.terminalLayoutsByTabId[terminalTabId]?.ptyIdsByLeafId?.[leaf.leafId]
: targetPtyId
] as const
})
)
const worktreeId = fields[6]
const targetKey = `${worktreeId}\0${terminalTabId}\0${paneKey ?? ''}`
const previous = useRef<{ targetKey: string; owner: NativeChatSessionOptionOwner } | null>(null)
const owner = useMemo(() => {
if (!targetPtyId) {
return undefined
}
const target = worktreeId ? { agent, terminalTabId, worktreeId, paneKey } : null
const readCurrentBinding = () =>
target ? readNativeChatSessionOptionBinding(useAppStore.getState(), target) : null
const binding = {
...readCurrentBinding(),
const candidate = useMemo<NativeChatSessionOptionBinding>(
() => ({
agent,
ptyId: targetPtyId,
terminalHandle: fields[1]
}
return previous.current?.targetKey === targetKey &&
sameNativeChatSessionOptionBinding(previous.current.owner.binding, binding)
? previous.current.owner
: { binding, readCurrentBinding }
}, [agent, terminalTabId, targetPtyId, worktreeId, paneKey, fields, targetKey])
useLayoutEffect(() => {
if (owner) {
const current = owner.readCurrentBinding()
if (current && sameNativeChatSessionOptionBinding(owner.binding, current)) {
owner.binding = enrichNativeChatSessionOptionBinding(owner.binding, current)
terminalHandle: fields[1],
connectionId: fields[2],
worktreeId: worktreeId ?? undefined,
providerSession:
fields[3] && fields[4] !== undefined
? { key: fields[3], id: fields[4], transcriptPath: fields[5] }
: undefined
}),
[agent, targetPtyId, worktreeId, fields]
)
const [held, setHeld] = useState<{
targetKey: string
observation: NativeChatSessionOptionBinding
owner: NativeChatSessionOptionOwner
} | null>(null)
const domainObservation = useSyncExternalStore(
held?.owner.subscribe ?? subscribeEmpty,
held?.owner.getSnapshot ?? getEmptySnapshot,
held?.owner.getSnapshot ?? getEmptySnapshot
)
let selected = held
if (!targetPtyId) {
selected = null
} else {
const previous =
held?.targetKey === targetKey
? enrichNativeChatSessionOptionBinding(
held.observation,
domainObservation ?? held.observation
)
: null
if (!held || !previous || !sameNativeChatSessionOptionBinding(previous, candidate)) {
const observation = readNativeChatSessionOptionSeedBinding(targetPtyId, candidate)
const target = worktreeId ? { agent, terminalTabId, worktreeId, paneKey } : null
selected = {
targetKey,
observation,
owner: createNativeChatSessionOptionOwner(observation, () =>
target ? readNativeChatSessionOptionBinding(useAppStore.getState(), target) : null
)
}
} else {
const observation = enrichNativeChatSessionOptionBinding(previous, candidate)
if (!nativeChatSessionOptionBindingObservationsEqual(held.observation, observation)) {
selected = { ...held, observation }
}
}
previous.current = owner ? { targetKey, owner } : null
}, [owner, fields, targetKey])
return owner
}
if (selected !== held) {
setHeld(selected)
}
const owner = selected?.owner
const observation = selected?.observation
useLayoutEffect(() => {
if (observation) {
owner?.captureBinding(observation)
}
owner?.currentBinding()
}, [owner, observation, fields])
return {
owner,
targetAvailable: Boolean(worktreeId && targetPtyId && fields[7] === targetPtyId)
}
}
@@ -1,11 +1,20 @@
// @vitest-environment happy-dom
import { createElement, useSyncExternalStore } from 'react'
import { act, render, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
createElement,
StrictMode,
Suspense,
startTransition,
useLayoutEffect,
useSyncExternalStore
} from 'react'
import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CatalogModel } from '../../../../../../../shared/agent-session/options/agent-session-option-catalog-types'
import { clearNativeChatSessionOptionCacheForTests } from '../../../../../../../shared/native-chat/input/native-chat-session-option-cache'
import { createNativeChatSessionOptionOwner } from '../../../../../../../shared/native-chat/input/native-chat-session-option-owner'
import { createNativeChatPtySessionOptions } from '../../../../../../../shared/native-chat/input/native-chat-pty-session-options'
import { clearNativeChatModelEnrichmentForTests } from '../catalog/native-chat-session-option-enrichment'
const discoverModels = vi.fn<() => Promise<readonly CatalogModel[] | null>>()
@@ -91,6 +100,7 @@ function modelDescriptor(snapshot: { id: string; kind: unknown }[]): {
}
describe('useNativeChatSessionOptions model reporting', () => {
afterEach(cleanup)
beforeEach(() => {
clearNativeChatModelEnrichmentForTests()
clearNativeChatSessionOptionCacheForTests()
@@ -202,16 +212,19 @@ describe('useNativeChatSessionOptions model reporting', () => {
storeState.agentStatusByPaneKey[paneKey] = { agentType: agent, model: 'grok-4.7' }
const dispatchCommand = vi.fn()
const readTerminalScreen = () => CLAUDE_SCREEN
const { result, unmount } = renderHook(() =>
useNativeChatSessionOptions({
agent,
terminalTabId: 'tab-1',
targetPtyId: 'pty-1',
paneKey,
dispatchCommand,
readTerminalScreen
})
const { result, unmount } = renderHook(
() =>
useNativeChatSessionOptions({
agent,
terminalTabId: 'tab-1',
targetPtyId: 'pty-1',
paneKey,
dispatchCommand,
readTerminalScreen
}),
{ wrapper: StrictMode }
)
const originalSurface = result.current.surface
await act(async () => {
await Promise.resolve()
})
@@ -230,6 +243,18 @@ describe('useNativeChatSessionOptions model reporting', () => {
}
})
expect(modelDescriptor(result.current.snapshot).currentValue).toBe(pick)
expect(result.current.surface).toBe(originalSurface)
act(() => {
storeState.agentStatusByPaneKey[paneKey] = {
...storeState.agentStatusByPaneKey[paneKey],
providerSession: undefined
}
for (const listener of storeListeners) {
listener()
}
})
expect(modelDescriptor(result.current.snapshot).currentValue).toBe(pick)
expect(result.current.surface).toBe(originalSurface)
act(() => {
storeState.agentStatusByPaneKey[paneKey] = {
...storeState.agentStatusByPaneKey[paneKey],
@@ -301,34 +326,146 @@ describe('useNativeChatSessionOptions model reporting', () => {
}
)
it('keeps the actual target usable when discovery is unavailable and ownership later resolves', async () => {
discoveryUnavailable = true
currentConnectionId = undefined
storeState.tabsByWorktree = {}
it.each(['tab', 'leaf'])(
'keeps the actual target usable when discovery is unavailable and %s ownership later resolves',
async (target) => {
discoveryUnavailable = true
currentConnectionId = undefined
if (target === 'tab') {
storeState.tabsByWorktree = {}
}
const paneKey = target === 'leaf' ? 'tab-1:00000000-0000-4000-8000-000000000001' : undefined
const dispatchCommand = vi.fn()
const { result, rerender, unmount } = renderHook(() =>
useNativeChatSessionOptions({
agent: 'grok',
terminalTabId: 'tab-1',
targetPtyId: 'pty-1',
paneKey,
dispatchCommand
})
)
act(() => {
storeState.tabsByWorktree = { 'worktree-1': [{ id: 'tab-1', ptyId: 'pty-1' }] }
if (paneKey) {
storeState.terminalLayoutsByTabId['tab-1'] = {
ptyIdsByLeafId: { [paneKey.split(':')[1]]: 'pty-1' }
}
}
for (const listener of storeListeners) {
listener()
}
})
await act(async () => {
await result.current.surface!.setOption('model', 'grok-4.7-fast')
})
currentConnectionId = null
rerender()
await act(async () => {
await result.current.surface!.setOption('model', 'grok-4.7')
})
expect(dispatchCommand).toHaveBeenCalledTimes(2)
expect(modelDescriptor(result.current.snapshot).currentValue).toBe('grok-4.7')
unmount()
}
)
it('fences admission with a known seed committed while canonical metadata is missing', async () => {
discoverModels.mockResolvedValue(null)
const paneKey = 'tab-1:00000000-0000-4000-8000-000000000001'
storeState.terminalLayoutsByTabId['tab-1'] = {
ptyIdsByLeafId: { [paneKey.split(':')[1]]: 'pty-1' }
}
storeState.agentStatusByPaneKey[paneKey] = { agentType: 'grok' }
const dispatchCommand = vi.fn()
const { result, rerender, unmount } = renderHook(() =>
const { result, unmount } = renderHook(() =>
useNativeChatSessionOptions({
agent: 'grok',
terminalTabId: 'tab-1',
targetPtyId: 'pty-1',
paneKey,
dispatchCommand
})
)
storeState.tabsByWorktree = { 'worktree-1': [{ id: 'tab-1', ptyId: 'pty-1' }] }
rerender()
const original = result.current.surface!
const known = {
agent: 'grok',
connectionId: null,
worktreeId: 'worktree-1',
ptyId: 'pty-1',
providerSession: { key: 'session_id' as const, id: 'A' }
}
const other = createNativeChatPtySessionOptions({
agent: 'grok',
owner: createNativeChatSessionOptionOwner(known, () => known),
scopeKey: 'pty-1',
mode: 'live',
modelLabel: 'Model',
dispatchCommand: vi.fn()
})!
let release = (): void => {}
await act(async () => {
release = other.subscribe(() => {})
expect(result.current.surface).toBe(original)
storeState.agentStatusByPaneKey[paneKey] = {
agentType: 'grok',
providerSession: { key: 'session_id', id: 'B' }
}
await expect(original.setOption('model', 'grok-4.7-fast')).rejects.toThrow()
})
expect(dispatchCommand).not.toHaveBeenCalled()
act(() => {
for (const listener of storeListeners) {
listener()
}
})
expect(result.current.surface).not.toBe(original)
await act(async () => {
await result.current.surface!.setOption('model', 'grok-4.7-fast')
})
currentConnectionId = null
rerender()
await act(async () => {
await result.current.surface!.setOption('model', 'grok-4.7')
})
expect(dispatchCommand).toHaveBeenCalledTimes(2)
expect(modelDescriptor(result.current.snapshot).currentValue).toBe('grok-4.7')
expect(dispatchCommand).toHaveBeenCalledOnce()
release()
unmount()
})
it('keeps the committed session usable after a replacement render is discarded', async () => {
discoverModels.mockResolvedValue(null)
const dispatchCommand = vi.fn()
let committed: ReturnType<typeof useNativeChatSessionOptions> | undefined
const suspended = new Promise<never>(() => {})
function Probe({ replace }: { replace: boolean }): null {
const options = useNativeChatSessionOptions({
agent: replace ? 'claude' : 'grok',
terminalTabId: 'tab-1',
targetPtyId: 'pty-1',
dispatchCommand
})
useLayoutEffect(() => {
committed = options
})
if (replace) {
throw suspended
}
return null
}
const view = (replace: boolean) =>
createElement(Suspense, { fallback: null }, createElement(Probe, { replace }))
const mounted = render(view(false))
const original = committed!.surface!
await act(async () => {
await original.setOption('model', 'grok-4.7-fast')
})
act(() => startTransition(() => mounted.rerender(view(true))))
expect(committed!.surface).toBe(original)
expect(modelDescriptor(original.getSnapshot()).currentValue).toBe('grok-4.7-fast')
await act(async () => {
await original.setOption('model', 'grok-4.7')
})
expect(modelDescriptor(original.getSnapshot()).currentValue).toBe('grok-4.7')
expect(dispatchCommand).toHaveBeenCalledTimes(2)
mounted.unmount()
})
it.each([10, 100])('does not render unaffected model consumers among %i panes', async (count) => {
discoverModels.mockResolvedValue(null)
const dispatchCommand = vi.fn()
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'
import { useEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react'
import { useNativeChatSessionOptionOwner } from './native-chat-session-option-owner'
import type { AgentType } from '../../../../../../../shared/agent-status/contracts/agent-status-types'
import { getAgentSessionOptionCatalog } from '../../../../../../../shared/agent-session/options/agent-session-option-catalog'
@@ -66,7 +66,12 @@ export function useNativeChatSessionOptions(args: {
() => resolveNativeChatModelDiscoveryContext(terminalTabId),
[terminalTabId]
)
const owner = useNativeChatSessionOptionOwner({ agent, terminalTabId, targetPtyId, paneKey })
const { owner, targetAvailable } = useNativeChatSessionOptionOwner({
agent,
terminalTabId,
targetPtyId,
paneKey
})
const surface = useMemo(() => {
// Chat attaches after startup is queued, so a draft picker could no longer change its command.
if (!targetPtyId) {
@@ -224,5 +229,10 @@ export function useNativeChatSessionOptions(args: {
surface?.getSnapshot ?? getEmptySnapshot,
surface?.getSnapshot ?? getEmptySnapshot
)
useLayoutEffect(() => {
if (targetAvailable) {
surface?.reconcileOwner()
}
}, [surface, targetAvailable])
return { surface, snapshot }
}
@@ -1,6 +1,6 @@
export type NativeChatOptimisticSendOutcome = {
/** The host refused the write: mark the echo "Message not sent". */
useSourceEvidence?: (pendingId: string, source: boolean) => void
setSourceEvidence?: (pendingId: string, source: boolean) => void
finishSourceEvidence?: (pendingId: string) => void
reject: (pendingId: string) => void
/** The write acknowledgment was lost: hold the echo, then flag it unconfirmed. */
@@ -121,7 +121,7 @@ it('keeps a new old-host Send behind its visible window after a disjoint reconne
let id = ''
act(() => {
id = mounted.result.current.record('repeat', undefined, false, 'claude')
mounted.result.current.useSourceEvidence(id, false)
mounted.result.current.setSourceEvidence(id, false)
})
expect(mounted.result.current.pending.map((entry) => entry.id)).toEqual([id])
const unrelated = { ...userRow('other'), id: 'unrelated', timestamp: 4100 }
@@ -312,7 +312,7 @@ it.each([true, false])(
let id = ''
act(() => {
id = mounted.result.current.record('repeat', undefined, false, 'opencode')
mounted.result.current.useSourceEvidence(id, source)
mounted.result.current.setSourceEvidence(id, source)
})
const old = [
{ ...sourceRow('repeat', 'old-user'), timestamp: 500 },
@@ -342,9 +342,9 @@ it('assigns identical legacy occurrences at the real capability fallback and nev
act(() => {
one = first.result.current.record('repeat', undefined, false, 'opencode')
two = first.result.current.record('repeat', undefined, false, 'opencode')
first.result.current.useSourceEvidence(one, false)
first.result.current.useSourceEvidence(two, false)
first.result.current.useSourceEvidence(two, false)
first.result.current.setSourceEvidence(one, false)
first.result.current.setSourceEvidence(two, false)
first.result.current.setSourceEvidence(two, false)
})
const messages = [sourceRow('repeat', 'x'), { ...boundary, id: 'answer' }]
first.rerender({ messages })
@@ -367,15 +367,15 @@ it('transfers spent ownership to a reachable fallback glue witness, then retires
two = ''
act(() => {
source = first.result.current.record('first second', undefined, false, 'opencode')
first.result.current.useSourceEvidence(source, true)
first.result.current.setSourceEvidence(source, true)
one = first.result.current.record('first', undefined, false, 'opencode')
two = first.result.current.record('second', undefined, false, 'opencode')
})
const x = sourceRow('first second', 'x')
first.rerender({ messages: [x] })
act(() => {
first.result.current.useSourceEvidence(one, false)
first.result.current.useSourceEvidence(two, false)
first.result.current.setSourceEvidence(one, false)
first.result.current.setSourceEvidence(two, false)
})
const messages = [x, { ...boundary, id: 'answer' }]
first.rerender({ messages })
@@ -408,7 +408,7 @@ it('releases dead fallback group dependencies and does not accumulate receipts b
for (let index = 0; index < 20; index++) {
act(() => {
const id = mounted.result.current.record(`later-${index}`, undefined, false, 'opencode')
mounted.result.current.useSourceEvidence(id, true)
mounted.result.current.setSourceEvidence(id, true)
})
mounted.rerender({
messages: [sourceRow(`later-${index}`, `u${index}`), { ...boundary, id: `a${index}` }]
@@ -433,8 +433,8 @@ it('keeps a committed source lock through a late real fallback and prevents lega
const x = sourceRow('first second', 'x')
mounted.rerender({ messages: [x] })
act(() => {
mounted.result.current.useSourceEvidence(owner, false)
mounted.result.current.useSourceEvidence(continuation, false)
mounted.result.current.setSourceEvidence(owner, false)
mounted.result.current.setSourceEvidence(continuation, false)
})
mounted.rerender({ messages: [x, { ...boundary, id: 'answer' }] })
expect(mounted.result.current.pending.map((entry) => entry.id)).toEqual([continuation])
@@ -502,12 +502,12 @@ it.each(['repeat', 'repeat '])(
replacement = ''
act(() => {
rejected = mounted.result.current.record(failedText, undefined, false, 'opencode')
mounted.result.current.useSourceEvidence(rejected, false)
mounted.result.current.setSourceEvidence(rejected, false)
mounted.result.current.reject(rejected)
})
act(() => {
replacement = mounted.result.current.record('repeat', undefined, false, 'opencode')
mounted.result.current.useSourceEvidence(replacement, false)
mounted.result.current.setSourceEvidence(replacement, false)
})
expect(mounted.result.current.pending.map((entry) => entry.id)).toEqual([replacement])
mounted.rerender({ messages: [sourceRow('repeat', 'new'), { ...boundary, id: 'answer' }] })
@@ -106,7 +106,7 @@ export function useNativeChatPendingDelivery(args: {
},
[messages, readEmptySessionId, scope, workingEpoch, sessionId]
)
const useSourceEvidence = useCallback(
const setSourceEvidence = useCallback(
(id: string, source: boolean) =>
save((entries) => resolvePendingSendEvidence(entries, id, agent, source)),
[agent, save]
@@ -284,7 +284,7 @@ export function useNativeChatPendingDelivery(args: {
pending,
record,
cancel,
useSourceEvidence,
setSourceEvidence,
finishSourceEvidence,
reject,
holdUnconfirmed,
@@ -15,13 +15,16 @@ import {
setTrackedSessionOption
} from './native-chat-session-option-state'
import {
acquireNativeChatSessionOptionLease,
readNativeChatSessionOptionSeed,
type NativeChatSessionOptionLease,
type NativeChatSessionOptionOwner,
readNativeChatSessionOptionCache,
writeNativeChatSessionOptionCache
} from './native-chat-session-option-cache'
import {
acquireNativeChatSessionOptionOwnerLease,
settleNativeChatSessionOptionLease
} from './native-chat-session-option-owner'
import { createSessionOptionAppliers } from './native-chat-session-option-apply'
import {
buildNativeChatSessionOptionSnapshot,
@@ -35,6 +38,7 @@ export type NativeChatPtySessionOptionsSurface = SessionOptionsSurface & {
recordOutgoingCommand(command: string): void
reportSessionOptions(values: Record<string, SessionOptionValue>): void
replaceModels(models: CatalogModel[]): void
reconcileOwner(): void
/** The context window the host's model listing states for `modelId`, or null. */
contextWindowTokens(modelId: string): number | null
}
@@ -124,23 +128,28 @@ export function createNativeChatPtySessionOptions(
let operationLease: NativeChatSessionOptionLease | null = null
let hasSubscribed = false
const acquire = (): NativeChatSessionOptionLease | null =>
args.owner
? acquireNativeChatSessionOptionLease(args.scopeKey, args.owner, args.fallbackScopeKey)
: null
acquireNativeChatSessionOptionOwnerLease(args.scopeKey, args.owner, args.fallbackScopeKey)
const reconcileOwner = (): void => {
if (mountedLease || listeners.size === 0) {
return
}
mountedLease = acquire()
if (!mountedLease) {
return
}
record = mountedLease.record
unsubscribeOwner = mountedLease.subscribe(publish)
if (args.reportedValues) {
mountedLease.transact(() =>
applyNativeChatReportedSessionOptions(record, args.reportedValues!)
)
}
publish()
}
const canCommit = (): boolean =>
!args.owner || (operationLease ?? mountedLease)?.isCurrent() === true
const settle = <T>(mutate: () => T): T | undefined => {
if (!args.owner) {
return mutate()
}
const held = operationLease
let result: T | undefined
held?.settle(() => {
result = mutate()
return true
})
return result
}
const settle = <T>(mutate: () => T): T | undefined =>
args.owner ? settleNativeChatSessionOptionLease(operationLease, mutate) : mutate()
const transact = (mutate: () => boolean): void => {
if (!args.owner) {
if (mutate()) {
@@ -247,22 +256,11 @@ export function createNativeChatPtySessionOptions(
getSnapshot: () => snapshot,
setOption: appliers.setOption,
invokeAction: appliers.invokeAction,
reconcileOwner,
subscribe: (listener) => {
hasSubscribed = true
listeners.add(listener)
if (!mountedLease) {
mountedLease = acquire()
if (mountedLease) {
record = mountedLease.record
unsubscribeOwner = mountedLease.subscribe(publish)
if (args.reportedValues) {
mountedLease.transact(() =>
applyNativeChatReportedSessionOptions(record, args.reportedValues!)
)
}
publish()
}
}
reconcileOwner()
return () => {
listeners.delete(listener)
if (listeners.size === 0) {
@@ -14,6 +14,23 @@ export type NativeChatSessionOptionBinding = {
providerSession?: AgentProviderSessionMetadata
}
export function nativeChatSessionOptionBindingObservationsEqual(
left: NativeChatSessionOptionBinding,
right: NativeChatSessionOptionBinding
): boolean {
return (
left.agent === right.agent &&
left.connectionId === right.connectionId &&
left.worktreeId === right.worktreeId &&
left.terminalHandle === right.terminalHandle &&
left.ptyId === right.ptyId &&
left.incarnationId === right.incarnationId &&
left.providerSession?.key === right.providerSession?.key &&
left.providerSession?.id === right.providerSession?.id &&
left.providerSession?.transcriptPath === right.providerSession?.transcriptPath
)
}
/** Missing legacy metadata can enrich an owner, but cannot erase known identity. */
export function sameNativeChatSessionOptionBinding(
left: NativeChatSessionOptionBinding,
@@ -7,8 +7,14 @@ import {
type TrackedNativeChatSessionOption
} from './native-chat-session-option-state'
import { setBoundedScopeCacheEntry } from '../native-chat-scope-cache'
import type {
NativeChatSessionOptionOwner,
NativeChatSessionOptionBindingSource
} from './native-chat-session-option-owner'
export type { NativeChatSessionOptionOwner } from './native-chat-session-option-owner'
import {
enrichNativeChatSessionOptionBinding,
nativeChatSessionOptionBindingObservationsEqual,
sameNativeChatSessionOptionBinding,
type NativeChatSessionOptionBinding
} from './native-chat-session-option-binding'
@@ -18,12 +24,9 @@ type Entry = {
binding: NativeChatSessionOptionBinding
leases: number
listeners: Set<() => void>
bindingListeners: Set<() => void>
}
export type NativeChatSessionOptionOwner = {
binding: NativeChatSessionOptionBinding
readCurrentBinding: () => NativeChatSessionOptionBinding | null
}
export type NativeChatSessionOptionLease = {
export type NativeChatSessionOptionLease = NativeChatSessionOptionBindingSource & {
record: NativeChatSessionOptionRecord
isCurrent: () => boolean
transact: (mutate: (record: NativeChatSessionOptionRecord) => boolean) => boolean
@@ -37,20 +40,31 @@ const inactiveBindings = new WeakMap<
NativeChatSessionOptionBinding
>()
function currentBinding(
owner: NativeChatSessionOptionOwner
): NativeChatSessionOptionBinding | null {
const current = owner.readCurrentBinding()
if (!current || !sameNativeChatSessionOptionBinding(owner.binding, current)) {
return null
function publishBinding(entry: Entry, binding: NativeChatSessionOptionBinding): void {
if (nativeChatSessionOptionBindingObservationsEqual(entry.binding, binding)) {
return
}
owner.binding = enrichNativeChatSessionOptionBinding(owner.binding, current)
return current
entry.binding = binding
for (const listener of entry.bindingListeners) {
listener()
}
}
export function readNativeChatSessionOptionSeedBinding(
scopeKey: string,
candidate: NativeChatSessionOptionBinding
): NativeChatSessionOptionBinding {
const active = activeEntries.get(scopeKey)
const record = active?.record ?? sessionOptionCache.get(scopeKey)
const binding = active?.binding ?? (record ? inactiveBindings.get(record) : undefined)
return binding && sameNativeChatSessionOptionBinding(binding, candidate)
? enrichNativeChatSessionOptionBinding(binding, candidate)
: candidate
}
export function readNativeChatSessionOptionSeed(
scopeKey: string,
owner: NativeChatSessionOptionOwner,
owner: Pick<NativeChatSessionOptionOwner, 'binding'>,
fallbackScopeKey?: string
): NativeChatSessionOptionRecord {
const active = activeEntries.get(scopeKey)
@@ -79,21 +93,20 @@ export function acquireNativeChatSessionOptionLease(
owner: NativeChatSessionOptionOwner,
fallbackScopeKey?: string
): NativeChatSessionOptionLease | null {
const current = currentBinding(owner)
const current = owner.currentBinding()
if (!current) {
return null
}
let entry = activeEntries.get(scopeKey)
if (entry && !sameNativeChatSessionOptionBinding(entry.binding, current)) {
activeEntries.delete(scopeKey)
for (const listener of entry.bindingListeners) {
listener()
}
entry = undefined
}
if (!entry) {
const seed = readNativeChatSessionOptionSeed(
scopeKey,
{ ...owner, binding: enrichNativeChatSessionOptionBinding(owner.binding, current) },
fallbackScopeKey
)
const seed = readNativeChatSessionOptionSeed(scopeKey, { binding: current }, fallbackScopeKey)
entry = {
record: cloneNativeChatSessionOptionRecord(seed),
binding: enrichNativeChatSessionOptionBinding(
@@ -104,26 +117,28 @@ export function acquireNativeChatSessionOptionLease(
current
),
leases: 0,
listeners: new Set()
listeners: new Set(),
bindingListeners: new Set()
}
activeEntries.set(scopeKey, entry)
sessionOptionCache.delete(scopeKey)
} else {
entry.binding = enrichNativeChatSessionOptionBinding(entry.binding, current)
publishBinding(entry, enrichNativeChatSessionOptionBinding(entry.binding, current))
}
owner.binding = enrichNativeChatSessionOptionBinding(entry.binding, owner.binding)
owner.captureBinding(entry.binding)
const held = entry
held.leases++
let released = false
const isHeld = (): boolean => !released && activeEntries.get(scopeKey) === held
const isCurrent = (): boolean => {
if (released || activeEntries.get(scopeKey) !== held) {
if (!isHeld() || !owner.captureBinding(held.binding)) {
return false
}
const next = currentBinding(owner)
const next = owner.currentBinding()
if (!next || !sameNativeChatSessionOptionBinding(held.binding, next)) {
return false
}
held.binding = enrichNativeChatSessionOptionBinding(held.binding, next)
publishBinding(held, enrichNativeChatSessionOptionBinding(held.binding, next))
return true
}
const settle = (mutate: (record: NativeChatSessionOptionRecord) => boolean): boolean => {
@@ -137,6 +152,12 @@ export function acquireNativeChatSessionOptionLease(
}
return {
record: held.record,
getBindingSnapshot: () => held.binding,
isHeld,
subscribeBinding: (listener) => {
held.bindingListeners.add(listener)
return () => held.bindingListeners.delete(listener)
},
isCurrent,
transact: (mutate) => isCurrent() && settle(mutate),
settle,
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createNativeChatPtySessionOptions } from './native-chat-pty-session-options'
import { createNativeChatSessionOptionOwner } from './native-chat-session-option-owner'
import {
clearNativeChatSessionOptionCacheForTests,
readNativeChatSessionOptionCache,
@@ -49,7 +50,7 @@ describe('live session option ownership', () => {
it('returns an accepted original action without reviving it through any late writer', async () => {
let current: NativeChatSessionOptionBinding | null = binding('A')
const ownerA = { binding: current, readCurrentBinding: () => current }
const ownerA = createNativeChatSessionOptionOwner(current, () => current)
let accept!: () => void
const dispatched = vi.fn(
() =>
@@ -65,7 +66,10 @@ describe('live session option ownership', () => {
await Promise.resolve()
expect(dispatched).toHaveBeenCalledOnce()
current = binding('B')
const b = surface('pty', { binding: current, readCurrentBinding: () => current })
const b = surface(
'pty',
createNativeChatSessionOptionOwner(current, () => current)
)
const changedB = vi.fn()
const releaseB = b.subscribe(changedB)
b.reportSessionOptions({ model: 'haiku' })
@@ -96,10 +100,7 @@ describe('live session option ownership', () => {
...binding('A'),
providerSession: undefined
}
const original: NativeChatSessionOptionOwner = {
binding: current,
readCurrentBinding: () => current
}
const original = createNativeChatSessionOptionOwner(current, () => current)
let accept!: () => void
const a = surface(
'pty',
@@ -118,7 +119,10 @@ describe('live session option ownership', () => {
release()
for (let i = 0; i < 160; i++) {
const identity = { ...binding(String(i)), ptyId: String(i) }
const other = surface(String(i), { binding: identity, readCurrentBinding: () => identity })
const other = surface(
String(i),
createNativeChatSessionOptionOwner(identity, () => identity)
)
const close = other.subscribe(() => {})
other.reportSessionOptions({ model: 'haiku' })
close()
@@ -126,7 +130,10 @@ describe('live session option ownership', () => {
accept()
await result
expect(readNativeChatSessionOptionCache('pty')?.model?.value).toBe('opus')
const remount = surface('pty', { binding: binding('A'), readCurrentBinding: () => current })
const remount = surface(
'pty',
createNativeChatSessionOptionOwner(binding('A'), () => current)
)
const close = remount.subscribe(() => {})
expect(remount.getSnapshot()[0].kind).toMatchObject({ currentValue: 'opus' })
current = binding('B')
@@ -146,7 +153,11 @@ describe('live session option ownership', () => {
accept = resolve
})
)
const a = surface('pty', { binding: current, readCurrentBinding: () => current }, dispatched)
const a = surface(
'pty',
createNativeChatSessionOptionOwner(current, () => current),
dispatched
)
const release = a.subscribe(() => {})
a.reportSessionOptions({ model: 'sonnet' })
const accepted = a.setOption('model', 'opus')
@@ -179,10 +190,7 @@ describe('live session option ownership', () => {
const persist = vi.fn()
const target = surface(
'pty',
{
binding: identity,
readCurrentBinding: () => (oldRouteLive ? identity : null)
},
createNativeChatSessionOptionOwner(identity, () => (oldRouteLive ? identity : null)),
() =>
new Promise<void>((resolve) => {
accept = resolve
@@ -200,7 +208,10 @@ describe('live session option ownership', () => {
let reopened: ReturnType<typeof surface> | undefined
let closeReopened: (() => void) | undefined
const reopen = () => {
reopened = surface('pty', { binding: identity, readCurrentBinding: () => identity })
reopened = surface(
'pty',
createNativeChatSessionOptionOwner(identity, () => identity)
)
closeReopened = reopened.subscribe(() => {})
}
if (reopenBeforeAcceptance) {
@@ -224,7 +235,7 @@ describe('live session option ownership', () => {
let accept!: () => void
const target = surface(
'pty',
{ binding: current, readCurrentBinding: () => current },
createNativeChatSessionOptionOwner(current, () => current),
() =>
new Promise<void>((resolve) => {
accept = resolve
@@ -241,7 +252,10 @@ describe('live session option ownership', () => {
await picked
expect(notify).not.toHaveBeenCalled()
close()
const successor = surface('pty', { binding: current, readCurrentBinding: () => current })
const successor = surface(
'pty',
createNativeChatSessionOptionOwner(current, () => current)
)
const closeSuccessor = successor.subscribe(() => {})
expect(successor.getSnapshot()[0].kind).not.toMatchObject({ currentValue: 'opus' })
closeSuccessor()
@@ -253,7 +267,7 @@ describe('live session option ownership', () => {
let accept!: () => void
const target = surface(
'pty',
{ binding: identity, readCurrentBinding: () => identity },
createNativeChatSessionOptionOwner(identity, () => identity),
() =>
new Promise<void>((resolve) => {
accept = resolve
@@ -285,7 +299,7 @@ describe('live session option ownership', () => {
)
const target = surface(
'pty',
{ binding: current, readCurrentBinding: () => current },
createNativeChatSessionOptionOwner(current, () => current),
dispatched
)
const close = target.subscribe(() => {})
@@ -296,7 +310,10 @@ describe('live session option ownership', () => {
await Promise.resolve()
expect(dispatched).toHaveBeenCalledOnce()
current = { ...current, connectionId: 'ssh:another-host' }
const successor = surface('pty', { binding: current, readCurrentBinding: () => current })
const successor = surface(
'pty',
createNativeChatSessionOptionOwner(current, () => current)
)
const closeSuccessor = successor.subscribe(() => {})
successor.reportSessionOptions({ model: 'haiku' })
accept()
@@ -311,7 +328,10 @@ describe('live session option ownership', () => {
const owners = Array.from({ length: count }, (_, i) => {
const identity = { ...binding(String(i)), ptyId: String(i) }
const readCurrentBinding = vi.fn(() => identity)
const target = surface(String(i), { binding: identity, readCurrentBinding })
const target = surface(
String(i),
createNativeChatSessionOptionOwner(identity, readCurrentBinding)
)
const notify = vi.fn()
const release = target.subscribe(notify)
notify.mockClear()
@@ -0,0 +1,115 @@
import {
acquireNativeChatSessionOptionLease,
type NativeChatSessionOptionLease
} from './native-chat-session-option-cache'
import {
enrichNativeChatSessionOptionBinding,
nativeChatSessionOptionBindingObservationsEqual,
sameNativeChatSessionOptionBinding,
type NativeChatSessionOptionBinding
} from './native-chat-session-option-binding'
export type NativeChatSessionOptionBindingSource = {
getBindingSnapshot: () => NativeChatSessionOptionBinding
isHeld: () => boolean
subscribeBinding: (listener: () => void) => () => void
}
export type NativeChatSessionOptionOwner = {
readonly binding: NativeChatSessionOptionBinding
readCurrentBinding: () => NativeChatSessionOptionBinding | null
captureBinding: (known: NativeChatSessionOptionBinding) => NativeChatSessionOptionBinding | null
currentBinding: () => NativeChatSessionOptionBinding | null
getSnapshot: () => NativeChatSessionOptionBinding
subscribe: (listener: () => void) => () => void
attach: (source: NativeChatSessionOptionBindingSource) => () => void
}
export function createNativeChatSessionOptionOwner(
binding: NativeChatSessionOptionBinding,
readCurrentBinding: () => NativeChatSessionOptionBinding | null
): NativeChatSessionOptionOwner {
let captured = { ...binding }
const listeners = new Set<() => void>()
const sources = new Set<NativeChatSessionOptionBindingSource>()
const captureBinding = (
known: NativeChatSessionOptionBinding
): NativeChatSessionOptionBinding | null => {
if (!sameNativeChatSessionOptionBinding(captured, known)) {
return null
}
const next = enrichNativeChatSessionOptionBinding(captured, known)
if (!nativeChatSessionOptionBindingObservationsEqual(captured, next)) {
captured = next
for (const listener of listeners) {
listener()
}
}
return captured
}
return {
binding: { ...binding },
readCurrentBinding,
captureBinding,
getSnapshot: () => captured,
subscribe: (listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
attach: (source) => {
sources.add(source)
const observe = (): void => {
if (source.isHeld()) {
captureBinding(source.getBindingSnapshot())
}
}
observe()
const unsubscribe = source.subscribeBinding(observe)
observe()
return () => {
unsubscribe()
sources.delete(source)
}
},
currentBinding: () => {
for (const source of sources) {
if (!source.isHeld() || !captureBinding(source.getBindingSnapshot())) {
return null
}
}
const current = readCurrentBinding()
return current ? captureBinding(current) : null
}
}
}
export function acquireNativeChatSessionOptionOwnerLease(
scopeKey: string,
owner: NativeChatSessionOptionOwner | undefined,
fallbackScopeKey?: string
): NativeChatSessionOptionLease | null {
const held = owner ? acquireNativeChatSessionOptionLease(scopeKey, owner, fallbackScopeKey) : null
if (!held || !owner) {
return null
}
const detach = owner.attach(held)
return {
...held,
release: () => {
detach()
held.release()
}
}
}
export function settleNativeChatSessionOptionLease<T>(
held: NativeChatSessionOptionLease | null,
mutate: () => T
): T | undefined {
let result: T | undefined
held?.settle(() => {
result = mutate()
return true
})
return result
}
@@ -141,7 +141,7 @@ describe('RemoteRuntimeRequestConnection', () => {
})
return child
})
const server = await createServer((method) =>
const server = await createServer(async (method) =>
method === 'git.remoteFileUrl'
? getRemoteFileUrl('/repo', 'a.ts', 10, 20, routing)
: { method }