Skip to content
Merged
11 changes: 7 additions & 4 deletions mobile/src/session/mobile-session-route-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,18 @@ const HOST_COMPONENT_NAMES = new Set([
'View'
])

const HEAD_MAIN_HOOK_SHA256 = '10071240ef9edafc2b9c8bed73be83dceaf7828e3b29f17dab55da020a7697a6'
const HEAD_HOOK_BINDING_SHA256 = '1dadb8c3dc0573ea20659ce7251629669e618dd0effaeac3a4536b29c2e865a1'
const HEAD_MAIN_HOOK_SHA256 = '5c18b82b70218f71ea9eff5316ee2e1e9b6555bc1ea2f19f24ede519a5933857'
const HEAD_HOOK_BINDING_SHA256 = '9ee9c7d7d651e001499d906428a0987994a291517911cef7d529d41e4c61cb62'
const HEAD_CALLBACK_IDENTITY_SHA256 =
'2a9e4825df007f6ef53b81aa5004991d6318eee7507b44d625c07e630be432eb'
const HEAD_CALLBACK_BODY_SHA256 = 'af7f3c62954250d4be7ee432ecd10dc2689792aad8230fed2d1d68bbc892d776'
const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13'
const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581'
// Moved once for the create-tab placement fix: handleCreateTerminal now paints the created tab
// after the anchor it sent the host instead of appending. Only that body changed; the other 11
// extracted functions are byte-identical.
const HEAD_NESTED_FUNCTION_SHA256 =
'fde6679349ab2b8c30c7e627841ff99bd1dd24441ee95323d0aa70230422ae24'
'e54db6971e298dc27b59da9cbb2c455b85f0e1224cdf00482410ac43d179b02d'
const HEAD_NATIVE_REGISTRATION_SHA256 =
'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e'
const HEAD_NATIVE_REMOVAL_SHA256 =
Expand Down Expand Up @@ -472,7 +475,7 @@ describe('mobile session route extraction parity', () => {
const contentBindings = CONTENT_COMPONENT_NAMES.flatMap(
(name) => readHookFacts(name, definitions).bindings
)
expect(main.hooks).toHaveLength(266)
expect(main.hooks).toHaveLength(267)
expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256)
expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256)
expect(main.callbacks).toHaveLength(77)
Expand Down
3 changes: 3 additions & 0 deletions mobile/src/session/use-mobile-session-foundation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { isFloatingWorkspaceWorktreeId } from './floating-workspace'
import { useLiveWorktreeName } from './use-live-worktree-name'
import { useMissingWorktreeBounce } from './use-missing-worktree-bounce'
import { hostRouteWithNotice } from '../host-route-notice'
import { useHostProtocolGates } from '../components/HostProtocolGate'

export function useMobileSessionFoundation() {
const {
Expand All @@ -36,6 +37,7 @@ export function useMobileSessionFoundation() {
const insets = useSafeAreaInsets()
// Why: shared client per host owned by RpcClientProvider (docs/mobile-shared-client-per-host.md).
const { client, clientId, state: connState } = useHostClient(hostId)
const { hostCapabilities } = useHostProtocolGates()
const reconnectAttempts = useReconnectAttempt(hostId)
const lastConnectedAt = useLastConnectedAt(hostId)
const forceReconnectHost = useForceReconnect()
Expand Down Expand Up @@ -98,6 +100,7 @@ export function useMobileSessionFoundation() {
client,
clientId,
connState,
hostCapabilities,
reconnectAttempts,
lastConnectedAt,
forceReconnectHost,
Expand Down
106 changes: 106 additions & 0 deletions mobile/src/session/use-mobile-session-terminal-create-actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RpcClient } from '../transport/rpc-client'
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
import { useMobileSessionTerminalCreateActions } from './use-mobile-session-terminal-create-actions'
import { SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version'

vi.mock('../platform/haptics', () => ({
triggerSuccess: vi.fn(),
Expand Down Expand Up @@ -36,6 +37,7 @@ function createScope(client: RpcClient) {
return {
worktreeId: 'workspace-1',
client,
hostCapabilities: [],
connState: 'connected',
setTerminals: vi.fn(),
terminalsRef: { current: [] },
Expand Down Expand Up @@ -262,3 +264,107 @@ describe('mobile + Codex tab creation routing', () => {
}
)
})

describe('optimistic placement of a created tab', () => {
let renderer: ReactTestRenderer | undefined
afterEach(() => renderer?.unmount())

async function createLegacyTerminal(scope: ReturnType<typeof createScope>) {
let actions: ReturnType<typeof useMobileSessionTerminalCreateActions> | undefined
function Harness() {
actions = useMobileSessionTerminalCreateActions(scope as never)
return null
}
await act(async () => {
renderer = create(createElement(Harness))
})
await act(async () => {
await actions?.handleCreateTerminal()
})
}

function tabIdsAfterCreate(
scope: ReturnType<typeof createScope>,
prior: { id: string }[]
): string[] {
const updater = (scope.setSessionTabs as ReturnType<typeof vi.fn>).mock.calls.at(-1)?.[0] as (
prev: { id: string }[]
) => { id: string }[]
return updater(prior).map((tab) => tab.id)
}

it('paints the created tab after the anchor it asked the host for, not at the end', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
await createLegacyTerminal(scope)

expect(scope.setSessionTabs).toHaveBeenCalled()
// The request anchored on the active tab, so the paint must land in the same slot the host
// splices into; appending here is what made the tab jump on the next snapshot.
expect(tabIdsAfterCreate(scope, [{ id: 'existing-tab' }, { id: 'trailing-tab' }])).toEqual([
'existing-tab',
'terminal-tab-1',
'trailing-tab'
])
})

it('paints after the active split parent, matching headed host placement', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
scope.hostCapabilities = [SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY]
scope.activeSessionTabId = 'existing-tab::left'
await createLegacyTerminal(scope)

expect(
tabIdsAfterCreate(scope, [
{ id: 'existing-tab::left', parentTabId: 'existing-tab' },
{ id: 'existing-tab::right', parentTabId: 'existing-tab' },
{ id: 'trailing-tab' }
])
).toEqual(['existing-tab::left', 'existing-tab::right', 'terminal-tab-1', 'trailing-tab'])
})

it('keeps legacy leaf placement for an older host', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
scope.activeSessionTabId = 'existing-tab::left'
await createLegacyTerminal(scope)

expect(
tabIdsAfterCreate(scope, [
{ id: 'existing-tab::left', parentTabId: 'existing-tab' },
{ id: 'existing-tab::right', parentTabId: 'existing-tab' },
{ id: 'trailing-tab' }
])
).toEqual(['existing-tab::left', 'terminal-tab-1', 'existing-tab::right', 'trailing-tab'])
})

it('sends the same anchor it paints with', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
await createLegacyTerminal(scope)

expect(scope.client.sendRequest).toHaveBeenCalledWith(
'session.tabs.createTerminal',
expect.objectContaining({ afterTabId: 'existing-tab' })
)
})

it('appends when the anchor is not in the client list, matching the host fallback', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
await createLegacyTerminal(scope)

expect(tabIdsAfterCreate(scope, [{ id: 'unrelated-tab' }])).toEqual([
'unrelated-tab',
'terminal-tab-1'
])
})

it('leaves the list alone when the host snapshot already placed the tab', async () => {
const scope = createScope(clientReturning(terminalCreateResponse()))
await createLegacyTerminal(scope)

const prior = [{ id: 'existing-tab' }, { id: 'terminal-tab-1' }, { id: 'trailing-tab' }]
expect(tabIdsAfterCreate(scope, prior)).toEqual([
'existing-tab',
'terminal-tab-1',
'trailing-tab'
])
})
})
14 changes: 12 additions & 2 deletions mobile/src/session/use-mobile-session-terminal-create-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ import type { Terminal, TerminalCreateResult } from './mobile-session-route-type
import type { MobileSessionAttachmentsModel } from './use-mobile-session-attachments'
import { isAgentSessionHandleProvider } from '../../../src/shared/agent-session-provider-handle'
import { createMobileStructuredAgentSession } from './mobile-structured-agent-session-launch'
import { placeCreatedSessionTab } from '../../../src/shared/session-tab-placement'
import { SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version'

export function useMobileSessionTerminalCreateActions(scope: MobileSessionAttachmentsModel) {
const {
worktreeId,
client,
hostCapabilities,
connState,
setTerminals,
terminalsRef,
Expand Down Expand Up @@ -93,9 +96,12 @@ export function useMobileSessionTerminalCreateActions(scope: MobileSessionAttach
return
}
}
// Why: one anchor for both the request and the optimistic paint below; when they disagreed the
// new tab painted at the end and jumped to its real slot on the next host snapshot.
const afterTabId = activeSessionTabId ?? undefined
const response = await client.sendRequest('session.tabs.createTerminal', {
worktree: `id:${worktreeId}`,
afterTabId: activeSessionTabId ?? undefined,
afterTabId,
clientMutationId,
...(options?.startupCommand ? { command: options.startupCommand } : {}),
...(options?.startupCommandDelivery
Expand Down Expand Up @@ -123,7 +129,11 @@ export function useMobileSessionTerminalCreateActions(scope: MobileSessionAttach
if (prev.some((tab) => tab.id === created.id)) {
return prev
}
return [...prev, { ...created, isActive: true }]
return placeCreatedSessionTab(prev, { ...created, isActive: true }, afterTabId, {
afterParentGroup: hostCapabilities?.includes(
SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY
)
})
})
if (typeof created.terminal === 'string') {
const createdHandle = created.terminal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
AGENT_SESSION_TURN_ITEM_CAPABILITY,
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY
} from '../../../src/shared/protocol-version'
Expand All @@ -20,7 +21,8 @@ describe('mobile runtime client capabilities', () => {
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY,
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
AGENT_SESSION_TURN_ITEM_CAPABILITY
AGENT_SESSION_TURN_ITEM_CAPABILITY,
SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY
])
)
})
Expand Down
2 changes: 2 additions & 0 deletions mobile/src/transport/mobile-runtime-client-capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY,
AGENT_SESSION_TURN_ITEM_CAPABILITY,
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY
} from '../../../src/shared/protocol-version'
Expand All @@ -12,6 +13,7 @@ export const MOBILE_RUNTIME_CLIENT_CAPABILITIES = remoteRuntimeClientCapabilitie
AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY,
STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY,
CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY,
SESSION_TABS_SPLIT_GROUP_PLACEMENT_RUNTIME_CAPABILITY,
// Opts into the typed turn record; without it the host sends the legacy status carrier.
AGENT_SESSION_TURN_ITEM_CAPABILITY
])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export class OrcaRuntimeWithCreateMobileSessionTerminal extends OrcaRuntimeWithC
clientNavigationId?: string
navigation?: RuntimeNavigationTarget
clientMutationId?: string
// Older mobile clients optimistically append; preserve that placement until they advertise
// split-group ordering support.
supportsSplitGroupPlacement?: boolean
signal?: AbortSignal
} = {}
): Promise<RuntimeMobileSessionCreateTerminalResult> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type {
} from '../../shared/runtime-types'
import { randomUUID } from 'node:crypto'
import { parsePaneKey } from '../../shared/stable-pane-id'
import { placeCreatedSessionTab } from '../../shared/session-tab-placement'
import {
buildHeadlessMobileSessionTabGroups,
buildMaterializedHeadlessParentLayout,
Expand All @@ -31,6 +32,7 @@ export class OrcaRuntimeWithCreateRuntimeOwnedMobileSessionTerminal extends Orca
launchAgent?: TuiAgent
viewMode?: 'terminal' | 'chat'
targetGroupId?: string
supportsSplitGroupPlacement?: boolean
launchConfig?: SleepingAgentLaunchConfig
signal?: AbortSignal
} = {}
Expand Down Expand Up @@ -103,21 +105,18 @@ export class OrcaRuntimeWithCreateRuntimeOwnedMobileSessionTerminal extends Orca
parentLayout,
isActive: activate
}
const tabs = (existing?.tabs ?? [])
.filter((candidate) => candidate.id !== tab.id)
.map((candidate) => ({
const tabs = placeCreatedSessionTab(
(existing?.tabs ?? []).map((candidate) => ({
...candidate,
...(candidate.type === 'terminal' && candidate.parentTabId === parentTabId
? { parentLayout }
: {}),
isActive: activate ? false : candidate.isActive
}))
const insertAfter = afterTabId ? tabs.findIndex((candidate) => candidate.id === afterTabId) : -1
if (insertAfter >= 0) {
tabs.splice(insertAfter + 1, 0, tab)
} else {
tabs.push(tab)
}
})),
tab,
afterTabId,
{ afterParentGroup: opts.supportsSplitGroupPlacement !== false }
)
const next: RuntimeMobileSessionTabsSnapshot = {
worktree: worktreeId,
// Why: a fresh epoch retires the current publisher, so clients drop its later tab updates.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
activate?: boolean
clientNavigationId?: string
clientMutationId?: string
supportsSplitGroupPlacement?: boolean
signal?: AbortSignal
} = {}
): Promise<RuntimeMobileSessionCreateTerminalResult> {
Expand All @@ -41,14 +42,23 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
const worktreeId = workspace.id
const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd)
this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId)
// Older mobile clients append their optimistic tab, so make the host append too until the
// client advertises the grouped placement contract.
const requestedAfterTabId = opts.afterTabId
const afterTabId =
opts.clientNavigationId && opts.supportsSplitGroupPlacement === false
? undefined
: requestedAfterTabId
let afterDesktopTabId: string | undefined
if (opts.afterTabId) {
if (requestedAfterTabId) {
const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId)
const anchor = snapshot?.tabs.find((tab) => tab.id === opts.afterTabId)
const anchor = snapshot?.tabs.find((tab) => tab.id === requestedAfterTabId)
if (!anchor) {
throw new Error('after_tab_not_found')
}
afterDesktopTabId = anchor.type === 'terminal' ? anchor.parentTabId : anchor.id
if (afterTabId) {
afterDesktopTabId = anchor.type === 'terminal' ? anchor.parentTabId : anchor.id
}
}
const startupCommand = await this.resolveMobileSessionTerminalCommand(workspace, opts)
this.assertStableReadyGraph(graphEpoch)
Expand All @@ -60,7 +70,7 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
return await this.createRuntimeOwnedMobileSessionTerminal(
worktreeId,
opts.activate !== false,
opts.afterTabId,
afterTabId,
{
command: startupCommand.command,
cwd,
Expand All @@ -70,6 +80,7 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
launchAgent: startupCommand.launchAgent,
viewMode: opts.viewMode,
targetGroupId: opts.targetGroupId,
supportsSplitGroupPlacement: opts.supportsSplitGroupPlacement,
launchConfig: startupCommand.launchConfig,
signal: opts.signal
}
Expand Down Expand Up @@ -184,7 +195,7 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
return await this.createRuntimeOwnedMobileSessionTerminal(
worktreeId,
opts.activate !== false,
opts.afterTabId,
afterTabId,
{
command: startupCommand.command,
cwd,
Expand All @@ -195,6 +206,7 @@ export class OrcaRuntimeWithRunCreateMobileSessionTerminal extends OrcaRuntimeWi
launchAgent: startupCommand.launchAgent,
viewMode: opts.viewMode,
targetGroupId: opts.targetGroupId,
supportsSplitGroupPlacement: opts.supportsSplitGroupPlacement,
launchConfig: startupCommand.launchConfig,
signal: opts.signal
}
Expand Down
Loading