Harden mobile session tab sync

Harden mobile session-tab snapshot reconciliation and terminal creation. Rejects stale mobile snapshots, tombstones locally closed tabs until the publisher catches up, rolls back half-created terminal tabs when their surface never appears, and scopes terminal-create idempotency by worktree.
This commit is contained in:
JinHyeok Jeong
2026-06-22 13:31:10 -07:00
committed by GitHub
parent 423c2befe1
commit e253d46e72
7 changed files with 510 additions and 7 deletions
+244
View File
@@ -13887,6 +13887,250 @@ describe('OrcaRuntimeService', () => {
expect(result.tab).toMatchObject({ parentTabId: 'tab-renderer', isActive: false })
})
it('dedupes concurrent mobile terminal creates that share a clientMutationId', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setNotifier({
focusTerminal: vi.fn(),
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
revealTerminalSession: vi.fn(),
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
closeTerminal: vi.fn(),
closeSessionTab: vi.fn(),
sleepWorktree: vi.fn(),
terminalFitOverrideChanged: vi.fn(),
terminalDriverChanged: vi.fn()
})
const send = vi.fn((_channel: string, payload: { requestId: string }) => {
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: TEST_WORKTREE_ID,
publicationEpoch: 'epoch-1',
snapshotVersion: 1,
activeGroupId: 'group-1',
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'terminal',
id: 'tab-renderer::pane:1',
parentTabId: 'tab-renderer',
leafId: 'pane:1',
title: 'Terminal',
isActive: false
}
]
}
]
})
ipcMain.emit(
'terminal:tabCreateReply',
{},
{ requestId: payload.requestId, tabId: 'tab-renderer', title: 'Terminal' }
)
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
electronMocks.BrowserWindow.fromId.mockReturnValue({
isDestroyed: () => false,
webContents: { send }
})
const [first, second] = await Promise.all([
runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, {
activate: false,
clientMutationId: 'mutation-1'
}),
runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, {
activate: false,
clientMutationId: 'mutation-1'
})
])
const createRequests = send.mock.calls.filter(
([channel]) => channel === 'terminal:requestTabCreate'
)
expect(createRequests).toHaveLength(1)
expect(second).toBe(first)
expect(first.tab).toMatchObject({ parentTabId: 'tab-renderer' })
})
it('does not dedupe mobile terminal creates across worktrees with the same clientMutationId', async () => {
const otherWorktreeId = `${TEST_REPO_ID}::/tmp/worktree-b`
vi.mocked(listWorktrees).mockResolvedValue([
...MOCK_GIT_WORKTREES,
{
path: '/tmp/worktree-b',
head: 'def',
branch: 'feature/bar',
isBare: false,
isMainWorktree: false
}
])
const runtimeStore = {
...store,
getAllWorktreeMeta: () => ({
[TEST_WORKTREE_ID]: store.getAllWorktreeMeta()[TEST_WORKTREE_ID],
[otherWorktreeId]: makeWorktreeMeta({ displayName: 'other' })
})
}
const runtime = new OrcaRuntimeService(runtimeStore)
runtime.setNotifier({
focusTerminal: vi.fn(),
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
revealTerminalSession: vi.fn(),
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
closeTerminal: vi.fn(),
closeSessionTab: vi.fn(),
sleepWorktree: vi.fn(),
terminalFitOverrideChanged: vi.fn(),
terminalDriverChanged: vi.fn()
})
const send = vi.fn((_channel: string, payload: { requestId: string; worktreeId: string }) => {
const parentTabId =
payload.worktreeId === TEST_WORKTREE_ID ? 'tab-renderer-a' : 'tab-renderer-b'
ipcMain.emit(
'terminal:tabCreateReply',
{},
{ requestId: payload.requestId, tabId: parentTabId, title: 'Terminal' }
)
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
electronMocks.BrowserWindow.fromId.mockReturnValue({
isDestroyed: () => false,
webContents: { send }
})
const firstCreate = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, {
activate: false,
clientMutationId: 'mutation-1'
})
const secondCreate = runtime.createMobileSessionTerminal(`id:${otherWorktreeId}`, {
activate: false,
clientMutationId: 'mutation-1'
})
await vi.waitFor(() => {
const createRequests = send.mock.calls.filter(
([channel]) => channel === 'terminal:requestTabCreate'
)
expect(createRequests).toHaveLength(2)
})
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: TEST_WORKTREE_ID,
publicationEpoch: 'epoch-a',
snapshotVersion: 1,
activeGroupId: 'group-1',
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'terminal',
id: 'tab-renderer-a::pane:1',
parentTabId: 'tab-renderer-a',
leafId: 'pane:1',
title: 'Terminal',
isActive: false
}
]
},
{
worktree: otherWorktreeId,
publicationEpoch: 'epoch-b',
snapshotVersion: 1,
activeGroupId: 'group-1',
activeTabId: null,
activeTabType: null,
tabs: [
{
type: 'terminal',
id: 'tab-renderer-b::pane:1',
parentTabId: 'tab-renderer-b',
leafId: 'pane:1',
title: 'Terminal',
isActive: false
}
]
}
]
})
const [first, second] = await Promise.all([firstCreate, secondCreate])
const createRequests = send.mock.calls.filter(
([channel]) => channel === 'terminal:requestTabCreate'
)
expect(createRequests).toHaveLength(2)
expect(first.tab).toMatchObject({ parentTabId: 'tab-renderer-a' })
expect(second.tab).toMatchObject({ parentTabId: 'tab-renderer-b' })
})
it('rolls back a half-created terminal whose surface never publishes', async () => {
vi.useFakeTimers()
try {
const closeTerminal = vi.fn()
const runtime = new OrcaRuntimeService(store)
runtime.setNotifier({
focusTerminal: vi.fn(),
worktreesChanged: vi.fn(),
reposChanged: vi.fn(),
activateWorktree: vi.fn(),
createTerminal: vi.fn(),
revealTerminalSession: vi.fn(),
splitTerminal: vi.fn(),
renameTerminal: vi.fn(),
closeTerminal,
closeSessionTab: vi.fn(),
sleepWorktree: vi.fn(),
terminalFitOverrideChanged: vi.fn(),
terminalDriverChanged: vi.fn()
})
// Why: reply with a tabId but never sync a matching surface graph, so
// waitForMobileTerminalSurface times out and the rollback path runs.
const send = vi.fn((_channel: string, payload: { requestId: string }) => {
ipcMain.emit(
'terminal:tabCreateReply',
{},
{ requestId: payload.requestId, tabId: 'tab-ghost', title: 'Terminal' }
)
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
electronMocks.BrowserWindow.fromId.mockReturnValue({
isDestroyed: () => false,
webContents: { send }
})
const pending = runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, {
activate: false
})
const settled = pending.then(
() => ({ ok: true as const }),
(error: Error) => ({ ok: false as const, error })
)
await vi.advanceTimersByTimeAsync(11_000)
const outcome = await settled
expect(outcome.ok).toBe(false)
expect(closeTerminal).toHaveBeenCalledWith('tab-ghost')
} finally {
vi.useRealTimers()
}
})
it('reports browser tab creation as unsupported for a windowless host with no offscreen backend', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.syncWindowGraph(0, { tabs: [], leaves: [] })
+57 -1
View File
@@ -1784,6 +1784,12 @@ export class OrcaRuntimeService {
private authoritativeWindowId: number | null = null
private tabs = new Map<string, RuntimeSyncedTab>()
private mobileSessionTabsByWorktree = new Map<string, RuntimeMobileSessionTabsSnapshot>()
// Why: idempotency map for mobile terminal creation — a retried create with the
// same clientMutationId returns the in-flight operation instead of duplicating.
private mobileTerminalCreateByMutationId = new Map<
string,
Promise<RuntimeMobileSessionCreateTerminalResult>
>()
private mobileSessionTabListeners = new Set<(snapshot: RuntimeMobileSessionTabsResult) => void>()
private leaves = new Map<string, RuntimeLeafRecord>()
// Why: PTY output is a per-keystroke hot path. Looking up affected leaves by
@@ -14641,6 +14647,47 @@ export class OrcaRuntimeService {
launchConfig?: SleepingAgentLaunchConfig
launchAgent?: TuiAgent
activate?: boolean
clientMutationId?: string
} = {}
): Promise<RuntimeMobileSessionCreateTerminalResult> {
const mutationId = opts.clientMutationId
if (!mutationId) {
return this.runCreateMobileSessionTerminal(worktreeSelector, opts)
}
const mutationKey = `${worktreeSelector}\0${mutationId}`
// Why: a retried create (double-tap, reconnect replay) with the same
// idempotency key must return the in-flight operation instead of spawning a
// duplicate terminal. Settled entries are dropped so a later retry — after a
// failure or after the result is consumed — can start a fresh create.
const inflight = this.mobileTerminalCreateByMutationId.get(mutationKey)
if (inflight) {
return inflight
}
const run = this.runCreateMobileSessionTerminal(worktreeSelector, opts)
this.mobileTerminalCreateByMutationId.set(mutationKey, run)
void run
.catch(() => {})
.finally(() => {
if (this.mobileTerminalCreateByMutationId.get(mutationKey) === run) {
this.mobileTerminalCreateByMutationId.delete(mutationKey)
}
})
return run
}
private async runCreateMobileSessionTerminal(
worktreeSelector: string,
opts: {
afterTabId?: string
targetGroupId?: string
command?: string
env?: Record<string, string>
startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery']
agent?: TuiAgent
launchConfig?: SleepingAgentLaunchConfig
launchAgent?: TuiAgent
activate?: boolean
clientMutationId?: string
} = {}
): Promise<RuntimeMobileSessionCreateTerminalResult> {
this.assertGraphReady()
@@ -14713,7 +14760,16 @@ export class OrcaRuntimeService {
if (opts.activate !== false) {
this.notifier?.focusTerminal(reply.tabId, worktreeId, null)
}
return await this.waitForMobileTerminalSurface(worktreeId, reply.tabId)
try {
return await this.waitForMobileTerminalSurface(worktreeId, reply.tabId)
} catch (error) {
// Why: the renderer created the tab but its terminal surface never
// published (PTY spawn/handle failure). Roll the half-created tab back via
// the renderer close path so it can't linger as a ghost in mobile
// snapshots, then surface the failure to the caller.
this.notifier?.closeTerminal(reply.tabId)
throw error
}
}
private async resolveMobileSessionTerminalCommand(
@@ -125,7 +125,10 @@ export const CreateTerminalTab = WorktreeTabSelector.extend({
message: 'Unknown launch agent'
})
.optional(),
activate: z.boolean().optional()
activate: z.boolean().optional(),
// Why: idempotency key so a retried create (double-tap, reconnect replay)
// returns the in-flight operation instead of spawning a duplicate terminal.
clientMutationId: z.string().min(1).max(128).optional()
})
const MoveTabBase = {
+2 -1
View File
@@ -50,7 +50,8 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [
...(params.launchConfig ? { launchConfig: params.launchConfig } : {}),
...(params.launchToken ? { launchToken: params.launchToken } : {}),
...(params.launchAgent ? { launchAgent: params.launchAgent } : {}),
activate: params.activate
activate: params.activate,
clientMutationId: params.clientMutationId
})
}),
defineMethod({