fix(terminal): make remote agent sessions host-authoritative (#9687)
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
canonicalizeAgentSessionIdentity,
|
||||
createEphemeralAgentSessionClaimSigner
|
||||
} from './agent-session-claim-identity'
|
||||
|
||||
describe('agent session claim identity', () => {
|
||||
it('creates stable opaque identity and worktree digests', () => {
|
||||
const signer = createEphemeralAgentSessionClaimSigner('profile-1')
|
||||
const identity = canonicalizeAgentSessionIdentity('codex', {
|
||||
key: 'session_id',
|
||||
id: 'session-1'
|
||||
})
|
||||
const namespace = {
|
||||
machine: 'machine',
|
||||
principal: 'user',
|
||||
container: 'native',
|
||||
providerRoot: 'default'
|
||||
}
|
||||
|
||||
const first = signer.createClaim({ namespace, identity, canonicalWorktreeId: 'worktree-1' })
|
||||
const second = signer.createClaim({ namespace, identity, canonicalWorktreeId: 'worktree-1' })
|
||||
const otherWorktree = signer.createClaim({
|
||||
namespace,
|
||||
identity,
|
||||
canonicalWorktreeId: 'worktree-2'
|
||||
})
|
||||
|
||||
expect(first).toEqual(second)
|
||||
expect(first.identityDigest).not.toContain('session-1')
|
||||
expect(otherWorktree.identityDigest).toBe(first.identityDigest)
|
||||
expect(otherWorktree.worktreeScopeDigest).not.toBe(first.worktreeScopeDigest)
|
||||
})
|
||||
|
||||
it('rejects malformed and unsupported provider identity', () => {
|
||||
expect(() =>
|
||||
canonicalizeAgentSessionIdentity('codex', { key: 'session_id', id: '-unsafe' })
|
||||
).toThrow('agent_session_identity_required')
|
||||
expect(() =>
|
||||
canonicalizeAgentSessionIdentity('blank', { key: 'session_id', id: 'session-1' })
|
||||
).toThrow('agent_session_identity_required')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,177 @@
|
||||
import { createHash, createHmac, randomBytes } from 'node:crypto'
|
||||
import {
|
||||
closeSync,
|
||||
mkdirSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { dirname, isAbsolute, join, normalize } from 'node:path'
|
||||
import {
|
||||
AGENT_SESSION_CLAIM_DIGEST_VERSION,
|
||||
type AgentSessionExecutionClaim
|
||||
} from '../../shared/agent-session-host-authority'
|
||||
import {
|
||||
getAgentResumeArgv,
|
||||
isResumableTuiAgent,
|
||||
normalizeAgentProviderSession,
|
||||
type AgentProviderSessionMetadata,
|
||||
type ResumableTuiAgent
|
||||
} from '../../shared/agent-session-resume'
|
||||
|
||||
const COORDINATION_KEY_BYTES = 32
|
||||
const COORDINATION_KEY_FILE = 'agent-session-authority.key'
|
||||
const TRANSCRIPT_PATH_MAX_BYTES = 16 * 1024
|
||||
|
||||
export type ProviderExecutionNamespace = {
|
||||
machine: string
|
||||
principal: string
|
||||
container: string
|
||||
providerRoot: string
|
||||
}
|
||||
|
||||
export type CanonicalAgentSessionIdentity = {
|
||||
agent: ResumableTuiAgent
|
||||
providerSession: AgentProviderSessionMetadata
|
||||
}
|
||||
|
||||
function encodeFields(fields: readonly string[]): Buffer {
|
||||
const chunks: Buffer[] = []
|
||||
for (const field of fields) {
|
||||
const value = Buffer.from(field, 'utf8')
|
||||
const length = Buffer.allocUnsafe(4)
|
||||
length.writeUInt32BE(value.length)
|
||||
chunks.push(length, value)
|
||||
}
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
function canonicalPathForPlatform(value: string): string {
|
||||
const canonical = normalize(realpathSync(value))
|
||||
return process.platform === 'win32' ? canonical.toLocaleLowerCase('en-US') : canonical
|
||||
}
|
||||
|
||||
export function canonicalizeAgentSessionIdentity(
|
||||
agent: unknown,
|
||||
rawProviderSession: unknown
|
||||
): CanonicalAgentSessionIdentity {
|
||||
if (!isResumableTuiAgent(agent)) {
|
||||
throw new Error('agent_session_identity_required')
|
||||
}
|
||||
const providerSession = normalizeAgentProviderSession(rawProviderSession)
|
||||
if (!providerSession || !getAgentResumeArgv(agent, providerSession)) {
|
||||
throw new Error('agent_session_identity_required')
|
||||
}
|
||||
if (agent !== 'pi') {
|
||||
return { agent, providerSession }
|
||||
}
|
||||
const transcriptPath = providerSession.transcriptPath
|
||||
if (
|
||||
!transcriptPath ||
|
||||
!isAbsolute(transcriptPath) ||
|
||||
Buffer.byteLength(transcriptPath, 'utf8') > TRANSCRIPT_PATH_MAX_BYTES
|
||||
) {
|
||||
throw new Error('agent_session_identity_required')
|
||||
}
|
||||
const canonicalTranscriptPath = canonicalPathForPlatform(transcriptPath)
|
||||
if (!statSync(canonicalTranscriptPath).isFile()) {
|
||||
throw new Error('agent_session_identity_required')
|
||||
}
|
||||
return {
|
||||
agent,
|
||||
providerSession: { ...providerSession, transcriptPath: canonicalTranscriptPath }
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentSessionClaimSigner {
|
||||
readonly keyId: string
|
||||
|
||||
constructor(
|
||||
private readonly authorityDomainId: string,
|
||||
private readonly key: Buffer
|
||||
) {
|
||||
if (key.length !== COORDINATION_KEY_BYTES) {
|
||||
throw new Error('agent_session_ownership_unknown')
|
||||
}
|
||||
this.keyId = createHash('sha256').update(key).digest('base64url').slice(0, 22)
|
||||
}
|
||||
|
||||
createClaim(args: {
|
||||
namespace: ProviderExecutionNamespace
|
||||
identity: CanonicalAgentSessionIdentity
|
||||
canonicalWorktreeId: string
|
||||
}): AgentSessionExecutionClaim {
|
||||
const namespaceFields = [
|
||||
args.namespace.machine,
|
||||
args.namespace.principal,
|
||||
args.namespace.container,
|
||||
args.namespace.providerRoot
|
||||
]
|
||||
const identityFields = [
|
||||
'orca-agent-session-claim-v1',
|
||||
this.authorityDomainId,
|
||||
...namespaceFields,
|
||||
args.identity.agent,
|
||||
args.identity.providerSession.key,
|
||||
args.identity.providerSession.id,
|
||||
args.identity.agent === 'pi' ? (args.identity.providerSession.transcriptPath ?? '') : ''
|
||||
]
|
||||
const worktreeFields = [
|
||||
'orca-agent-session-worktree-v1',
|
||||
this.authorityDomainId,
|
||||
...namespaceFields,
|
||||
args.canonicalWorktreeId
|
||||
]
|
||||
return {
|
||||
digestVersion: AGENT_SESSION_CLAIM_DIGEST_VERSION,
|
||||
keyId: this.keyId,
|
||||
identityDigest: createHmac('sha256', this.key)
|
||||
.update(encodeFields(identityFields))
|
||||
.digest('base64url'),
|
||||
worktreeScopeDigest: createHmac('sha256', this.key)
|
||||
.update(encodeFields(worktreeFields))
|
||||
.digest('base64url'),
|
||||
agent: args.identity.agent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function loadAgentSessionClaimSigner(
|
||||
profileDirectory: string,
|
||||
authorityDomainId: string
|
||||
): AgentSessionClaimSigner {
|
||||
const keyPath = join(profileDirectory, COORDINATION_KEY_FILE)
|
||||
mkdirSync(dirname(keyPath), { recursive: true })
|
||||
let key: Buffer
|
||||
try {
|
||||
key = readFileSync(keyPath)
|
||||
} catch {
|
||||
const candidate = randomBytes(COORDINATION_KEY_BYTES)
|
||||
let fd: number | null = null
|
||||
try {
|
||||
fd = openSync(keyPath, 'wx', 0o600)
|
||||
writeFileSync(fd, candidate)
|
||||
key = candidate
|
||||
} catch {
|
||||
key = readFileSync(keyPath)
|
||||
} finally {
|
||||
if (fd !== null) {
|
||||
closeSync(fd)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Why: a replaced/corrupt key could make a surviving owner look absent;
|
||||
// refuse authority instead of silently minting an incomparable namespace.
|
||||
if (key.length !== COORDINATION_KEY_BYTES) {
|
||||
throw new Error('agent_session_ownership_unknown')
|
||||
}
|
||||
return new AgentSessionClaimSigner(authorityDomainId, key)
|
||||
}
|
||||
|
||||
export function createEphemeralAgentSessionClaimSigner(
|
||||
authorityDomainId: string
|
||||
): AgentSessionClaimSigner {
|
||||
return new AgentSessionClaimSigner(authorityDomainId, randomBytes(COORDINATION_KEY_BYTES))
|
||||
}
|
||||
@@ -8,6 +8,8 @@ const MOBILE_DYNAMIC_RPC_METHODS = [
|
||||
// mobile source scan below, but still must stay mobile-authorized.
|
||||
'accounts.selectClaude',
|
||||
'accounts.selectCodex',
|
||||
'terminal.createAgentSession',
|
||||
'terminal.ensureAgentSession',
|
||||
'github.updateIssue',
|
||||
'github.updatePRState',
|
||||
'gitlab.updateIssue',
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getDefaultWorkspaceSession } from '../../shared/constants'
|
||||
import {
|
||||
retireTerminalSurfaceFromPersistence,
|
||||
sanitizeWorkspaceSessionTerminalRetirements
|
||||
} from './mobile-session-terminal-persistence-retirement'
|
||||
|
||||
const WORKTREE_ID = 'repo::/worktree'
|
||||
const REPO_ID = 'repo'
|
||||
|
||||
describe('mobile session terminal persistence retirement', () => {
|
||||
it('de-persists a final leaf and repairs active group state', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
activeTabId: 'terminal',
|
||||
activeTabIdByWorktree: { [WORKTREE_ID]: 'terminal' },
|
||||
activeTabTypeByWorktree: { [WORKTREE_ID]: 'terminal' as const },
|
||||
activeGroupIdByWorktree: { [WORKTREE_ID]: 'terminal-group' },
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-left',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: {
|
||||
root: { type: 'leaf' as const, leafId: 'left' },
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { left: 'pty-left' }
|
||||
}
|
||||
},
|
||||
unifiedTabs: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
entityId: 'terminal',
|
||||
groupId: 'terminal-group',
|
||||
worktreeId: WORKTREE_ID,
|
||||
contentType: 'terminal' as const,
|
||||
label: 'Terminal',
|
||||
customLabel: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
},
|
||||
{
|
||||
id: 'notes',
|
||||
entityId: 'notes.md',
|
||||
groupId: 'notes-group',
|
||||
worktreeId: WORKTREE_ID,
|
||||
contentType: 'editor' as const,
|
||||
label: 'Notes',
|
||||
customLabel: null,
|
||||
color: null,
|
||||
sortOrder: 1,
|
||||
createdAt: 2
|
||||
}
|
||||
]
|
||||
},
|
||||
tabGroups: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal-group',
|
||||
worktreeId: WORKTREE_ID,
|
||||
activeTabId: 'terminal',
|
||||
tabOrder: ['terminal']
|
||||
},
|
||||
{
|
||||
id: 'notes-group',
|
||||
worktreeId: WORKTREE_ID,
|
||||
activeTabId: 'notes',
|
||||
tabOrder: ['notes']
|
||||
}
|
||||
]
|
||||
},
|
||||
tabGroupLayouts: {
|
||||
[WORKTREE_ID]: {
|
||||
type: 'split' as const,
|
||||
direction: 'horizontal' as const,
|
||||
first: { type: 'leaf' as const, groupId: 'terminal-group' },
|
||||
second: { type: 'leaf' as const, groupId: 'notes-group' }
|
||||
}
|
||||
},
|
||||
remoteSessionIdsByTabId: { terminal: 'pty-left' }
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left'
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
expect(result.terminalLayoutsByTabId.terminal).toBeUndefined()
|
||||
expect(result.unifiedTabs?.[WORKTREE_ID].map((tab) => tab.id)).toEqual(['notes'])
|
||||
expect(result.tabGroups?.[WORKTREE_ID].map((group) => group.id)).toEqual(['notes-group'])
|
||||
expect(result.tabGroupLayouts?.[WORKTREE_ID]).toEqual({
|
||||
type: 'leaf',
|
||||
groupId: 'notes-group'
|
||||
})
|
||||
expect(result.activeTabIdByWorktree?.[WORKTREE_ID]).toBe('notes')
|
||||
expect(result.activeTabTypeByWorktree?.[WORKTREE_ID]).toBe('editor')
|
||||
expect(result.activeGroupIdByWorktree?.[WORKTREE_ID]).toBe('notes-group')
|
||||
expect(result.remoteSessionIdsByTabId?.terminal).toBeUndefined()
|
||||
})
|
||||
|
||||
it('retires an exact split leaf when only its sibling has a persisted PTY mapping', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-right',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: {
|
||||
root: {
|
||||
type: 'split' as const,
|
||||
direction: 'vertical' as const,
|
||||
first: { type: 'leaf' as const, leafId: 'left' },
|
||||
second: { type: 'leaf' as const, leafId: 'right' }
|
||||
},
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left'
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual([
|
||||
expect.objectContaining({ id: 'terminal', ptyId: 'pty-right' })
|
||||
])
|
||||
expect(result.terminalLayoutsByTabId.terminal).toMatchObject({
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
})
|
||||
})
|
||||
|
||||
it('fences an absent exact leaf without deleting its live sibling parent', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-right',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: {
|
||||
root: { type: 'leaf' as const, leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
}
|
||||
},
|
||||
terminalPtyIncarnationsByPaneKey: { 'terminal:left': 'incarnation-left' },
|
||||
remoteSessionIdsByTabId: { terminal: 'pty-right' }
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
incarnationId: 'incarnation-left',
|
||||
retiredAt: 42
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual(session.tabsByWorktree[WORKTREE_ID])
|
||||
expect(result.terminalLayoutsByTabId.terminal).toEqual(session.terminalLayoutsByTabId.terminal)
|
||||
expect(result.remoteSessionIdsByTabId).toEqual({ terminal: 'pty-right' })
|
||||
expect(result.terminalPtyIncarnationsByPaneKey?.['terminal:left']).toBeUndefined()
|
||||
expect(result.terminalSurfaceTombstonesByPaneKey).toEqual({})
|
||||
expect(result.terminalTopologyRevisionByRepoId?.[REPO_ID]).toBe(1)
|
||||
})
|
||||
|
||||
it('does not treat a sibling parent PTY as the exact leaf when layout is unavailable', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-right',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
incarnationId: 'incarnation-left'
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual(session.tabsByWorktree[WORKTREE_ID])
|
||||
expect(result.terminalSurfaceTombstonesByPaneKey).toEqual({})
|
||||
expect(result.terminalTopologyRevisionByRepoId?.[REPO_ID]).toBe(1)
|
||||
})
|
||||
|
||||
it('rebases stale writes onto durable host membership without retaining pane history', () => {
|
||||
const staleSession = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-left',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: {
|
||||
root: { type: 'leaf' as const, leafId: 'left' },
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { left: 'pty-left' }
|
||||
}
|
||||
},
|
||||
terminalPtyIncarnationsByPaneKey: { 'terminal:left': 'incarnation-a' }
|
||||
}
|
||||
const retired = retireTerminalSurfaceFromPersistence(staleSession, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
incarnationId: 'incarnation-a',
|
||||
retiredAt: 42
|
||||
})
|
||||
|
||||
const afterStaleWrite = sanitizeWorkspaceSessionTerminalRetirements(staleSession, retired)
|
||||
expect(afterStaleWrite.tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
expect(afterStaleWrite.terminalSurfaceTombstonesByPaneKey).toEqual({})
|
||||
expect(afterStaleWrite.terminalTopologyRevisionByRepoId?.[REPO_ID]).toBe(1)
|
||||
|
||||
const afterRestart = sanitizeWorkspaceSessionTerminalRetirements(staleSession, afterStaleWrite)
|
||||
expect(afterRestart.tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
|
||||
const untrustedReplacement = sanitizeWorkspaceSessionTerminalRetirements(
|
||||
{
|
||||
...staleSession,
|
||||
terminalPtyIncarnationsByPaneKey: { 'terminal:left': 'incarnation-b' }
|
||||
},
|
||||
afterRestart
|
||||
)
|
||||
expect(untrustedReplacement.tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
expect(untrustedReplacement.terminalPtyIncarnationsByPaneKey).toBeUndefined()
|
||||
})
|
||||
|
||||
it('migrates legacy tombstones into one repo watermark', () => {
|
||||
const stale = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
terminalSurfaceTombstonesByPaneKey: {
|
||||
'terminal:left': {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
incarnationId: 'incarnation-a',
|
||||
retiredAt: 42
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const migrated = sanitizeWorkspaceSessionTerminalRetirements(stale, stale)
|
||||
|
||||
expect(migrated.terminalSurfaceTombstonesByPaneKey).toEqual({})
|
||||
expect(migrated.terminalTopologyRevisionByRepoId).toEqual({ [REPO_ID]: 1 })
|
||||
})
|
||||
|
||||
it('keeps retirement state proportional to repos across many worktrees and closed panes', () => {
|
||||
let session = getDefaultWorkspaceSession()
|
||||
for (let index = 0; index < 1_000; index += 1) {
|
||||
session = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: `${REPO_ID}::/worktree-${index}`,
|
||||
parentTabId: `terminal-${index}`,
|
||||
leafId: `leaf-${index}`,
|
||||
ptyId: `pty-${index}`,
|
||||
incarnationId: `incarnation-${index}`
|
||||
})
|
||||
}
|
||||
|
||||
expect(session.terminalSurfaceTombstonesByPaneKey).toEqual({})
|
||||
expect(Object.keys(session.terminalTopologyRevisionByRepoId ?? {})).toEqual([REPO_ID])
|
||||
expect(session.terminalTopologyRevisionByRepoId?.[REPO_ID]).toBe(1_000)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { WorkspaceSessionState, WorkspaceVisibleTabType } from '../../shared/types'
|
||||
import {
|
||||
pruneTabGroupLayoutAfterRetirement,
|
||||
repairMobileSessionTabGroupsAfterRetirement,
|
||||
retireLeavesFromTerminalLayout,
|
||||
type RetiredTerminalSurface
|
||||
} from './mobile-session-terminal-retirement'
|
||||
import {
|
||||
advanceTerminalTopologyRevision,
|
||||
rebaseWorkspaceSessionTerminalMembership
|
||||
} from './workspace-session-terminal-membership-authority'
|
||||
|
||||
function visibleTypeForContentType(
|
||||
contentType: string | undefined
|
||||
): WorkspaceVisibleTabType | undefined {
|
||||
if (contentType === 'terminal') {
|
||||
return 'terminal'
|
||||
}
|
||||
if (contentType === 'browser') {
|
||||
return 'browser'
|
||||
}
|
||||
if (contentType === 'simulator') {
|
||||
return 'simulator'
|
||||
}
|
||||
return contentType ? 'editor' : undefined
|
||||
}
|
||||
|
||||
function layoutContainsLeaf(
|
||||
node: WorkspaceSessionState['terminalLayoutsByTabId'][string]['root'],
|
||||
leafId: string
|
||||
): boolean {
|
||||
if (!node) {
|
||||
return false
|
||||
}
|
||||
return node.type === 'leaf'
|
||||
? node.leafId === leafId
|
||||
: layoutContainsLeaf(node.first, leafId) || layoutContainsLeaf(node.second, leafId)
|
||||
}
|
||||
|
||||
function recordTerminalSurfaceRetirement(
|
||||
session: WorkspaceSessionState,
|
||||
surface: RetiredTerminalSurface,
|
||||
paneKey: string
|
||||
): WorkspaceSessionState {
|
||||
const terminalPtyIncarnationsByPaneKey = {
|
||||
...session.terminalPtyIncarnationsByPaneKey
|
||||
}
|
||||
delete terminalPtyIncarnationsByPaneKey[paneKey]
|
||||
const terminalSurfaceTombstonesByPaneKey = {
|
||||
...session.terminalSurfaceTombstonesByPaneKey
|
||||
}
|
||||
delete terminalSurfaceTombstonesByPaneKey[paneKey]
|
||||
return advanceTerminalTopologyRevision(
|
||||
{
|
||||
...session,
|
||||
terminalPtyIncarnationsByPaneKey,
|
||||
terminalSurfaceTombstonesByPaneKey
|
||||
},
|
||||
surface.worktreeId
|
||||
)
|
||||
}
|
||||
|
||||
export function retireTerminalSurfaceFromPersistence(
|
||||
session: WorkspaceSessionState,
|
||||
surface: RetiredTerminalSurface
|
||||
): WorkspaceSessionState {
|
||||
const paneKey = `${surface.parentTabId}:${surface.leafId}`
|
||||
const boundIncarnationId = session.terminalPtyIncarnationsByPaneKey?.[paneKey]
|
||||
if (surface.incarnationId && boundIncarnationId && boundIncarnationId !== surface.incarnationId) {
|
||||
return session
|
||||
}
|
||||
const persistedTabs = session.tabsByWorktree[surface.worktreeId] ?? []
|
||||
const persistedTab = persistedTabs.find((tab) => tab.id === surface.parentTabId)
|
||||
const layout = session.terminalLayoutsByTabId[surface.parentTabId]
|
||||
const exactLeafInLayout = Boolean(layout && layoutContainsLeaf(layout.root, surface.leafId))
|
||||
const leafPtyId = exactLeafInLayout ? layout?.ptyIdsByLeafId?.[surface.leafId] : undefined
|
||||
if (leafPtyId && leafPtyId !== surface.ptyId) {
|
||||
return session
|
||||
}
|
||||
|
||||
const isLegacyFinalSurface = !layout && persistedTab?.ptyId === surface.ptyId
|
||||
if (!exactLeafInLayout && !isLegacyFinalSurface) {
|
||||
// Why: tab.ptyId may describe a live sibling. The absent exact leaf still
|
||||
// needs a tombstone, but sibling evidence must not remove its parent.
|
||||
return recordTerminalSurfaceRetirement(session, surface, paneKey)
|
||||
}
|
||||
|
||||
const nextLayout =
|
||||
exactLeafInLayout && layout
|
||||
? retireLeavesFromTerminalLayout(layout, new Set([surface.leafId]))
|
||||
: null
|
||||
const removeParent = !nextLayout
|
||||
const nextTabsForWorktree = removeParent
|
||||
? persistedTabs.filter((tab) => tab.id !== surface.parentTabId)
|
||||
: persistedTabs.map((tab) =>
|
||||
tab.id === surface.parentTabId
|
||||
? {
|
||||
...tab,
|
||||
ptyId:
|
||||
nextLayout.ptyIdsByLeafId?.[nextLayout.activeLeafId ?? ''] ??
|
||||
Object.values(nextLayout.ptyIdsByLeafId ?? {})[0] ??
|
||||
null
|
||||
}
|
||||
: tab
|
||||
)
|
||||
const terminalLayoutsByTabId = { ...session.terminalLayoutsByTabId }
|
||||
if (nextLayout) {
|
||||
terminalLayoutsByTabId[surface.parentTabId] = nextLayout
|
||||
} else {
|
||||
delete terminalLayoutsByTabId[surface.parentTabId]
|
||||
}
|
||||
|
||||
const unifiedTabsForWorktree = session.unifiedTabs?.[surface.worktreeId] ?? []
|
||||
const unifiedTabs = session.unifiedTabs
|
||||
? {
|
||||
...session.unifiedTabs,
|
||||
[surface.worktreeId]: removeParent
|
||||
? unifiedTabsForWorktree.filter(
|
||||
(tab) => tab.id !== surface.parentTabId && tab.entityId !== surface.parentTabId
|
||||
)
|
||||
: unifiedTabsForWorktree
|
||||
}
|
||||
: undefined
|
||||
const validTopLevelIds = new Set((unifiedTabs?.[surface.worktreeId] ?? []).map((tab) => tab.id))
|
||||
for (const tab of nextTabsForWorktree) {
|
||||
validTopLevelIds.add(tab.id)
|
||||
}
|
||||
const persistedGroups = session.tabGroups?.[surface.worktreeId]
|
||||
const repairedGroups = repairMobileSessionTabGroupsAfterRetirement(
|
||||
persistedGroups,
|
||||
validTopLevelIds
|
||||
)
|
||||
const tabGroups = session.tabGroups
|
||||
? {
|
||||
...session.tabGroups,
|
||||
[surface.worktreeId]: (repairedGroups ?? []).map((group) => ({
|
||||
...group,
|
||||
worktreeId: surface.worktreeId
|
||||
}))
|
||||
}
|
||||
: undefined
|
||||
const retainedGroupIds = new Set(repairedGroups?.map((group) => group.id) ?? [])
|
||||
const repairedGroupLayout = pruneTabGroupLayoutAfterRetirement(
|
||||
session.tabGroupLayouts?.[surface.worktreeId],
|
||||
retainedGroupIds
|
||||
)
|
||||
const tabGroupLayouts = session.tabGroupLayouts ? { ...session.tabGroupLayouts } : undefined
|
||||
if (tabGroupLayouts) {
|
||||
if (repairedGroupLayout) {
|
||||
tabGroupLayouts[surface.worktreeId] = repairedGroupLayout
|
||||
} else {
|
||||
delete tabGroupLayouts[surface.worktreeId]
|
||||
}
|
||||
}
|
||||
|
||||
const previousActiveTabId = session.activeTabIdByWorktree?.[surface.worktreeId]
|
||||
const activeTabStillExists = previousActiveTabId && validTopLevelIds.has(previousActiveTabId)
|
||||
const nextActiveTabId =
|
||||
(activeTabStillExists ? previousActiveTabId : undefined) ??
|
||||
repairedGroups?.find(
|
||||
(group) => group.id === session.activeGroupIdByWorktree?.[surface.worktreeId]
|
||||
)?.activeTabId ??
|
||||
repairedGroups?.[0]?.activeTabId ??
|
||||
[...validTopLevelIds][0] ??
|
||||
null
|
||||
const activeTabIdByWorktree = {
|
||||
...session.activeTabIdByWorktree,
|
||||
[surface.worktreeId]: nextActiveTabId
|
||||
}
|
||||
const activeTabTypeByWorktree = { ...session.activeTabTypeByWorktree }
|
||||
const activeUnifiedTab = unifiedTabs?.[surface.worktreeId]?.find(
|
||||
(tab) => tab.id === nextActiveTabId
|
||||
)
|
||||
const nextActiveType = visibleTypeForContentType(activeUnifiedTab?.contentType)
|
||||
if (nextActiveType) {
|
||||
activeTabTypeByWorktree[surface.worktreeId] = nextActiveType
|
||||
} else if (!nextActiveTabId) {
|
||||
delete activeTabTypeByWorktree[surface.worktreeId]
|
||||
}
|
||||
const activeGroupIdByWorktree = { ...session.activeGroupIdByWorktree }
|
||||
const nextActiveGroupId =
|
||||
repairedGroups?.find((group) => group.tabOrder.includes(nextActiveTabId ?? ''))?.id ??
|
||||
repairedGroups?.[0]?.id
|
||||
if (nextActiveGroupId) {
|
||||
activeGroupIdByWorktree[surface.worktreeId] = nextActiveGroupId
|
||||
} else {
|
||||
delete activeGroupIdByWorktree[surface.worktreeId]
|
||||
}
|
||||
const remoteSessionIdsByTabId = { ...session.remoteSessionIdsByTabId }
|
||||
if (removeParent) {
|
||||
delete remoteSessionIdsByTabId[surface.parentTabId]
|
||||
} else if (remoteSessionIdsByTabId[surface.parentTabId] === surface.ptyId) {
|
||||
remoteSessionIdsByTabId[surface.parentTabId] =
|
||||
nextLayout?.ptyIdsByLeafId?.[nextLayout.activeLeafId ?? ''] ??
|
||||
Object.values(nextLayout?.ptyIdsByLeafId ?? {})[0] ??
|
||||
''
|
||||
if (!remoteSessionIdsByTabId[surface.parentTabId]) {
|
||||
delete remoteSessionIdsByTabId[surface.parentTabId]
|
||||
}
|
||||
}
|
||||
return recordTerminalSurfaceRetirement(
|
||||
{
|
||||
...session,
|
||||
activeTabId:
|
||||
session.activeTabId === surface.parentTabId ? nextActiveTabId : session.activeTabId,
|
||||
tabsByWorktree: {
|
||||
...session.tabsByWorktree,
|
||||
[surface.worktreeId]: nextTabsForWorktree
|
||||
},
|
||||
terminalLayoutsByTabId,
|
||||
activeTabIdByWorktree,
|
||||
...(unifiedTabs ? { unifiedTabs } : {}),
|
||||
...(tabGroups ? { tabGroups } : {}),
|
||||
...(tabGroupLayouts ? { tabGroupLayouts } : {}),
|
||||
...(session.activeGroupIdByWorktree ? { activeGroupIdByWorktree } : {}),
|
||||
...(session.activeTabTypeByWorktree ? { activeTabTypeByWorktree } : {}),
|
||||
...(session.remoteSessionIdsByTabId ? { remoteSessionIdsByTabId } : {})
|
||||
},
|
||||
surface,
|
||||
paneKey
|
||||
)
|
||||
}
|
||||
|
||||
export function sanitizeWorkspaceSessionTerminalRetirements(
|
||||
incoming: WorkspaceSessionState,
|
||||
prior: WorkspaceSessionState | undefined
|
||||
): WorkspaceSessionState {
|
||||
if (
|
||||
!prior?.terminalSurfaceTombstonesByPaneKey &&
|
||||
!incoming.terminalSurfaceTombstonesByPaneKey &&
|
||||
!prior?.terminalTopologyRevisionByRepoId
|
||||
) {
|
||||
return incoming
|
||||
}
|
||||
const bindings = {
|
||||
...prior?.terminalPtyIncarnationsByPaneKey,
|
||||
...incoming.terminalPtyIncarnationsByPaneKey
|
||||
}
|
||||
const tombstones = {
|
||||
...prior?.terminalSurfaceTombstonesByPaneKey,
|
||||
...incoming.terminalSurfaceTombstonesByPaneKey
|
||||
}
|
||||
const hasLegacyTombstones = Object.keys(tombstones).length > 0
|
||||
let next: WorkspaceSessionState = {
|
||||
...incoming,
|
||||
terminalPtyIncarnationsByPaneKey: hasLegacyTombstones
|
||||
? bindings
|
||||
: incoming.terminalPtyIncarnationsByPaneKey,
|
||||
terminalSurfaceTombstonesByPaneKey: tombstones
|
||||
}
|
||||
for (const tombstone of Object.values(tombstones)) {
|
||||
next = retireTerminalSurfaceFromPersistence(next, tombstone)
|
||||
}
|
||||
return rebaseWorkspaceSessionTerminalMembership(
|
||||
{ ...next, terminalSurfaceTombstonesByPaneKey: {} },
|
||||
prior
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getDefaultWorkspaceSession } from '../../shared/constants'
|
||||
import type {
|
||||
RuntimeMobileSessionTabsSnapshot,
|
||||
RuntimeMobileSessionTerminalTab
|
||||
} from '../../shared/runtime-types'
|
||||
import { retireTerminalSurfacesFromSnapshot } from './mobile-session-terminal-retirement'
|
||||
import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement'
|
||||
|
||||
const WORKTREE_ID = 'repo::/worktree'
|
||||
|
||||
function splitSnapshot(): RuntimeMobileSessionTabsSnapshot {
|
||||
const parentLayout = {
|
||||
root: {
|
||||
type: 'split' as const,
|
||||
direction: 'vertical' as const,
|
||||
first: { type: 'leaf' as const, leafId: 'left' },
|
||||
second: { type: 'leaf' as const, leafId: 'right' }
|
||||
},
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: 'left',
|
||||
ptyIdsByLeafId: { left: 'pty-left', right: 'pty-right' },
|
||||
buffersByLeafId: { left: 'left buffer', right: 'right buffer' },
|
||||
titlesByLeafId: { left: 'Left', right: 'Right' }
|
||||
}
|
||||
return {
|
||||
worktree: WORKTREE_ID,
|
||||
publicationEpoch: 'host',
|
||||
snapshotVersion: 4,
|
||||
activeGroupId: 'terminals',
|
||||
activeTabId: 'terminal::left',
|
||||
activeTabType: 'terminal',
|
||||
tabGroups: [
|
||||
{
|
||||
id: 'terminals',
|
||||
activeTabId: 'terminal',
|
||||
tabOrder: ['terminal', 'notes'],
|
||||
recentTabIds: ['notes', 'terminal']
|
||||
},
|
||||
{ id: 'secondary', activeTabId: 'other', tabOrder: ['other'] }
|
||||
],
|
||||
tabGroupLayout: {
|
||||
type: 'split',
|
||||
direction: 'horizontal',
|
||||
first: { type: 'leaf', groupId: 'terminals' },
|
||||
second: { type: 'leaf', groupId: 'secondary' }
|
||||
},
|
||||
tabs: [
|
||||
{
|
||||
type: 'terminal',
|
||||
id: 'terminal::left',
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
title: 'Left',
|
||||
parentLayout,
|
||||
isActive: true
|
||||
},
|
||||
{
|
||||
type: 'terminal',
|
||||
id: 'terminal::right',
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'right',
|
||||
ptyId: 'pty-right',
|
||||
title: 'Right',
|
||||
parentLayout,
|
||||
isActive: false
|
||||
},
|
||||
{
|
||||
type: 'markdown',
|
||||
id: 'notes',
|
||||
title: 'Notes',
|
||||
filePath: '/worktree/notes.md',
|
||||
relativePath: 'notes.md',
|
||||
language: 'markdown',
|
||||
mode: 'edit',
|
||||
isDirty: false,
|
||||
sourceFileId: 'notes.md',
|
||||
sourceFilePath: '/worktree/notes.md',
|
||||
sourceRelativePath: 'notes.md',
|
||||
documentVersion: '1',
|
||||
isActive: false
|
||||
},
|
||||
{
|
||||
type: 'file',
|
||||
id: 'other',
|
||||
title: 'Other',
|
||||
filePath: '/worktree/other.ts',
|
||||
relativePath: 'other.ts',
|
||||
language: 'typescript',
|
||||
isDirty: false,
|
||||
isActive: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
describe('mobile session terminal retirement', () => {
|
||||
it('retires one split leaf and rewrites every surviving sibling layout', () => {
|
||||
const result = retireTerminalSurfacesFromSnapshot({
|
||||
snapshot: splitSnapshot(),
|
||||
ptyId: 'pty-left'
|
||||
})
|
||||
|
||||
expect(result?.snapshot).toMatchObject({
|
||||
snapshotVersion: 5,
|
||||
activeGroupId: 'terminals',
|
||||
activeTabId: 'terminal::right',
|
||||
activeTabType: 'terminal'
|
||||
})
|
||||
expect(result?.snapshot.tabs).toHaveLength(3)
|
||||
expect(result?.snapshot.tabs[0]).toMatchObject({
|
||||
id: 'terminal::right',
|
||||
isActive: true,
|
||||
parentLayout: {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' },
|
||||
buffersByLeafId: { right: 'right buffer' },
|
||||
titlesByLeafId: { right: 'Right' }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('removes the final parent, empty group, and group-layout leaf', () => {
|
||||
const first = retireTerminalSurfacesFromSnapshot({
|
||||
snapshot: splitSnapshot(),
|
||||
ptyId: 'pty-left'
|
||||
})!
|
||||
const result = retireTerminalSurfacesFromSnapshot({
|
||||
snapshot: first.snapshot,
|
||||
ptyId: 'pty-right'
|
||||
})
|
||||
|
||||
expect(result?.snapshot).toMatchObject({
|
||||
activeGroupId: 'terminals',
|
||||
activeTabId: 'notes',
|
||||
activeTabType: 'markdown',
|
||||
tabGroupLayout: {
|
||||
type: 'split',
|
||||
direction: 'horizontal',
|
||||
first: { type: 'leaf', groupId: 'terminals' },
|
||||
second: { type: 'leaf', groupId: 'secondary' }
|
||||
}
|
||||
})
|
||||
expect(result?.snapshot.tabGroups?.[0]).toMatchObject({
|
||||
id: 'terminals',
|
||||
activeTabId: 'notes',
|
||||
tabOrder: ['notes']
|
||||
})
|
||||
expect(result?.snapshot.tabs.map((tab) => tab.id)).toEqual(['notes', 'other'])
|
||||
})
|
||||
|
||||
it('does not retire an exact surface rebound to a replacement PTY', () => {
|
||||
const snapshot = splitSnapshot()
|
||||
const rebound = {
|
||||
...snapshot,
|
||||
tabs: snapshot.tabs.map((tab) =>
|
||||
tab.type === 'terminal' && tab.leafId === 'left'
|
||||
? {
|
||||
...tab,
|
||||
ptyId: 'pty-replacement',
|
||||
parentLayout: tab.parentLayout
|
||||
? {
|
||||
...tab.parentLayout,
|
||||
ptyIdsByLeafId: {
|
||||
...tab.parentLayout.ptyIdsByLeafId,
|
||||
left: 'pty-replacement'
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
: tab
|
||||
)
|
||||
}
|
||||
|
||||
expect(
|
||||
retireTerminalSurfacesFromSnapshot({
|
||||
snapshot: rebound,
|
||||
ptyId: 'pty-left',
|
||||
exactSurfaces: [{ parentTabId: 'terminal', leafId: 'left' }]
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('de-persists an exact leaf without removing its live sibling', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
activeTabId: 'terminal',
|
||||
activeTabIdByWorktree: { [WORKTREE_ID]: 'terminal' },
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-left',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: (splitSnapshot().tabs[0] as RuntimeMobileSessionTerminalTab).parentLayout!
|
||||
}
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left'
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual([
|
||||
expect.objectContaining({ id: 'terminal', ptyId: 'pty-right' })
|
||||
])
|
||||
expect(result.terminalLayoutsByTabId.terminal).toMatchObject({
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
})
|
||||
})
|
||||
|
||||
it('retires a permanently exited surface despite a stale sleeping record', () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'terminal',
|
||||
ptyId: 'pty-left',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
terminal: {
|
||||
root: { type: 'leaf' as const, leafId: 'left' },
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { left: 'pty-left' }
|
||||
}
|
||||
},
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
'terminal:left': {} as never
|
||||
}
|
||||
}
|
||||
|
||||
const result = retireTerminalSurfaceFromPersistence(session, {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'terminal',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left'
|
||||
})
|
||||
|
||||
expect(result.tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
expect(result.terminalLayoutsByTabId.terminal).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,286 @@
|
||||
import type {
|
||||
RuntimeMobileSessionSnapshotTab,
|
||||
RuntimeMobileSessionTabGroup,
|
||||
RuntimeMobileSessionTabsSnapshot,
|
||||
RuntimeMobileSessionTerminalTab
|
||||
} from '../../shared/runtime-types'
|
||||
import type {
|
||||
TabGroupLayoutNode,
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalPaneLayoutNode
|
||||
} from '../../shared/types'
|
||||
|
||||
export type RetiredTerminalSurface = {
|
||||
worktreeId: string
|
||||
parentTabId: string
|
||||
leafId: string
|
||||
ptyId: string
|
||||
incarnationId?: string
|
||||
retiredAt?: number
|
||||
}
|
||||
|
||||
function pruneTerminalPane(
|
||||
node: TerminalPaneLayoutNode | null,
|
||||
retiredLeafIds: ReadonlySet<string>
|
||||
): TerminalPaneLayoutNode | null {
|
||||
if (!node) {
|
||||
return null
|
||||
}
|
||||
if (node.type === 'leaf') {
|
||||
return retiredLeafIds.has(node.leafId) ? null : node
|
||||
}
|
||||
const first = pruneTerminalPane(node.first, retiredLeafIds)
|
||||
const second = pruneTerminalPane(node.second, retiredLeafIds)
|
||||
if (first && second) {
|
||||
return { ...node, first, second }
|
||||
}
|
||||
return first ?? second
|
||||
}
|
||||
|
||||
function collectTerminalLeafIds(node: TerminalPaneLayoutNode | null): string[] {
|
||||
if (!node) {
|
||||
return []
|
||||
}
|
||||
return node.type === 'leaf'
|
||||
? [node.leafId]
|
||||
: [...collectTerminalLeafIds(node.first), ...collectTerminalLeafIds(node.second)]
|
||||
}
|
||||
|
||||
function omitLeafRecords<T>(
|
||||
values: Record<string, T> | undefined,
|
||||
retiredLeafIds: ReadonlySet<string>
|
||||
): Record<string, T> | undefined {
|
||||
if (!values) {
|
||||
return undefined
|
||||
}
|
||||
const retained = Object.fromEntries(
|
||||
Object.entries(values).filter(([leafId]) => !retiredLeafIds.has(leafId))
|
||||
)
|
||||
return Object.keys(retained).length > 0 ? retained : undefined
|
||||
}
|
||||
|
||||
export function retireLeavesFromTerminalLayout(
|
||||
layout: TerminalLayoutSnapshot,
|
||||
retiredLeafIds: ReadonlySet<string>
|
||||
): TerminalLayoutSnapshot | null {
|
||||
const root = pruneTerminalPane(layout.root, retiredLeafIds)
|
||||
if (!root) {
|
||||
return null
|
||||
}
|
||||
const retainedLeafIds = collectTerminalLeafIds(root)
|
||||
const retainedLeafIdSet = new Set(retainedLeafIds)
|
||||
const activeLeafId =
|
||||
layout.activeLeafId && retainedLeafIdSet.has(layout.activeLeafId)
|
||||
? layout.activeLeafId
|
||||
: retainedLeafIds[0]!
|
||||
return {
|
||||
...layout,
|
||||
root,
|
||||
activeLeafId,
|
||||
expandedLeafId:
|
||||
layout.expandedLeafId && retainedLeafIdSet.has(layout.expandedLeafId)
|
||||
? layout.expandedLeafId
|
||||
: null,
|
||||
ptyIdsByLeafId: omitLeafRecords(layout.ptyIdsByLeafId, retiredLeafIds),
|
||||
buffersByLeafId: omitLeafRecords(layout.buffersByLeafId, retiredLeafIds),
|
||||
scrollbackRefsByLeafId: omitLeafRecords(layout.scrollbackRefsByLeafId, retiredLeafIds),
|
||||
titlesByLeafId: omitLeafRecords(layout.titlesByLeafId, retiredLeafIds)
|
||||
}
|
||||
}
|
||||
|
||||
export function pruneTabGroupLayoutAfterRetirement(
|
||||
layout: TabGroupLayoutNode | undefined,
|
||||
retainedGroupIds: ReadonlySet<string>
|
||||
): TabGroupLayoutNode | undefined {
|
||||
if (!layout) {
|
||||
return undefined
|
||||
}
|
||||
if (layout.type === 'leaf') {
|
||||
return retainedGroupIds.has(layout.groupId) ? layout : undefined
|
||||
}
|
||||
const first = pruneTabGroupLayoutAfterRetirement(layout.first, retainedGroupIds)
|
||||
const second = pruneTabGroupLayoutAfterRetirement(layout.second, retainedGroupIds)
|
||||
if (first && second) {
|
||||
return { ...layout, first, second }
|
||||
}
|
||||
return first ?? second
|
||||
}
|
||||
|
||||
function chooseGroupActiveTab(
|
||||
group: RuntimeMobileSessionTabGroup,
|
||||
retainedTabIds: ReadonlySet<string>
|
||||
): string | null {
|
||||
if (group.activeTabId && retainedTabIds.has(group.activeTabId)) {
|
||||
return group.activeTabId
|
||||
}
|
||||
const recent = (group.recentTabIds ?? []).toReversed().find((tabId) => retainedTabIds.has(tabId))
|
||||
return recent ?? group.tabOrder.find((tabId) => retainedTabIds.has(tabId)) ?? null
|
||||
}
|
||||
|
||||
export function repairMobileSessionTabGroupsAfterRetirement(
|
||||
groups: readonly RuntimeMobileSessionTabGroup[] | undefined,
|
||||
validTopLevelIds: ReadonlySet<string>
|
||||
): RuntimeMobileSessionTabGroup[] | undefined {
|
||||
if (!groups) {
|
||||
return undefined
|
||||
}
|
||||
const repaired = groups.flatMap((group) => {
|
||||
const tabOrder = group.tabOrder.filter((tabId) => validTopLevelIds.has(tabId))
|
||||
if (tabOrder.length === 0) {
|
||||
return []
|
||||
}
|
||||
const retained = new Set(tabOrder)
|
||||
const recentTabIds = group.recentTabIds?.filter((tabId) => retained.has(tabId))
|
||||
return [
|
||||
{
|
||||
...group,
|
||||
tabOrder,
|
||||
activeTabId: chooseGroupActiveTab(group, retained),
|
||||
...(recentTabIds && recentTabIds.length > 0 ? { recentTabIds } : {})
|
||||
}
|
||||
]
|
||||
})
|
||||
return repaired.length > 0 ? repaired : undefined
|
||||
}
|
||||
|
||||
function topLevelTabId(tab: RuntimeMobileSessionSnapshotTab): string {
|
||||
return tab.type === 'terminal' ? tab.parentTabId : tab.id
|
||||
}
|
||||
|
||||
function chooseActiveSurface(
|
||||
tabs: readonly RuntimeMobileSessionSnapshotTab[],
|
||||
previousActiveId: string | null,
|
||||
groups: readonly RuntimeMobileSessionTabGroup[] | undefined,
|
||||
previousActiveGroupId: string | null
|
||||
): RuntimeMobileSessionSnapshotTab | null {
|
||||
const previous = previousActiveId ? tabs.find((tab) => tab.id === previousActiveId) : undefined
|
||||
if (previous) {
|
||||
return previous
|
||||
}
|
||||
const activeGroup =
|
||||
groups?.find((group) => group.id === previousActiveGroupId) ?? groups?.[0] ?? null
|
||||
const activeTopLevelId = activeGroup?.activeTabId
|
||||
return (
|
||||
(activeTopLevelId
|
||||
? (tabs.find((tab) => topLevelTabId(tab) === activeTopLevelId && tab.isActive) ??
|
||||
tabs.find((tab) => topLevelTabId(tab) === activeTopLevelId))
|
||||
: undefined) ??
|
||||
tabs.find((tab) => tab.isActive) ??
|
||||
tabs[0] ??
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
function terminalMatchesRetirement(
|
||||
tab: RuntimeMobileSessionTerminalTab,
|
||||
ptyId: string,
|
||||
exactSurfaceKeys: ReadonlySet<string>,
|
||||
exactOnly: boolean
|
||||
): boolean {
|
||||
const surfaceKey = `${tab.parentTabId}\0${tab.leafId}`
|
||||
if (exactSurfaceKeys.has(surfaceKey)) {
|
||||
const leafPtyId = tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId]
|
||||
return (!tab.ptyId || tab.ptyId === ptyId) && (!leafPtyId || leafPtyId === ptyId)
|
||||
}
|
||||
if (exactOnly) {
|
||||
return false
|
||||
}
|
||||
return tab.ptyId === ptyId || tab.parentLayout?.ptyIdsByLeafId?.[tab.leafId] === ptyId
|
||||
}
|
||||
|
||||
export function retireTerminalSurfacesFromSnapshot(args: {
|
||||
snapshot: RuntimeMobileSessionTabsSnapshot
|
||||
ptyId: string
|
||||
exactSurfaces?: readonly Pick<RetiredTerminalSurface, 'parentTabId' | 'leafId'>[]
|
||||
exactOnly?: boolean
|
||||
}): { snapshot: RuntimeMobileSessionTabsSnapshot; retired: RetiredTerminalSurface[] } | null {
|
||||
const exactSurfaceKeys = new Set(
|
||||
(args.exactSurfaces ?? []).map((surface) => `${surface.parentTabId}\0${surface.leafId}`)
|
||||
)
|
||||
const retiredTabs = args.snapshot.tabs.filter(
|
||||
(tab): tab is RuntimeMobileSessionTerminalTab =>
|
||||
tab.type === 'terminal' &&
|
||||
terminalMatchesRetirement(tab, args.ptyId, exactSurfaceKeys, args.exactOnly === true)
|
||||
)
|
||||
if (retiredTabs.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const retiredLeafIdsByParent = new Map<string, Set<string>>()
|
||||
for (const tab of retiredTabs) {
|
||||
const leafIds = retiredLeafIdsByParent.get(tab.parentTabId) ?? new Set<string>()
|
||||
leafIds.add(tab.leafId)
|
||||
retiredLeafIdsByParent.set(tab.parentTabId, leafIds)
|
||||
}
|
||||
const retiredIds = new Set(retiredTabs.map((tab) => tab.id))
|
||||
let tabs = args.snapshot.tabs.filter((tab) => !retiredIds.has(tab.id))
|
||||
tabs = tabs.map((tab) => {
|
||||
if (tab.type !== 'terminal') {
|
||||
return tab
|
||||
}
|
||||
const retiredLeafIds = retiredLeafIdsByParent.get(tab.parentTabId)
|
||||
if (!retiredLeafIds) {
|
||||
return tab
|
||||
}
|
||||
const sourceLayout =
|
||||
tab.parentLayout ??
|
||||
retiredTabs.find((retired) => retired.parentTabId === tab.parentTabId)?.parentLayout
|
||||
const parentLayout = sourceLayout
|
||||
? retireLeavesFromTerminalLayout(sourceLayout, retiredLeafIds)
|
||||
: undefined
|
||||
return {
|
||||
...tab,
|
||||
...(parentLayout ? { parentLayout } : {}),
|
||||
isActive:
|
||||
tab.isActive ||
|
||||
retiredTabs.some((retired) => retired.parentTabId === tab.parentTabId && retired.isActive)
|
||||
}
|
||||
})
|
||||
|
||||
const validTopLevelIds = new Set(tabs.map(topLevelTabId))
|
||||
const tabGroups = repairMobileSessionTabGroupsAfterRetirement(
|
||||
args.snapshot.tabGroups,
|
||||
validTopLevelIds
|
||||
)
|
||||
const active = chooseActiveSurface(
|
||||
tabs,
|
||||
args.snapshot.activeTabId,
|
||||
tabGroups,
|
||||
args.snapshot.activeGroupId
|
||||
)
|
||||
tabs = tabs.map((tab) => ({ ...tab, isActive: tab.id === active?.id }))
|
||||
const activeTopLevelId = active ? topLevelTabId(active) : null
|
||||
const activeGroupId =
|
||||
(activeTopLevelId
|
||||
? tabGroups?.find((group) => group.tabOrder.includes(activeTopLevelId))?.id
|
||||
: undefined) ??
|
||||
tabGroups?.[0]?.id ??
|
||||
null
|
||||
const retainedGroupIds = new Set(tabGroups?.map((group) => group.id) ?? [])
|
||||
|
||||
return {
|
||||
snapshot: {
|
||||
...args.snapshot,
|
||||
snapshotVersion: args.snapshot.snapshotVersion + 1,
|
||||
activeGroupId,
|
||||
activeTabId: active?.id ?? null,
|
||||
activeTabType: active?.type ?? null,
|
||||
...(tabGroups ? { tabGroups } : { tabGroups: undefined }),
|
||||
...(args.snapshot.tabGroupLayout
|
||||
? {
|
||||
tabGroupLayout: pruneTabGroupLayoutAfterRetirement(
|
||||
args.snapshot.tabGroupLayout,
|
||||
retainedGroupIds
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
tabs
|
||||
},
|
||||
retired: retiredTabs.map((tab) => ({
|
||||
worktreeId: args.snapshot.worktree,
|
||||
parentTabId: tab.parentTabId,
|
||||
leafId: tab.leafId,
|
||||
ptyId: args.ptyId
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
RuntimeCreateAgentSessionRequest,
|
||||
RuntimeCreateAgentSessionResult
|
||||
} from '../../shared/agent-session-host-authority'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
|
||||
function operationId(now = Date.now()): string {
|
||||
return `${now}-0123456789abcdef0123456789abcdef`
|
||||
}
|
||||
|
||||
function request(
|
||||
clientOperationId: string,
|
||||
overrides: Partial<RuntimeCreateAgentSessionRequest> = {}
|
||||
): RuntimeCreateAgentSessionRequest {
|
||||
return {
|
||||
clientOperationId,
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
prompt: 'do the thing',
|
||||
presentation: 'background',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function terminal() {
|
||||
return {
|
||||
handle: 'term_operation',
|
||||
tabId: '11111111-1111-4111-8111-111111111111',
|
||||
paneKey: '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222',
|
||||
ptyId: 'pty-operation',
|
||||
worktreeId: 'worktree-1',
|
||||
title: null,
|
||||
surface: 'background' as const
|
||||
}
|
||||
}
|
||||
|
||||
function createRuntime(provider?: {
|
||||
supportsAgentSessionClaims?: () => boolean
|
||||
supportsAgentSessionCreateOperations?: () => boolean
|
||||
}) {
|
||||
const runtime = new OrcaRuntimeService(
|
||||
{
|
||||
getSettings: () => ({
|
||||
disabledTuiAgents: [],
|
||||
agentCmdOverrides: {},
|
||||
agentDefaultArgs: {},
|
||||
agentDefaultEnv: {}
|
||||
})
|
||||
} as never,
|
||||
undefined,
|
||||
provider ? { getLocalProvider: () => provider as never } : undefined
|
||||
)
|
||||
const internal = runtime as unknown as {
|
||||
resolveTerminalWorkspaceLaunchScope: ReturnType<typeof vi.fn>
|
||||
markLocalWorkspaceTrustedForAgent: ReturnType<typeof vi.fn>
|
||||
markRemoteWorkspaceTrustedForAgent: ReturnType<typeof vi.fn>
|
||||
}
|
||||
internal.resolveTerminalWorkspaceLaunchScope = vi.fn(async () => ({
|
||||
id: 'worktree-1',
|
||||
path: '/tmp/worktree-1',
|
||||
connectionId: null
|
||||
}))
|
||||
internal.markLocalWorkspaceTrustedForAgent = vi.fn()
|
||||
internal.markRemoteWorkspaceTrustedForAgent = vi.fn()
|
||||
return runtime
|
||||
}
|
||||
|
||||
describe('agent-session create operation ledger', () => {
|
||||
it('selects legacy before trust, spawn, or ledger state for an old daemon', async () => {
|
||||
const provider = {
|
||||
supportsAgentSessionClaims: vi.fn(() => false),
|
||||
supportsAgentSessionCreateOperations: vi.fn(() => false)
|
||||
}
|
||||
const runtime = createRuntime(provider)
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
const internal = runtime as unknown as {
|
||||
markLocalWorkspaceTrustedForAgent: ReturnType<typeof vi.fn>
|
||||
}
|
||||
const id = operationId()
|
||||
|
||||
await expect(runtime.createAgentSession(request(id))).rejects.toThrow(
|
||||
'agent_session_legacy_required'
|
||||
)
|
||||
await expect(
|
||||
runtime.ensureAgentSession({
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' }
|
||||
})
|
||||
).rejects.toThrow('agent_session_legacy_required')
|
||||
|
||||
expect(createTerminal).not.toHaveBeenCalled()
|
||||
expect(internal.markLocalWorkspaceTrustedForAgent).not.toHaveBeenCalled()
|
||||
|
||||
provider.supportsAgentSessionCreateOperations.mockReturnValue(true)
|
||||
await expect(runtime.createAgentSession(request(id))).resolves.toMatchObject({
|
||||
disposition: 'created'
|
||||
})
|
||||
provider.supportsAgentSessionCreateOperations.mockReturnValue(false)
|
||||
await expect(runtime.createAgentSession(request(id))).resolves.toMatchObject({
|
||||
disposition: 'replayed'
|
||||
})
|
||||
expect(createTerminal).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('requests exact client legacy fallback before nested SSH side effects', async () => {
|
||||
const runtime = createRuntime()
|
||||
const internal = runtime as unknown as {
|
||||
resolveTerminalWorkspaceLaunchScope: ReturnType<typeof vi.fn>
|
||||
}
|
||||
internal.resolveTerminalWorkspaceLaunchScope.mockResolvedValue({
|
||||
id: 'worktree-1',
|
||||
path: '/remote/worktree-1',
|
||||
connectionId: 'ssh-1'
|
||||
})
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
|
||||
await expect(
|
||||
runtime.ensureAgentSession({
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' }
|
||||
})
|
||||
).rejects.toThrow('agent_session_legacy_required')
|
||||
|
||||
expect(createTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('selects nested SSH legacy fallback before reading a Pi transcript path locally', async () => {
|
||||
const runtime = createRuntime()
|
||||
const internal = runtime as unknown as {
|
||||
resolveTerminalWorkspaceLaunchScope: ReturnType<typeof vi.fn>
|
||||
markRemoteWorkspaceTrustedForAgent: ReturnType<typeof vi.fn>
|
||||
}
|
||||
internal.resolveTerminalWorkspaceLaunchScope.mockResolvedValue({
|
||||
id: 'worktree-1',
|
||||
path: '/remote/worktree-1',
|
||||
connectionId: 'ssh-1'
|
||||
})
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
|
||||
await expect(
|
||||
runtime.ensureAgentSession({
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'pi',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'provider-session-1',
|
||||
transcriptPath: '/remote-only/pi/session.jsonl'
|
||||
}
|
||||
})
|
||||
).rejects.toThrow('agent_session_legacy_required')
|
||||
|
||||
expect(createTerminal).not.toHaveBeenCalled()
|
||||
expect(internal.markRemoteWorkspaceTrustedForAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('replays the same completed operation without spawning again', async () => {
|
||||
const runtime = createRuntime()
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
const id = operationId()
|
||||
|
||||
await expect(
|
||||
runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
).resolves.toMatchObject({ disposition: 'created' })
|
||||
await expect(
|
||||
runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
).resolves.toMatchObject({ disposition: 'replayed' })
|
||||
expect(createTerminal).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('joins concurrent retries and conflicts on a changed fingerprint', async () => {
|
||||
const runtime = createRuntime()
|
||||
let finish!: (result: ReturnType<typeof terminal>) => void
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
)
|
||||
const id = operationId()
|
||||
const first = runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
const joined = runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
|
||||
await expect(
|
||||
runtime.createAgentSession(request(id, { prompt: 'changed' }), { clientId: 'device-a' })
|
||||
).rejects.toThrow('agent_session_operation_conflict')
|
||||
await expect(
|
||||
runtime.createAgentSession(request(id, { agentArgs: '--profile changed' }), {
|
||||
clientId: 'device-a'
|
||||
})
|
||||
).rejects.toThrow('agent_session_operation_conflict')
|
||||
finish(terminal())
|
||||
await expect(first).resolves.toMatchObject({ disposition: 'created' })
|
||||
await expect(joined).resolves.toMatchObject({ disposition: 'replayed' })
|
||||
expect(createTerminal).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('isolates operation ids by authenticated caller', async () => {
|
||||
const runtime = createRuntime()
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
const id = operationId()
|
||||
|
||||
await runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
await runtime.createAgentSession(request(id), { clientId: 'device-b' })
|
||||
expect(createTerminal).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('rejects an expired unseen operation before terminal creation', async () => {
|
||||
const runtime = createRuntime()
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue(terminal())
|
||||
const expired = operationId(Date.now() - 25 * 60 * 60 * 1_000)
|
||||
|
||||
await expect(
|
||||
runtime.createAgentSession(request(expired), { clientId: 'device-a' })
|
||||
).rejects.toThrow('agent_session_operation_expired')
|
||||
expect(createTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('releases a failed pre-spawn operation for a safe retry', async () => {
|
||||
const runtime = createRuntime()
|
||||
const createTerminal = vi
|
||||
.spyOn(runtime, 'createTerminal')
|
||||
.mockRejectedValueOnce(new Error('pre-spawn failure'))
|
||||
.mockResolvedValueOnce(terminal())
|
||||
const id = operationId()
|
||||
|
||||
await expect(runtime.createAgentSession(request(id), { clientId: 'device-a' })).rejects.toThrow(
|
||||
'pre-spawn failure'
|
||||
)
|
||||
await expect(
|
||||
runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
).resolves.toMatchObject({ disposition: 'created' })
|
||||
expect(createTerminal).toHaveBeenCalledTimes(2)
|
||||
expect(createTerminal.mock.calls[0]?.[1]).toMatchObject({
|
||||
tabId: createTerminal.mock.calls[1]?.[1]?.tabId,
|
||||
leafId: createTerminal.mock.calls[1]?.[1]?.leafId,
|
||||
preAllocatedHandle: createTerminal.mock.calls[1]?.[1]?.preAllocatedHandle,
|
||||
agentSessionCreateOperationId:
|
||||
createTerminal.mock.calls[1]?.[1]?.agentSessionCreateOperationId
|
||||
})
|
||||
expect(createTerminal.mock.calls[0]?.[1]?.agentSessionCreateOperationId).toMatch(
|
||||
/^[A-Za-z0-9_-]{43}$/
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['controller admission fails', 'agent_session_exited_during_start'],
|
||||
['publication fails', 'post-spawn publication failure']
|
||||
])('retains a replay fence when %s after physical spawn commit', async (_case, message) => {
|
||||
const runtime = createRuntime()
|
||||
const failure = new Error(message)
|
||||
const createTerminal = vi
|
||||
.spyOn(runtime, 'createTerminal')
|
||||
.mockImplementation(async (_worktree, opts) => {
|
||||
opts?.onPtySpawnCommitted?.()
|
||||
throw failure
|
||||
})
|
||||
const id = operationId()
|
||||
|
||||
await expect(runtime.createAgentSession(request(id), { clientId: 'device-a' })).rejects.toThrow(
|
||||
failure.message
|
||||
)
|
||||
await expect(runtime.createAgentSession(request(id), { clientId: 'device-a' })).rejects.toThrow(
|
||||
failure.message
|
||||
)
|
||||
expect(createTerminal).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('retains a replay fence when the provider reports an unknown spawn outcome', async () => {
|
||||
const runtime = createRuntime()
|
||||
const failure = Object.assign(new Error('cleanup could not prove exit'), {
|
||||
agentSessionOperationOutcome: 'unknown' as const
|
||||
})
|
||||
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockRejectedValue(failure)
|
||||
const id = operationId()
|
||||
|
||||
const attempts: Promise<RuntimeCreateAgentSessionResult>[] = [
|
||||
runtime.createAgentSession(request(id), { clientId: 'device-a' }),
|
||||
runtime.createAgentSession(request(id), { clientId: 'device-a' })
|
||||
]
|
||||
await expect(Promise.all(attempts)).rejects.toThrow(failure.message)
|
||||
await expect(runtime.createAgentSession(request(id), { clientId: 'device-a' })).rejects.toThrow(
|
||||
failure.message
|
||||
)
|
||||
expect(createTerminal).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,666 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { getDefaultWorkspaceSession } from '../../shared/constants'
|
||||
import type {
|
||||
RuntimeMobileSessionTabsResult,
|
||||
RuntimeMobileSessionTabsSnapshot
|
||||
} from '../../shared/runtime-types'
|
||||
import type { WorkspaceSessionState } from '../../shared/types'
|
||||
import { sanitizeWorkspaceSessionTerminalRetirements } from './mobile-session-terminal-persistence-retirement'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
|
||||
const WORKTREE_ID = 'repo::/worktree'
|
||||
const REPO_ID = 'repo'
|
||||
|
||||
function makeSplitSnapshot(): RuntimeMobileSessionTabsSnapshot {
|
||||
const parentLayout = {
|
||||
root: {
|
||||
type: 'split' as const,
|
||||
direction: 'vertical' as const,
|
||||
first: { type: 'leaf' as const, leafId: 'left' },
|
||||
second: { type: 'leaf' as const, leafId: 'right' }
|
||||
},
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: 'left',
|
||||
ptyIdsByLeafId: { left: 'pty-left', right: 'pty-right' }
|
||||
}
|
||||
return {
|
||||
worktree: WORKTREE_ID,
|
||||
publicationEpoch: 'renderer',
|
||||
snapshotVersion: 1,
|
||||
activeGroupId: 'group',
|
||||
activeTabId: 'tab::left',
|
||||
activeTabType: 'terminal',
|
||||
tabGroups: [{ id: 'group', activeTabId: 'tab', tabOrder: ['tab'] }],
|
||||
tabs: [
|
||||
{
|
||||
type: 'terminal',
|
||||
id: 'tab::left',
|
||||
parentTabId: 'tab',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
title: 'Left',
|
||||
parentLayout,
|
||||
isActive: true
|
||||
},
|
||||
{
|
||||
type: 'terminal',
|
||||
id: 'tab::right',
|
||||
parentTabId: 'tab',
|
||||
leafId: 'right',
|
||||
ptyId: 'pty-right',
|
||||
title: 'Right',
|
||||
parentLayout,
|
||||
isActive: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function syncSplit(runtime: OrcaRuntimeService, snapshot = makeSplitSnapshot()): void {
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
activeLeafId: 'left',
|
||||
layout:
|
||||
snapshot.tabs[0]?.type === 'terminal'
|
||||
? (snapshot.tabs[0].parentLayout?.root ?? null)
|
||||
: null
|
||||
}
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'left',
|
||||
paneRuntimeId: 1,
|
||||
ptyId: 'pty-left'
|
||||
},
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'right',
|
||||
paneRuntimeId: 2,
|
||||
ptyId: 'pty-right'
|
||||
}
|
||||
],
|
||||
mobileSessionTabs: [snapshot]
|
||||
})
|
||||
}
|
||||
|
||||
function makePersistedSplitSession(): WorkspaceSessionState {
|
||||
return {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
{
|
||||
id: 'tab',
|
||||
ptyId: 'pty-left',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
tab: {
|
||||
root: {
|
||||
type: 'split' as const,
|
||||
direction: 'vertical' as const,
|
||||
first: { type: 'leaf' as const, leafId: 'left' },
|
||||
second: { type: 'leaf' as const, leafId: 'right' }
|
||||
},
|
||||
activeLeafId: 'left',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { left: 'pty-left', right: 'pty-right' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('OrcaRuntimeService terminal surface retirement', () => {
|
||||
it('releases each early-exit fence after its matching registration is rejected', () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const internals = runtime as unknown as {
|
||||
earlyExitedPtyIncarnations: Map<string, string | null>
|
||||
}
|
||||
|
||||
for (let index = 0; index < 1_000; index += 1) {
|
||||
const ptyId = `pty-early-${index}`
|
||||
const incarnationId = `incarnation-${index}`
|
||||
runtime.beginPtyRegistration(ptyId, incarnationId)
|
||||
runtime.onPtyExit(ptyId, 0, incarnationId)
|
||||
expect(() => runtime.assertPtyRegistrationAllowed(ptyId, incarnationId)).toThrow(
|
||||
'agent_session_exited_during_start'
|
||||
)
|
||||
runtime.releaseRejectedPtyRegistrationFence(ptyId, incarnationId)
|
||||
}
|
||||
|
||||
expect(internals.earlyExitedPtyIncarnations.size).toBe(0)
|
||||
})
|
||||
|
||||
it('does not retain fences for completed surface-less lifecycles', () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const internals = runtime as unknown as {
|
||||
earlyExitedPtyIncarnations: Map<string, string | null>
|
||||
pendingPtyRegistrationIncarnations: Map<string, string | null>
|
||||
}
|
||||
|
||||
for (let index = 0; index < 1_000; index += 1) {
|
||||
runtime.onPtySpawned(`pty-headless-${index}`, `incarnation-${index}`, {
|
||||
awaitsRegistration: false
|
||||
})
|
||||
runtime.onPtyExit(`pty-headless-${index}`, 0, `incarnation-${index}`)
|
||||
}
|
||||
|
||||
expect(internals.earlyExitedPtyIncarnations.size).toBe(0)
|
||||
expect(internals.pendingPtyRegistrationIncarnations.size).toBe(0)
|
||||
})
|
||||
|
||||
it('fences an early-exited replacement even when its pane already exists', () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
runtime.attachWindow(1)
|
||||
syncSplit(runtime)
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-old'
|
||||
})
|
||||
|
||||
runtime.onPtySpawned('pty-left', 'incarnation-replacement')
|
||||
runtime.onPtyExit('pty-left', 0, 'incarnation-replacement')
|
||||
|
||||
expect(() =>
|
||||
runtime.assertPtyRegistrationAllowed('pty-left', 'incarnation-replacement')
|
||||
).toThrow('agent_session_exited_during_start')
|
||||
runtime.releaseRejectedPtyRegistrationFence('pty-left', 'incarnation-replacement')
|
||||
const internals = runtime as unknown as {
|
||||
earlyExitedPtyIncarnations: Map<string, string | null>
|
||||
pendingPtyRegistrationIncarnations: Map<string, string | null>
|
||||
}
|
||||
expect(internals.earlyExitedPtyIncarnations.size).toBe(0)
|
||||
expect(internals.pendingPtyRegistrationIncarnations.size).toBe(0)
|
||||
})
|
||||
|
||||
it('retires the exact split leaf and rejects a stale renderer resurrection', async () => {
|
||||
const runtime = new OrcaRuntimeService()
|
||||
runtime.attachWindow(1)
|
||||
const staleSnapshot = makeSplitSnapshot()
|
||||
syncSplit(runtime, staleSnapshot)
|
||||
|
||||
runtime.onPtyExit('pty-left', 0)
|
||||
|
||||
expect(await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).toMatchObject({
|
||||
activeTabId: 'tab::right',
|
||||
tabs: [
|
||||
{
|
||||
id: 'tab::right',
|
||||
status: 'ready',
|
||||
terminal: expect.stringMatching(/^term_/),
|
||||
isActive: true,
|
||||
parentLayout: {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
syncSplit(runtime, { ...staleSnapshot, snapshotVersion: 2 })
|
||||
|
||||
const afterStaleFrame = await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)
|
||||
expect(afterStaleFrame.tabs.map((tab) => tab.id)).toEqual(['tab::right'])
|
||||
})
|
||||
|
||||
it('rejects one stale shared-PTY surface without removing its live sibling', () => {
|
||||
const session = makePersistedSplitSession()
|
||||
session.tabsByWorktree[WORKTREE_ID]![0]!.ptyId = 'pty-shared'
|
||||
session.terminalLayoutsByTabId.tab = {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-shared' }
|
||||
}
|
||||
session.terminalPtyIncarnationsByPaneKey = { 'tab:right': 'incarnation-current' }
|
||||
session.terminalTopologyRevisionByRepoId = { [REPO_ID]: 1 }
|
||||
const runtime = new OrcaRuntimeService({ getWorkspaceSession: () => session } as never)
|
||||
runtime.attachWindow(1)
|
||||
runtime.registerPty('pty-shared', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'right',
|
||||
incarnationId: 'incarnation-current'
|
||||
})
|
||||
const snapshot = makeSplitSnapshot()
|
||||
const incoming = {
|
||||
...snapshot,
|
||||
tabs: snapshot.tabs.map((tab) =>
|
||||
tab.type === 'terminal'
|
||||
? {
|
||||
...tab,
|
||||
ptyId: 'pty-shared',
|
||||
parentLayout: tab.parentLayout
|
||||
? {
|
||||
...tab.parentLayout,
|
||||
ptyIdsByLeafId: { left: 'pty-shared', right: 'pty-shared' }
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
: tab
|
||||
)
|
||||
}
|
||||
type IncomingTerminalTab = Extract<(typeof incoming.tabs)[number], { type: 'terminal' }>
|
||||
const rightTab = incoming.tabs.find(
|
||||
(tab): tab is IncomingTerminalTab => tab.type === 'terminal' && tab.leafId === 'right'
|
||||
)!
|
||||
const hostSnapshot: RuntimeMobileSessionTabsSnapshot = {
|
||||
...incoming,
|
||||
activeTabId: rightTab.id,
|
||||
tabs: [
|
||||
{
|
||||
...rightTab,
|
||||
parentLayout: {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-shared' }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
activeLeafId: 'right',
|
||||
layout: { type: 'leaf', leafId: 'right' }
|
||||
}
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'right',
|
||||
paneRuntimeId: 2,
|
||||
ptyId: 'pty-shared'
|
||||
}
|
||||
],
|
||||
mobileSessionTabs: [hostSnapshot]
|
||||
})
|
||||
;(
|
||||
runtime as unknown as {
|
||||
mobileSessionTabsByWorktree: Map<string, RuntimeMobileSessionTabsSnapshot>
|
||||
}
|
||||
).mobileSessionTabsByWorktree.set(WORKTREE_ID, hostSnapshot)
|
||||
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
activeLeafId: 'right',
|
||||
layout: incoming.tabs[0]?.type === 'terminal' ? incoming.tabs[0].parentLayout!.root : null
|
||||
}
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'left',
|
||||
paneRuntimeId: 1,
|
||||
ptyId: 'pty-shared'
|
||||
},
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'right',
|
||||
paneRuntimeId: 2,
|
||||
ptyId: 'pty-shared'
|
||||
}
|
||||
],
|
||||
mobileSessionTabs: [incoming]
|
||||
})
|
||||
|
||||
const internalSnapshot = (
|
||||
runtime as unknown as {
|
||||
mobileSessionTabsByWorktree: Map<string, RuntimeMobileSessionTabsSnapshot>
|
||||
}
|
||||
).mobileSessionTabsByWorktree.get(WORKTREE_ID)
|
||||
expect(internalSnapshot?.tabs).toEqual([
|
||||
expect.objectContaining({ id: 'tab::right', ptyId: 'pty-shared' })
|
||||
])
|
||||
})
|
||||
|
||||
it('honors a legacy persisted tombstone before its first migration write', async () => {
|
||||
const session = makePersistedSplitSession()
|
||||
session.tabsByWorktree[WORKTREE_ID]![0]!.ptyId = 'pty-right'
|
||||
session.terminalLayoutsByTabId.tab = {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
}
|
||||
Object.assign(session, {
|
||||
terminalSurfaceTombstonesByPaneKey: {
|
||||
'tab:left': {
|
||||
worktreeId: WORKTREE_ID,
|
||||
parentTabId: 'tab',
|
||||
leafId: 'left',
|
||||
ptyId: 'pty-left',
|
||||
incarnationId: 'incarnation-left',
|
||||
retiredAt: 42
|
||||
}
|
||||
}
|
||||
})
|
||||
const runtime = new OrcaRuntimeService({ getWorkspaceSession: () => session } as never)
|
||||
runtime.attachWindow(1)
|
||||
runtime.registerPty('pty-right', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'right',
|
||||
incarnationId: 'incarnation-right'
|
||||
})
|
||||
|
||||
syncSplit(runtime)
|
||||
|
||||
const tabs = (await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs
|
||||
expect(tabs).toHaveLength(1)
|
||||
expect(tabs[0]).toMatchObject({ type: 'terminal', ptyId: 'pty-right' })
|
||||
})
|
||||
|
||||
it('publishes the host-rebased layout after a stale client pane update', async () => {
|
||||
let session = makePersistedSplitSession()
|
||||
session.tabsByWorktree[WORKTREE_ID]![0]!.ptyId = 'pty-right'
|
||||
session.terminalLayoutsByTabId.tab = {
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
activeLeafId: 'right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
}
|
||||
Object.assign(session, {
|
||||
terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 }
|
||||
})
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession: (incoming: WorkspaceSessionState) => {
|
||||
session = sanitizeWorkspaceSessionTerminalRetirements(incoming, session)
|
||||
}
|
||||
} as never)
|
||||
|
||||
await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)
|
||||
await runtime.updateMobileSessionPaneLayout(`id:${WORKTREE_ID}`, {
|
||||
tabId: 'tab',
|
||||
root: {
|
||||
type: 'split',
|
||||
direction: 'vertical',
|
||||
first: { type: 'leaf', leafId: 'left' },
|
||||
second: { type: 'leaf', leafId: 'right' }
|
||||
},
|
||||
expandedLeafId: null,
|
||||
titlesByLeafId: { right: 'Survivor' }
|
||||
})
|
||||
|
||||
const tabs = (await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs
|
||||
expect(tabs).toHaveLength(1)
|
||||
expect(tabs[0]).toMatchObject({
|
||||
type: 'terminal',
|
||||
ptyId: 'pty-right',
|
||||
parentLayout: {
|
||||
root: { type: 'leaf', leafId: 'right' }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('retires a permanently exited surface despite a stale sleeping record', async () => {
|
||||
const session = {
|
||||
...getDefaultWorkspaceSession(),
|
||||
sleepingAgentSessionsByPaneKey: { 'tab:left': {} as never }
|
||||
}
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession: vi.fn(),
|
||||
flushOrThrow: vi.fn()
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
syncSplit(runtime)
|
||||
|
||||
runtime.onPtyExit('pty-left', 0)
|
||||
|
||||
const result = await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)
|
||||
expect(result.tabs.find((tab) => tab.id === 'tab::left')).toBeUndefined()
|
||||
expect(result.tabs.find((tab) => tab.id === 'tab::right')).toMatchObject({
|
||||
status: 'ready'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores a delayed exit from an older incarnation of a reused PTY id', async () => {
|
||||
const setWorkspaceSession = vi.fn()
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => makePersistedSplitSession(),
|
||||
setWorkspaceSession
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
syncSplit(runtime)
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-a'
|
||||
})
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-b'
|
||||
})
|
||||
|
||||
runtime.onPtyExit('pty-left', 0, 'incarnation-a')
|
||||
|
||||
expect((await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs).toEqual([
|
||||
expect.objectContaining({ id: 'tab::left', status: 'ready' }),
|
||||
expect.objectContaining({ id: 'tab::right', status: 'ready' })
|
||||
])
|
||||
expect(setWorkspaceSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retires a durable surface after reconnect proves a newer incarnation', async () => {
|
||||
const session = makePersistedSplitSession()
|
||||
const setWorkspaceSession = vi.fn()
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession,
|
||||
flushOrThrow: vi.fn()
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
syncSplit(runtime)
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-before-reconnect'
|
||||
})
|
||||
|
||||
runtime.acceptPtyIncarnationForExit('pty-left', 'incarnation-after-reconnect')
|
||||
runtime.onPtyExit('pty-left', 0, 'incarnation-after-reconnect')
|
||||
|
||||
expect((await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs).toEqual([
|
||||
expect.objectContaining({ id: 'tab::right', status: 'ready' })
|
||||
])
|
||||
expect(setWorkspaceSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
terminalLayoutsByTabId: {
|
||||
tab: expect.objectContaining({
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
})
|
||||
}
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('publishes only same-repo retirements individually accepted by persistence', async () => {
|
||||
let session = makePersistedSplitSession()
|
||||
session.terminalLayoutsByTabId.tab.ptyIdsByLeafId = {
|
||||
left: 'pty-shared',
|
||||
right: 'pty-shared'
|
||||
}
|
||||
session.tabsByWorktree[WORKTREE_ID]![0]!.ptyId = 'pty-shared'
|
||||
session.terminalPtyIncarnationsByPaneKey = {
|
||||
'tab:left': 'incarnation-exiting',
|
||||
'tab:right': 'incarnation-newer'
|
||||
}
|
||||
const setWorkspaceSession = vi.fn((next: WorkspaceSessionState) => {
|
||||
session = next
|
||||
})
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession,
|
||||
flushOrThrow: vi.fn()
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
const snapshot = makeSplitSnapshot()
|
||||
const sharedSnapshot: RuntimeMobileSessionTabsSnapshot = {
|
||||
...snapshot,
|
||||
tabs: snapshot.tabs.map((tab) =>
|
||||
tab.type === 'terminal'
|
||||
? {
|
||||
...tab,
|
||||
ptyId: 'pty-shared',
|
||||
parentLayout: tab.parentLayout
|
||||
? {
|
||||
...tab.parentLayout,
|
||||
ptyIdsByLeafId: { left: 'pty-shared', right: 'pty-shared' }
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
: tab
|
||||
)
|
||||
}
|
||||
syncSplit(runtime, sharedSnapshot)
|
||||
runtime.registerPty('pty-shared', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-exiting'
|
||||
})
|
||||
const published: RuntimeMobileSessionTabsResult[] = []
|
||||
const unsubscribe = runtime.onMobileSessionTabsChanged((event) => published.push(event))
|
||||
|
||||
runtime.onPtyExit('pty-shared', 0, 'incarnation-exiting')
|
||||
|
||||
expect(session.terminalLayoutsByTabId.tab).toMatchObject({
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
ptyIdsByLeafId: { right: 'pty-shared' }
|
||||
})
|
||||
expect(session.terminalPtyIncarnationsByPaneKey).toEqual({
|
||||
'tab:right': 'incarnation-newer'
|
||||
})
|
||||
expect(published.at(-1)?.tabs).toEqual([
|
||||
expect.objectContaining({
|
||||
ptyId: 'pty-shared',
|
||||
parentLayout: expect.objectContaining({ root: { type: 'leaf', leafId: 'right' } })
|
||||
})
|
||||
])
|
||||
expect((await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs).toEqual([
|
||||
expect.objectContaining({
|
||||
ptyId: 'pty-shared',
|
||||
parentLayout: expect.objectContaining({ root: { type: 'leaf', leafId: 'right' } })
|
||||
})
|
||||
])
|
||||
expect(setWorkspaceSession).toHaveBeenCalledOnce()
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('de-persists an exact surface even when there is no mobile snapshot', () => {
|
||||
const session = makePersistedSplitSession()
|
||||
const setWorkspaceSession = vi.fn()
|
||||
const flushOrThrow = vi.fn()
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession,
|
||||
flushOrThrow
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Terminal',
|
||||
activeLeafId: 'left',
|
||||
layout: { type: 'leaf', leafId: 'left' }
|
||||
}
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
tabId: 'tab',
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: 'left',
|
||||
paneRuntimeId: 1,
|
||||
ptyId: 'pty-left'
|
||||
}
|
||||
]
|
||||
})
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-a'
|
||||
})
|
||||
|
||||
runtime.onPtyExit('pty-left', 0, 'incarnation-a')
|
||||
|
||||
expect(setWorkspaceSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
terminalLayoutsByTabId: {
|
||||
tab: expect.objectContaining({
|
||||
root: { type: 'leaf', leafId: 'right' },
|
||||
ptyIdsByLeafId: { right: 'pty-right' }
|
||||
})
|
||||
},
|
||||
terminalSurfaceTombstonesByPaneKey: {},
|
||||
terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 }
|
||||
})
|
||||
)
|
||||
expect(flushOrThrow).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('does not publish absence when the durable retirement flush fails', async () => {
|
||||
const session = makePersistedSplitSession()
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const runtime = new OrcaRuntimeService({
|
||||
getWorkspaceSession: () => session,
|
||||
setWorkspaceSession: vi.fn(),
|
||||
flushOrThrow: vi.fn(() => {
|
||||
throw new Error('disk unavailable')
|
||||
})
|
||||
} as never)
|
||||
runtime.attachWindow(1)
|
||||
syncSplit(runtime)
|
||||
runtime.registerPty('pty-left', WORKTREE_ID, null, {
|
||||
tabId: 'tab',
|
||||
leafId: 'left',
|
||||
incarnationId: 'incarnation-a'
|
||||
})
|
||||
const events: unknown[] = []
|
||||
const unsubscribe = runtime.onMobileSessionTabsChanged((event) => events.push(event))
|
||||
|
||||
runtime.onPtyExit('pty-left', 0, 'incarnation-a')
|
||||
|
||||
expect((await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)).tabs).toEqual([
|
||||
expect.objectContaining({ id: 'tab::left' }),
|
||||
expect.objectContaining({ id: 'tab::right' })
|
||||
])
|
||||
expect(events).toEqual([])
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
'[runtime] failed to persist terminal retirement:',
|
||||
expect.any(Error)
|
||||
)
|
||||
unsubscribe()
|
||||
errorSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -93,6 +93,10 @@ import {
|
||||
import { advertisedUrlWatcher } from '../ports/advertised-url-watcher'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV } from '../../shared/setup-agent-sequencing'
|
||||
import type {
|
||||
AgentSessionExecutionClaim,
|
||||
AgentSessionSurfaceBinding
|
||||
} from '../../shared/agent-session-host-authority'
|
||||
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree-id'
|
||||
import { RpcDispatcher } from './rpc/dispatcher'
|
||||
import type { RpcRequest } from './rpc/core'
|
||||
@@ -10537,6 +10541,153 @@ describe('OrcaRuntimeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('does not register or publish a PTY incarnation that exited before spawn resolved', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
const tabId = '11111111-1111-4111-8111-111111111111'
|
||||
const leafId = '22222222-2222-4222-8222-222222222222'
|
||||
runtime.setPtyController({
|
||||
spawn: vi.fn(async () => {
|
||||
runtime.beginPtyRegistration('pty-exited-during-start', 'incarnation-exited-during-start')
|
||||
runtime.onPtyExit('pty-exited-during-start', 0, 'incarnation-exited-during-start')
|
||||
return {
|
||||
id: 'pty-exited-during-start',
|
||||
incarnationId: 'incarnation-exited-during-start'
|
||||
}
|
||||
}),
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
|
||||
await expect(
|
||||
runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, {
|
||||
command: 'codex',
|
||||
presentation: 'background',
|
||||
tabId,
|
||||
leafId,
|
||||
persistHostSessionBinding: true
|
||||
})
|
||||
).rejects.toThrow('agent_session_exited_during_start')
|
||||
await expect(runtime.listTerminals(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({
|
||||
terminals: []
|
||||
})
|
||||
await expect(runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({
|
||||
tabs: []
|
||||
})
|
||||
const internals = runtime as unknown as {
|
||||
handleByPtyId: Map<string, string>
|
||||
ptysById: Map<string, unknown>
|
||||
}
|
||||
expect(internals.handleByPtyId.has('pty-exited-during-start')).toBe(false)
|
||||
expect(internals.ptysById.has('pty-exited-during-start')).toBe(false)
|
||||
})
|
||||
|
||||
it('adopts the execution owner canonical surface for repeated structured resumes', async () => {
|
||||
let canonicalOwner:
|
||||
| {
|
||||
claim: AgentSessionExecutionClaim
|
||||
generation: string
|
||||
phase: 'live'
|
||||
ptyId: string
|
||||
surface: AgentSessionSurfaceBinding
|
||||
}
|
||||
| undefined
|
||||
const spawn = vi.fn(async (options) => {
|
||||
const ensure = options.agentSessionEnsure
|
||||
expect(ensure).toBeDefined()
|
||||
canonicalOwner ??= {
|
||||
claim: ensure!.claim,
|
||||
generation: 'generation-1',
|
||||
phase: 'live',
|
||||
ptyId: 'pty-claimed',
|
||||
surface: ensure!.surface
|
||||
}
|
||||
return {
|
||||
id: 'pty-claimed',
|
||||
agentSessionEnsure: {
|
||||
disposition: spawn.mock.calls.length === 1 ? ('created' as const) : ('adopted' as const),
|
||||
owner: canonicalOwner
|
||||
}
|
||||
}
|
||||
})
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
runtime.setPtyController({
|
||||
spawn,
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
|
||||
const request = {
|
||||
kind: 'explicit' as const,
|
||||
worktree: `id:${TEST_WORKTREE_ID}`,
|
||||
agent: 'codex' as const,
|
||||
providerSession: { key: 'session_id' as const, id: 'provider-session-1' }
|
||||
}
|
||||
const first = await runtime.ensureAgentSession(request)
|
||||
const second = await runtime.ensureAgentSession(request)
|
||||
|
||||
expect(first.disposition).toBe('created')
|
||||
expect(second.disposition).toBe('adopted')
|
||||
expect(second.terminal).toMatchObject({
|
||||
handle: first.terminal.handle,
|
||||
tabId: first.terminal.tabId,
|
||||
paneKey: first.terminal.paneKey
|
||||
})
|
||||
expect(spawn).toHaveBeenCalledTimes(2)
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: expect.stringContaining("'resume' 'provider-session-1'"),
|
||||
agentSessionEnsure: expect.objectContaining({
|
||||
claim: expect.objectContaining({ agent: 'codex' })
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('builds structured fresh drafts with supported launch preferences on the host', async () => {
|
||||
const spawn = vi.fn().mockResolvedValue({ id: 'pty-agent-draft' })
|
||||
const runtime = new OrcaRuntimeService({
|
||||
...store,
|
||||
getSettings: () => ({
|
||||
...store.getSettings(),
|
||||
disabledTuiAgents: [],
|
||||
agentCmdOverrides: { claude: 'host-claude' },
|
||||
agentDefaultArgs: { claude: '--host-default' },
|
||||
agentDefaultEnv: { claude: { HOST_PROFILE: 'true' } }
|
||||
})
|
||||
})
|
||||
runtime.setPtyController({
|
||||
spawn,
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
|
||||
await runtime.createAgentSession(
|
||||
{
|
||||
clientOperationId: `${Date.now()}-${'ab'.repeat(16)}`,
|
||||
worktree: `id:${TEST_WORKTREE_ID}`,
|
||||
agent: 'claude',
|
||||
prompt: 'review before sending',
|
||||
promptDelivery: 'draft',
|
||||
agentArgs: '--permission-mode plan',
|
||||
launchPreferences: { model: 'opus', effort: 'high' }
|
||||
},
|
||||
{ clientId: 'renderer-1', clientKind: 'runtime' }
|
||||
)
|
||||
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: expect.stringMatching(
|
||||
/^host-claude '--model' 'opus'.*'--permission-mode' 'plan'.*--prefill 'review before sending'/
|
||||
),
|
||||
env: expect.objectContaining({ HOST_PROFILE: 'true' })
|
||||
})
|
||||
)
|
||||
expect(spawn.mock.calls[0]?.[0]?.command).not.toContain('--host-default')
|
||||
})
|
||||
|
||||
it('applies Settings agent defaults to bare agent command terminal creates', async () => {
|
||||
const spawn = vi.fn().mockResolvedValue({ id: 'pty-bg' })
|
||||
const runtimeStore = {
|
||||
@@ -17932,7 +18083,7 @@ describe('OrcaRuntimeService', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('does not publish exited saved PTY bindings as ready terminal streams', async () => {
|
||||
it('retires exited saved PTY bindings instead of publishing a pending ghost', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
runtime.attachWindow(1)
|
||||
runtime.syncWindowGraph(1, {
|
||||
@@ -17966,14 +18117,12 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
const result = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)
|
||||
|
||||
expect(result.tabs).toEqual([
|
||||
expect.objectContaining({
|
||||
type: 'terminal',
|
||||
id: 'tab-1::pane:1',
|
||||
status: 'pending-handle',
|
||||
terminal: null
|
||||
})
|
||||
])
|
||||
expect(result).toMatchObject({
|
||||
activeGroupId: null,
|
||||
activeTabId: null,
|
||||
activeTabType: null,
|
||||
tabs: []
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves mobile terminal surfaces by exact split leaf', async () => {
|
||||
@@ -19779,7 +19928,7 @@ describe('OrcaRuntimeService', () => {
|
||||
expect(suppressed?.type === 'terminal' && suppressed.agentStatus?.terminalTitle).toBeUndefined()
|
||||
})
|
||||
|
||||
it('pushes PTY-backed mobile session readiness changes when a server PTY exits', async () => {
|
||||
it('pushes PTY-backed mobile session retirement when a server PTY exits', async () => {
|
||||
const spawn = vi.fn().mockResolvedValue({ id: 'laptop-created-pty' })
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
runtime.setPtyController({
|
||||
@@ -19801,14 +19950,10 @@ describe('OrcaRuntimeService', () => {
|
||||
|
||||
expect(events).toEqual([
|
||||
expect.objectContaining({
|
||||
tabs: [
|
||||
expect.objectContaining({
|
||||
type: 'terminal',
|
||||
parentTabId: 'laptop-tab',
|
||||
status: 'pending-handle',
|
||||
terminal: null
|
||||
})
|
||||
]
|
||||
activeGroupId: null,
|
||||
activeTabId: null,
|
||||
activeTabType: null,
|
||||
tabs: []
|
||||
})
|
||||
])
|
||||
await expect(runtime.readTerminal(laptopTerminal.handle)).resolves.toMatchObject({
|
||||
@@ -22259,6 +22404,53 @@ describe('OrcaRuntimeService', () => {
|
||||
expect(listProcesses).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps a live persisted PTY whose pane binding has not reconnected yet', async () => {
|
||||
const ptyId = 'persisted-pty'
|
||||
const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(
|
||||
makeWorkspaceSessionWithHeadlessTerminal({
|
||||
tabsByWorktree: {
|
||||
[TEST_WORKTREE_ID]: [
|
||||
{
|
||||
id: 'host-tab',
|
||||
ptyId,
|
||||
worktreeId: TEST_WORKTREE_ID,
|
||||
title: 'Persisted Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: ptyId })
|
||||
}
|
||||
})
|
||||
)
|
||||
const kill = vi.fn(() => true)
|
||||
const runtime = new OrcaRuntimeService(runtimeStore as never)
|
||||
runtime.setPtyController({
|
||||
write: () => true,
|
||||
kill,
|
||||
getForegroundProcess: async () => null,
|
||||
listProcesses: async () => [{ id: ptyId, cwd: TEST_WORKTREE_PATH, title: 'Live' }]
|
||||
})
|
||||
|
||||
const result = await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab', {
|
||||
reason: 'cleanup'
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
closed: true,
|
||||
refused: true,
|
||||
refusalReason: 'live-host-pty',
|
||||
snapshotRepublished: true
|
||||
})
|
||||
expect(kill).not.toHaveBeenCalled()
|
||||
expect(getSession().tabsByWorktree[TEST_WORKTREE_ID]).toHaveLength(1)
|
||||
expect(getSession().terminalLayoutsByTabId['host-tab']).toBeDefined()
|
||||
})
|
||||
|
||||
it('keeps an explicit user close destructive while the PTY is live', async () => {
|
||||
const { runtime, closeTerminalTab } = makeAdoptedLiveTabRuntime()
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,233 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants'
|
||||
import { parsePairingCode } from '../../shared/pairing'
|
||||
import { RemoteRuntimeRequestConnection } from '../../shared/remote-runtime-request-connection'
|
||||
import type {
|
||||
RuntimeEnsureAgentSessionResult,
|
||||
RuntimeEnsureAgentSessionRequest
|
||||
} from '../../shared/agent-session-host-authority'
|
||||
import type { RuntimeMobileSessionTabsResult } from '../../shared/runtime-types'
|
||||
import type { SubprocessHandle } from '../daemon/session'
|
||||
import { TerminalHost } from '../daemon/terminal-host'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
import { OrcaRuntimeRpcServer } from './runtime-rpc'
|
||||
|
||||
const TEST_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_MS = 5_000
|
||||
|
||||
type ControlledSubprocess = SubprocessHandle & { exit: (code?: number) => void }
|
||||
|
||||
function createControlledSubprocess(): ControlledSubprocess {
|
||||
let onExit: ((code: number) => void) | null = null
|
||||
let exited = false
|
||||
const exit = (code = 0): void => {
|
||||
if (exited) {
|
||||
return
|
||||
}
|
||||
exited = true
|
||||
onExit?.(code)
|
||||
}
|
||||
return {
|
||||
pid: 41_000,
|
||||
getForegroundProcess: () => (exited ? null : 'claude'),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
kill: () => exit(0),
|
||||
forceKill: () => exit(137),
|
||||
signal: vi.fn(),
|
||||
onData: vi.fn(),
|
||||
onExit: (listener) => {
|
||||
onExit = listener
|
||||
},
|
||||
dispose: vi.fn(),
|
||||
exit
|
||||
}
|
||||
}
|
||||
|
||||
function requirePairing(server: OrcaRuntimeRpcServer, name: string) {
|
||||
const offer = server.createPairingOffer({ name, scope: 'runtime' })
|
||||
if (!offer.available) {
|
||||
throw new Error('pairing unavailable')
|
||||
}
|
||||
const pairing = parsePairingCode(offer.pairingUrl)
|
||||
if (!pairing) {
|
||||
throw new Error('invalid pairing')
|
||||
}
|
||||
return pairing
|
||||
}
|
||||
|
||||
describe('remote agent-session host authority integration', () => {
|
||||
const cleanups: (() => void | Promise<void>)[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0).toReversed()) {
|
||||
await cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it(
|
||||
'deduplicates racing remote resumes, adopts retries, and retires exited surfaces',
|
||||
{ timeout: TEST_TIMEOUT_MS },
|
||||
async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-agent-authority-repro-'))
|
||||
cleanups.push(() => rmSync(userDataPath, { recursive: true, force: true }))
|
||||
|
||||
const subprocesses: ControlledSubprocess[] = []
|
||||
const spawnSubprocess = vi.fn(() => {
|
||||
const subprocess = createControlledSubprocess()
|
||||
subprocesses.push(subprocess)
|
||||
return subprocess
|
||||
})
|
||||
const host = new TerminalHost({ spawnSubprocess })
|
||||
cleanups.push(() => host.dispose())
|
||||
|
||||
const store = {
|
||||
getSettings: () => ({
|
||||
workspaceDir: userDataPath,
|
||||
nestWorkspaces: false,
|
||||
refreshLocalBaseRefOnWorktreeCreate: false,
|
||||
branchPrefix: 'none',
|
||||
branchPrefixCustom: '',
|
||||
disabledTuiAgents: [],
|
||||
agentCmdOverrides: {},
|
||||
agentDefaultArgs: {},
|
||||
agentDefaultEnv: {}
|
||||
}),
|
||||
getRepos: () => [],
|
||||
getRepo: () => undefined,
|
||||
getAllWorktreeMeta: () => ({}),
|
||||
getWorktreeMeta: () => undefined,
|
||||
getProjects: () => []
|
||||
}
|
||||
const runtime = new OrcaRuntimeService(store as never)
|
||||
let nextRequestedSession = 0
|
||||
runtime.setPtyController({
|
||||
spawn: async (options) => {
|
||||
const requestedSessionId = `remote-repro-${++nextRequestedSession}`
|
||||
let resolvedSessionId = requestedSessionId
|
||||
const result = await host.createOrAttach({
|
||||
sessionId: requestedSessionId,
|
||||
cols: options.cols,
|
||||
rows: options.rows,
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
command: options.command,
|
||||
startupCommandDelivery: options.startupCommandDelivery,
|
||||
launchAgent: options.launchAgent,
|
||||
agentSessionEnsure: options.agentSessionEnsure,
|
||||
streamClient: {
|
||||
onData: (data) => runtime.onPtyData(resolvedSessionId, data, Date.now()),
|
||||
onExit: (code) => runtime.onPtyExit(resolvedSessionId, code)
|
||||
},
|
||||
onSessionResolved: (sessionId) => {
|
||||
resolvedSessionId = sessionId
|
||||
}
|
||||
})
|
||||
return {
|
||||
id: result.agentSessionEnsure?.owner.ptyId ?? resolvedSessionId,
|
||||
...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {})
|
||||
}
|
||||
},
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => 'claude'
|
||||
})
|
||||
|
||||
const server = new OrcaRuntimeRpcServer({
|
||||
runtime,
|
||||
userDataPath,
|
||||
enableWebSocket: true,
|
||||
wsPort: 0
|
||||
})
|
||||
await server.start()
|
||||
cleanups.push(() => server.stop())
|
||||
|
||||
const firstClient = new RemoteRuntimeRequestConnection(requirePairing(server, 'client-one'))
|
||||
const secondClient = new RemoteRuntimeRequestConnection(requirePairing(server, 'client-two'))
|
||||
const retryClient = new RemoteRuntimeRequestConnection(requirePairing(server, 'retry-client'))
|
||||
cleanups.push(() => firstClient.close())
|
||||
cleanups.push(() => secondClient.close())
|
||||
cleanups.push(() => retryClient.close())
|
||||
|
||||
const request: RuntimeEnsureAgentSessionRequest = {
|
||||
kind: 'explicit',
|
||||
worktree: `id:${FLOATING_TERMINAL_WORKTREE_ID}`,
|
||||
agent: 'claude',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-repro' },
|
||||
presentation: 'background'
|
||||
}
|
||||
const [first, second] = await Promise.all([
|
||||
firstClient.request<RuntimeEnsureAgentSessionResult>(
|
||||
'terminal.ensureAgentSession',
|
||||
request,
|
||||
REQUEST_TIMEOUT_MS
|
||||
),
|
||||
secondClient.request<RuntimeEnsureAgentSessionResult>(
|
||||
'terminal.ensureAgentSession',
|
||||
request,
|
||||
REQUEST_TIMEOUT_MS
|
||||
)
|
||||
])
|
||||
|
||||
expect(first.ok).toBe(true)
|
||||
expect(second.ok).toBe(true)
|
||||
if (!first.ok || !second.ok) {
|
||||
throw new Error('structured resume failed')
|
||||
}
|
||||
expect([first.result.disposition, second.result.disposition].sort()).toEqual([
|
||||
'adopted',
|
||||
'created'
|
||||
])
|
||||
expect(second.result.terminal).toMatchObject({
|
||||
handle: first.result.terminal.handle,
|
||||
tabId: first.result.terminal.tabId,
|
||||
paneKey: first.result.terminal.paneKey,
|
||||
ptyId: first.result.terminal.ptyId
|
||||
})
|
||||
expect(spawnSubprocess).toHaveBeenCalledOnce()
|
||||
expect(host.listSessions()).toHaveLength(1)
|
||||
|
||||
// Why: a retry cannot prove whether its previous response arrived, so
|
||||
// the provider identity—not a new client operation—must recover the owner.
|
||||
const retry = await retryClient.request<RuntimeEnsureAgentSessionResult>(
|
||||
'terminal.ensureAgentSession',
|
||||
request,
|
||||
REQUEST_TIMEOUT_MS
|
||||
)
|
||||
expect(retry).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
disposition: 'adopted',
|
||||
terminal: {
|
||||
handle: first.result.terminal.handle,
|
||||
tabId: first.result.terminal.tabId,
|
||||
paneKey: first.result.terminal.paneKey,
|
||||
ptyId: first.result.terminal.ptyId
|
||||
}
|
||||
}
|
||||
})
|
||||
expect(spawnSubprocess).toHaveBeenCalledOnce()
|
||||
|
||||
subprocesses[0]?.exit(0)
|
||||
await vi.waitFor(async () => {
|
||||
const [terminals, tabs] = await Promise.all([
|
||||
firstClient.request<{ terminals: unknown[] }>(
|
||||
'terminal.list',
|
||||
{ worktree: `id:${FLOATING_TERMINAL_WORKTREE_ID}` },
|
||||
REQUEST_TIMEOUT_MS
|
||||
),
|
||||
secondClient.request<RuntimeMobileSessionTabsResult>(
|
||||
'session.tabs.list',
|
||||
{ worktree: `id:${FLOATING_TERMINAL_WORKTREE_ID}` },
|
||||
REQUEST_TIMEOUT_MS
|
||||
)
|
||||
])
|
||||
expect(terminals).toMatchObject({ ok: true, result: { terminals: [] } })
|
||||
expect(tabs).toMatchObject({ ok: true, result: { tabs: [] } })
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core'
|
||||
import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery'
|
||||
import { COMPUTER_ERROR_CODES } from '../../../shared/runtime-types'
|
||||
import { LINEAR_ERROR_CODES } from '../../../shared/linear-agent-access'
|
||||
import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../shared/agent-session-host-authority'
|
||||
|
||||
export function successResponse(id: string, meta: RpcEnvelopeMeta, result: unknown): RpcSuccess {
|
||||
return {
|
||||
@@ -49,7 +50,8 @@ const RUNTIME_PASSTHROUGH_CODES: ReadonlySet<string> = new Set([
|
||||
'no_active_terminal',
|
||||
'repo_not_found',
|
||||
'timeout',
|
||||
'invalid_limit'
|
||||
'invalid_limit',
|
||||
...AGENT_SESSION_RPC_ERROR_CODES
|
||||
])
|
||||
|
||||
const COMPUTER_PASSTHROUGH_CODES: ReadonlySet<string> = new Set(Object.values(COMPUTER_ERROR_CODES))
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY,
|
||||
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
|
||||
RUNTIME_CAPABILITIES,
|
||||
RUNTIME_PROTOCOL_VERSION
|
||||
} from '../../../../shared/protocol-version'
|
||||
import { AGENT_SESSION_RPC_ERROR_CODES } from '../../../../shared/agent-session-host-authority'
|
||||
import { AGENT_SESSION_OPERATION_FUTURE_SKEW_MS } from '../../../../shared/agent-session-host-authority'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { RpcRequest, RpcResponse } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { AGENT_SESSION_METHODS } from './agent-session'
|
||||
import { TERMINAL_METHODS } from './terminal'
|
||||
|
||||
function request(method: string, params: unknown): RpcRequest {
|
||||
return { id: 'request-1', authToken: 'token', method, params }
|
||||
}
|
||||
|
||||
function terminalResult(disposition: 'created' | 'adopted' | 'replayed' = 'created') {
|
||||
return {
|
||||
terminal: {
|
||||
handle: 'term_1',
|
||||
worktreeId: 'worktree-1',
|
||||
title: null
|
||||
},
|
||||
disposition
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeStub() {
|
||||
return {
|
||||
getRuntimeId: () => 'runtime-1',
|
||||
ensureAgentSession: vi.fn().mockResolvedValue(terminalResult()),
|
||||
createAgentSession: vi.fn().mockResolvedValue(terminalResult())
|
||||
}
|
||||
}
|
||||
|
||||
describe('agent session RPC methods', () => {
|
||||
it('dispatches an explicit structured resume without an authoritative command', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.ensureAgentSession', {
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' },
|
||||
agentArgs: '--profile review',
|
||||
launchPreferences: { model: 'gpt-5', effort: 'high' },
|
||||
presentation: 'focused',
|
||||
placement: { tabId: 'tab-1', leafId: 'leaf-1' }
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: true, result: { disposition: 'created' } })
|
||||
expect(runtime.ensureAgentSession).toHaveBeenCalledWith(
|
||||
{
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' },
|
||||
agentArgs: '--profile review',
|
||||
launchPreferences: { model: 'gpt-5', effort: 'high' },
|
||||
presentation: 'focused',
|
||||
placement: { tabId: 'tab-1', leafId: 'leaf-1' }
|
||||
},
|
||||
{}
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps automatic authority checkpoint-only', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.ensureAgentSession', {
|
||||
kind: 'automatic',
|
||||
sleepingCheckpointId: 'checkpoint_123456789012345678901',
|
||||
worktree: 'id:forged',
|
||||
placement: { tabId: 'forged' }
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(runtime.ensureAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects mismatched agent/provider identity before runtime mutation', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.ensureAgentSession', {
|
||||
kind: 'explicit',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'antigravity',
|
||||
providerSession: { key: 'session_id', id: 'provider-session-1' }
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(runtime.ensureAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects opaque fresh-launch authority and malformed operation IDs', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const opaque = await dispatcher.dispatch(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
command: 'codex resume provider-session-1'
|
||||
})
|
||||
)
|
||||
const malformed = await dispatcher.dispatch(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: 'not-time-sortable',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex'
|
||||
})
|
||||
)
|
||||
|
||||
expect(opaque).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(malformed).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(runtime.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves legacy agent-bearing terminal.create requests for mixed-version clients', async () => {
|
||||
const createTerminal = vi.fn().mockResolvedValue({ handle: 'term-1' })
|
||||
const dedupeTerminalCreate = vi.fn(
|
||||
async (
|
||||
_clientIdentity: string,
|
||||
worktree: string | undefined,
|
||||
_clientMutationId: string | undefined,
|
||||
_reconcileExisting: boolean,
|
||||
run: (worktree: string | undefined, handle: string | undefined) => Promise<unknown>
|
||||
) => run(worktree, undefined)
|
||||
)
|
||||
const runtime = {
|
||||
getRuntimeId: () => 'runtime-1',
|
||||
createTerminal,
|
||||
dedupeTerminalCreate
|
||||
}
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: TERMINAL_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.create', {
|
||||
worktree: 'id:worktree-1',
|
||||
command: 'codex resume provider-session-1',
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
)
|
||||
|
||||
expect(response.ok).toBe(true)
|
||||
expect(dedupeTerminalCreate).toHaveBeenCalledWith(
|
||||
'local',
|
||||
'id:worktree-1',
|
||||
undefined,
|
||||
false,
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(createTerminal).toHaveBeenCalledWith('id:worktree-1', {
|
||||
command: 'codex resume provider-session-1',
|
||||
startupCommandDelivery: undefined,
|
||||
env: undefined,
|
||||
launchAgent: 'codex',
|
||||
title: undefined,
|
||||
focus: false,
|
||||
rendererBacked: false,
|
||||
activate: false,
|
||||
presentation: undefined,
|
||||
tabId: undefined,
|
||||
leafId: undefined
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects future-dated operation IDs before runtime mutation', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
const now = 1_752_883_200_000
|
||||
const dateNow = vi.spyOn(Date, 'now').mockReturnValue(now)
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: `${now + AGENT_SESSION_OPERATION_FUTURE_SKEW_MS + 1}-0123456789abcdef0123456789abcdef`,
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex'
|
||||
})
|
||||
)
|
||||
dateNow.mockRestore()
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'agent_session_operation_invalid' }
|
||||
})
|
||||
expect(runtime.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes authenticated caller identity outside the request payload', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
const replies: RpcResponse[] = []
|
||||
|
||||
await dispatcher.dispatchStreaming(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
prompt: 'Fix the race',
|
||||
promptDelivery: 'draft',
|
||||
agentArgs: '--profile review',
|
||||
launchPreferences: { model: 'gpt-5', effort: 'high' },
|
||||
viewMode: 'chat'
|
||||
}),
|
||||
(response) => replies.push(JSON.parse(response) as RpcResponse),
|
||||
{ clientId: 'authenticated-device', clientKind: 'runtime' }
|
||||
)
|
||||
|
||||
expect(replies).toHaveLength(1)
|
||||
expect(replies[0]).toMatchObject({ ok: true, result: { disposition: 'created' } })
|
||||
expect(runtime.createAgentSession).toHaveBeenCalledWith(
|
||||
{
|
||||
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
prompt: 'Fix the race',
|
||||
promptDelivery: 'draft',
|
||||
agentArgs: '--profile review',
|
||||
launchPreferences: { model: 'gpt-5', effort: 'high' },
|
||||
viewMode: 'chat'
|
||||
},
|
||||
{ clientId: 'authenticated-device', clientKind: 'runtime' }
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects draft delivery without a non-empty prompt', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'claude',
|
||||
prompt: ' ',
|
||||
promptDelivery: 'draft'
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(runtime.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects oversized structured agent arguments before runtime mutation', async () => {
|
||||
const runtime = runtimeStub()
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.createAgentSession', {
|
||||
clientOperationId: '1752883200000-0123456789abcdef0123456789abcdef',
|
||||
worktree: 'id:worktree-1',
|
||||
agent: 'codex',
|
||||
agentArgs: 'a'.repeat(16 * 1024 + 1)
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } })
|
||||
expect(runtime.createAgentSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(AGENT_SESSION_RPC_ERROR_CODES)('preserves stable runtime error %s', async (code) => {
|
||||
const runtime = runtimeStub()
|
||||
runtime.ensureAgentSession.mockRejectedValueOnce(new Error(code))
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: AGENT_SESSION_METHODS
|
||||
})
|
||||
|
||||
const response = await dispatcher.dispatch(
|
||||
request('terminal.ensureAgentSession', {
|
||||
kind: 'automatic',
|
||||
sleepingCheckpointId: 'checkpoint_123456789012345678901'
|
||||
})
|
||||
)
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code } })
|
||||
})
|
||||
|
||||
it('advertises the capability without moving the mixed-version protocol fence', () => {
|
||||
expect(RUNTIME_PROTOCOL_VERSION).toBe(3)
|
||||
expect(MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION).toBe(2)
|
||||
expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,228 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
getAgentResumeArgv,
|
||||
hasUnsafeProviderSessionIdChars,
|
||||
RESUMABLE_TUI_AGENTS
|
||||
} from '../../../../shared/agent-session-resume'
|
||||
import type {
|
||||
RuntimeAgentSessionRpcCaller,
|
||||
RuntimeCreateAgentSessionRequest,
|
||||
RuntimeCreateAgentSessionResult,
|
||||
RuntimeEnsureAgentSessionRequest,
|
||||
RuntimeEnsureAgentSessionResult
|
||||
} from '../../../../shared/agent-session-host-authority'
|
||||
import {
|
||||
AGENT_SESSION_OPERATION_FUTURE_SKEW_MS,
|
||||
parseAgentSessionOperationTimestamp
|
||||
} from '../../../../shared/agent-session-host-authority'
|
||||
import { isTuiAgent } from '../../../../shared/tui-agent-config'
|
||||
import { isValidTerminalTabId } from '../../../../shared/terminal-tab-id'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { defineMethod, type RpcAnyMethod } from '../core'
|
||||
|
||||
const MAX_WORKTREE_SELECTOR_LENGTH = 32_768
|
||||
const MAX_TRANSCRIPT_PATH_BYTES = 16 * 1024
|
||||
const MAX_PROMPT_BYTES = 256 * 1024
|
||||
const MAX_AGENT_ARGS_BYTES = 16 * 1024
|
||||
const MAX_LAUNCH_PREFERENCE_LENGTH = 512
|
||||
|
||||
const StrictNonEmptyString = (max: number, message: string) =>
|
||||
z
|
||||
.string()
|
||||
.min(1, message)
|
||||
.max(max, message)
|
||||
.refine((value) => value === value.trim(), `${message}; surrounding whitespace is invalid`)
|
||||
|
||||
const WorktreeSelector = StrictNonEmptyString(
|
||||
MAX_WORKTREE_SELECTOR_LENGTH,
|
||||
'Invalid worktree selector'
|
||||
)
|
||||
|
||||
const Presentation = z.enum(['background', 'focused'])
|
||||
|
||||
const Placement = z
|
||||
.object({
|
||||
tabId: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(512)
|
||||
.refine(isValidTerminalTabId, 'Invalid terminal tab ID')
|
||||
.optional(),
|
||||
leafId: z.string().min(1).max(128).optional()
|
||||
})
|
||||
.strict()
|
||||
.refine((value) => value.tabId !== undefined || value.leafId !== undefined, {
|
||||
message: 'Placement must include a tab or leaf ID'
|
||||
})
|
||||
|
||||
const LaunchPreferences = z
|
||||
.object({
|
||||
model: StrictNonEmptyString(
|
||||
MAX_LAUNCH_PREFERENCE_LENGTH,
|
||||
'Invalid model preference'
|
||||
).optional(),
|
||||
effort: StrictNonEmptyString(
|
||||
MAX_LAUNCH_PREFERENCE_LENGTH,
|
||||
'Invalid effort preference'
|
||||
).optional(),
|
||||
mode: StrictNonEmptyString(MAX_LAUNCH_PREFERENCE_LENGTH, 'Invalid mode preference').optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
const PromptDelivery = z.enum(['auto-submit', 'draft'])
|
||||
|
||||
const AgentArgs = z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => Buffer.byteLength(value, 'utf8') <= MAX_AGENT_ARGS_BYTES,
|
||||
'Agent arguments are too large'
|
||||
)
|
||||
.nullable()
|
||||
|
||||
const ProviderSession = z
|
||||
.object({
|
||||
key: z.enum(['session_id', 'conversation_id']),
|
||||
id: StrictNonEmptyString(512, 'Invalid provider session ID').refine(
|
||||
(value) => !value.startsWith('-') && !hasUnsafeProviderSessionIdChars(value),
|
||||
'Invalid provider session ID'
|
||||
),
|
||||
transcriptPath: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine((value) => value === value.trim(), 'Invalid transcript path')
|
||||
.refine(
|
||||
(value) =>
|
||||
!hasUnsafeProviderSessionIdChars(value) &&
|
||||
Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES,
|
||||
'Invalid transcript path'
|
||||
)
|
||||
.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
const AutomaticEnsure = z
|
||||
.object({
|
||||
kind: z.literal('automatic'),
|
||||
sleepingCheckpointId: z
|
||||
.string()
|
||||
.min(32)
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9_-]+$/),
|
||||
presentation: Presentation.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
const ExplicitEnsure = z
|
||||
.object({
|
||||
kind: z.literal('explicit'),
|
||||
worktree: WorktreeSelector,
|
||||
agent: z.enum(RESUMABLE_TUI_AGENTS),
|
||||
providerSession: ProviderSession,
|
||||
agentArgs: AgentArgs.optional(),
|
||||
launchPreferences: LaunchPreferences.optional(),
|
||||
presentation: Presentation.optional(),
|
||||
placement: Placement.optional()
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (getAgentResumeArgv(value.agent, value.providerSession) === null) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['providerSession'],
|
||||
message: 'Provider session is not resumable for this agent'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const EnsureAgentSessionParams: z.ZodType<RuntimeEnsureAgentSessionRequest> =
|
||||
z.discriminatedUnion('kind', [AutomaticEnsure, ExplicitEnsure])
|
||||
|
||||
export const CreateAgentSessionParams: z.ZodType<RuntimeCreateAgentSessionRequest> = z
|
||||
.object({
|
||||
clientOperationId: z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => parseAgentSessionOperationTimestamp(value) !== null,
|
||||
'Invalid agent operation ID'
|
||||
),
|
||||
worktree: WorktreeSelector,
|
||||
agent: z.string().refine(isTuiAgent, 'Unknown agent preset'),
|
||||
prompt: z
|
||||
.string()
|
||||
.refine(
|
||||
(value) => Buffer.byteLength(value, 'utf8') <= MAX_PROMPT_BYTES,
|
||||
'Prompt is too large'
|
||||
)
|
||||
.optional(),
|
||||
promptDelivery: PromptDelivery.optional(),
|
||||
agentArgs: AgentArgs.optional(),
|
||||
launchPreferences: LaunchPreferences.optional(),
|
||||
startupCwd: z.string().min(1).max(MAX_WORKTREE_SELECTOR_LENGTH).optional(),
|
||||
presentation: Presentation.optional(),
|
||||
placement: Placement.optional(),
|
||||
viewMode: z.enum(['terminal', 'chat']).optional()
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (value.promptDelivery === 'draft' && !value.prompt?.trim()) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['prompt'],
|
||||
message: 'Draft delivery requires a non-empty prompt'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type AgentSessionRuntime = OrcaRuntimeService & {
|
||||
ensureAgentSession(
|
||||
request: RuntimeEnsureAgentSessionRequest,
|
||||
caller?: RuntimeAgentSessionRpcCaller
|
||||
): Promise<RuntimeEnsureAgentSessionResult>
|
||||
createAgentSession(
|
||||
request: RuntimeCreateAgentSessionRequest,
|
||||
caller?: RuntimeAgentSessionRpcCaller
|
||||
): Promise<RuntimeCreateAgentSessionResult>
|
||||
}
|
||||
|
||||
function callerContext(
|
||||
clientId: string | undefined,
|
||||
clientKind: 'mobile' | 'runtime' | undefined,
|
||||
signal: AbortSignal | undefined
|
||||
): RuntimeAgentSessionRpcCaller {
|
||||
return {
|
||||
...(clientId !== undefined ? { clientId } : {}),
|
||||
...(clientKind !== undefined ? { clientKind } : {}),
|
||||
...(signal ? { signal } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function assertOperationTimestampWithinFutureSkew(clientOperationId: string): void {
|
||||
const timestamp = parseAgentSessionOperationTimestamp(clientOperationId)
|
||||
if (timestamp === null || timestamp > Date.now() + AGENT_SESSION_OPERATION_FUTURE_SKEW_MS) {
|
||||
// Why: a future-dated ID could look new again after its idempotency tombstone is collected.
|
||||
throw new Error('agent_session_operation_invalid')
|
||||
}
|
||||
}
|
||||
|
||||
export const AGENT_SESSION_METHODS: RpcAnyMethod[] = [
|
||||
defineMethod({
|
||||
name: 'terminal.ensureAgentSession',
|
||||
params: EnsureAgentSessionParams,
|
||||
handler: (params, { runtime, pairedDeviceId, clientId, clientKind, signal }) =>
|
||||
(runtime as AgentSessionRuntime).ensureAgentSession(
|
||||
params,
|
||||
callerContext(pairedDeviceId ?? clientId, clientKind, signal)
|
||||
)
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'terminal.createAgentSession',
|
||||
params: CreateAgentSessionParams,
|
||||
handler: (params, { runtime, pairedDeviceId, clientId, clientKind, signal }) => {
|
||||
assertOperationTimestampWithinFutureSkew(params.clientOperationId)
|
||||
return (runtime as AgentSessionRuntime).createAgentSession(
|
||||
params,
|
||||
callerContext(pairedDeviceId ?? clientId, clientKind, signal)
|
||||
)
|
||||
}
|
||||
})
|
||||
]
|
||||
@@ -35,6 +35,7 @@ import { CLIPBOARD_METHODS } from './clipboard'
|
||||
import { HOST_CAPABILITY_METHODS } from './host-capabilities'
|
||||
import { EMULATOR_METHODS } from './emulator'
|
||||
import { PAIRING_METHODS } from './pairing'
|
||||
import { AGENT_SESSION_METHODS } from './agent-session'
|
||||
|
||||
// Why: a flat manifest keeps registration order explicit and provides one
|
||||
// grep-point for "what methods does the RPC server expose?" — useful when
|
||||
@@ -45,6 +46,7 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [
|
||||
...AUTOMATION_METHODS,
|
||||
...REPO_METHODS,
|
||||
...WORKTREE_METHODS,
|
||||
...AGENT_SESSION_METHODS,
|
||||
...TERMINAL_METHODS,
|
||||
...BROWSER_CORE_METHODS,
|
||||
...BROWSER_SCREENCAST_METHODS,
|
||||
|
||||
@@ -10,7 +10,7 @@ export const SESSION_TAB_CLOSE_METHODS: RpcAnyMethod[] = [
|
||||
withSpan(
|
||||
'runtime.session-tabs.close',
|
||||
async (span) => {
|
||||
if (!params.reason && context.clientKind !== 'mobile') {
|
||||
if (!params.reason && context.clientKind === undefined) {
|
||||
const result = await context.runtime.refuseUnattributedMobileSessionTabClose(
|
||||
params.worktree,
|
||||
params.tabId
|
||||
@@ -35,7 +35,8 @@ export const SESSION_TAB_CLOSE_METHODS: RpcAnyMethod[] = [
|
||||
attribution: 'session-tab-close',
|
||||
origin: context.clientKind ?? 'in-process',
|
||||
closeReason:
|
||||
params.reason ?? (context.clientKind === 'mobile' ? 'legacy-mobile-user' : 'missing'),
|
||||
params.reason ??
|
||||
(context.clientKind ? `legacy-${context.clientKind}-user` : 'missing'),
|
||||
connectionGeneration: context.connectionId ?? 'in-process',
|
||||
requestId: context.requestId ?? 'in-process'
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ export const ActivateTab = WorktreeTabSelector.extend({
|
||||
})
|
||||
|
||||
export const CloseTab = ActivateTab.extend({
|
||||
// Why: optional so legacy clients still validate; policy conservatively
|
||||
// attributes only authenticated mobile callers as user intent.
|
||||
// Why: optional preserves authenticated legacy user closes; lifecycle intent
|
||||
// uses the additive evidence-bearing method instead.
|
||||
reason: z.literal('user').optional()
|
||||
})
|
||||
|
||||
|
||||
@@ -136,6 +136,28 @@ describe('session tab RPC methods', () => {
|
||||
expect(runtime.refuseUnattributedMobileSessionTabClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('preserves reasonless explicit closes from authenticated legacy runtime clients', async () => {
|
||||
const runtime = {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
refuseUnattributedMobileSessionTabClose: vi.fn(),
|
||||
closeMobileSessionTab: vi.fn().mockResolvedValue({ closed: true })
|
||||
} as unknown as OrcaRuntimeService
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
|
||||
const replies: string[] = []
|
||||
|
||||
await dispatcher.dispatchStreaming(
|
||||
makeRequest('session.tabs.close', { worktree: 'id:wt-1', tabId: 'tab-1' }),
|
||||
(response) => replies.push(response),
|
||||
{ clientKind: 'runtime', pairedDeviceId: 'legacy-runtime' }
|
||||
)
|
||||
|
||||
expect(replies).toHaveLength(1)
|
||||
expect(runtime.closeMobileSessionTab).toHaveBeenCalledWith('id:wt-1', 'tab-1', {
|
||||
reason: 'user'
|
||||
})
|
||||
expect(runtime.refuseUnattributedMobileSessionTabClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['pty-exit', 'cleanup'] as const)(
|
||||
'rejects %s on the legacy close endpoint before host adjudication',
|
||||
async (reason) => {
|
||||
@@ -262,7 +284,7 @@ describe('session tab RPC methods', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('dispatches terminal creation with the requested tab group', async () => {
|
||||
it('dispatches ordinary terminal creation with the requested tab group', async () => {
|
||||
const runtime = {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
createMobileSessionTerminal: vi.fn().mockResolvedValue({
|
||||
@@ -321,7 +343,9 @@ describe('session tab RPC methods', () => {
|
||||
activate: true,
|
||||
select: undefined,
|
||||
clientNavigationId: undefined,
|
||||
navigation: 'all'
|
||||
navigation: 'all',
|
||||
clientMutationId: undefined,
|
||||
signal: undefined
|
||||
})
|
||||
})
|
||||
|
||||
@@ -357,7 +381,7 @@ describe('session tab RPC methods', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('dispatches terminal creation with a requested agent preset', async () => {
|
||||
it('preserves legacy agent creation for mixed-version clients', async () => {
|
||||
const runtime = {
|
||||
getRuntimeId: () => 'test-runtime',
|
||||
createMobileSessionTerminal: vi.fn().mockResolvedValue({
|
||||
@@ -390,13 +414,16 @@ describe('session tab RPC methods', () => {
|
||||
afterTabId: undefined,
|
||||
targetGroupId: undefined,
|
||||
command: undefined,
|
||||
cwd: undefined,
|
||||
startupCommandDelivery: undefined,
|
||||
agent: 'codex',
|
||||
agentPrompt: 'Review this diff',
|
||||
activate: undefined,
|
||||
select: undefined,
|
||||
clientNavigationId: undefined,
|
||||
navigation: 'all'
|
||||
navigation: 'all',
|
||||
clientMutationId: undefined,
|
||||
signal: undefined
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -356,6 +356,8 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'terminal.close',
|
||||
'terminal.closeTab',
|
||||
'terminal.create',
|
||||
'terminal.createAgentSession',
|
||||
'terminal.ensureAgentSession',
|
||||
'terminal.focus',
|
||||
'terminal.agentStatus',
|
||||
'terminal.getAutoRestoreFit',
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import type {
|
||||
Tab,
|
||||
TabGroup,
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalPaneLayoutNode,
|
||||
WorkspaceSessionState
|
||||
} from '../../shared/types'
|
||||
import { getRepoIdFromWorktreeId } from '../../shared/worktree-id'
|
||||
import { pruneTabGroupLayoutAfterRetirement } from './mobile-session-terminal-retirement'
|
||||
|
||||
function collectLeafIds(node: TerminalPaneLayoutNode | null, ids: Set<string>): void {
|
||||
if (!node) {
|
||||
return
|
||||
}
|
||||
if (node.type === 'leaf') {
|
||||
ids.add(node.leafId)
|
||||
return
|
||||
}
|
||||
collectLeafIds(node.first, ids)
|
||||
collectLeafIds(node.second, ids)
|
||||
}
|
||||
|
||||
function layoutHasSameMembership(
|
||||
candidate: TerminalLayoutSnapshot,
|
||||
current: TerminalLayoutSnapshot
|
||||
): boolean {
|
||||
const candidateIds = new Set<string>()
|
||||
const currentIds = new Set<string>()
|
||||
collectLeafIds(candidate.root, candidateIds)
|
||||
collectLeafIds(current.root, currentIds)
|
||||
return (
|
||||
candidateIds.size === currentIds.size &&
|
||||
[...candidateIds].every((leafId) => currentIds.has(leafId))
|
||||
)
|
||||
}
|
||||
|
||||
function rebaseLayout(
|
||||
candidate: TerminalLayoutSnapshot | undefined,
|
||||
current: TerminalLayoutSnapshot | undefined
|
||||
): TerminalLayoutSnapshot | undefined {
|
||||
if (!current) {
|
||||
return undefined
|
||||
}
|
||||
if (!candidate || !layoutHasSameMembership(candidate, current)) {
|
||||
return current
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
// Why: renderer layout metadata may move, but only host-persisted live bindings may name PTYs.
|
||||
ptyIdsByLeafId: {
|
||||
...candidate.ptyIdsByLeafId,
|
||||
...current.ptyIdsByLeafId
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function terminalUnifiedTabMatches(tab: Tab, terminalTabIds: ReadonlySet<string>): boolean {
|
||||
return (
|
||||
tab.contentType === 'terminal' &&
|
||||
(terminalTabIds.has(tab.id) || terminalTabIds.has(tab.entityId))
|
||||
)
|
||||
}
|
||||
|
||||
function rebaseUnifiedTabs(
|
||||
candidate: readonly Tab[],
|
||||
current: readonly Tab[],
|
||||
terminalTabIds: ReadonlySet<string>
|
||||
): Tab[] {
|
||||
const result = candidate.filter(
|
||||
(tab) => tab.contentType !== 'terminal' || terminalUnifiedTabMatches(tab, terminalTabIds)
|
||||
)
|
||||
const representedTerminalIds = new Set(
|
||||
result.filter((tab) => tab.contentType === 'terminal').flatMap((tab) => [tab.id, tab.entityId])
|
||||
)
|
||||
for (const tab of current) {
|
||||
if (
|
||||
terminalUnifiedTabMatches(tab, terminalTabIds) &&
|
||||
!representedTerminalIds.has(tab.id) &&
|
||||
!representedTerminalIds.has(tab.entityId)
|
||||
) {
|
||||
result.push(tab)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function rebaseTabGroups(
|
||||
groups: readonly TabGroup[],
|
||||
validTabIds: ReadonlySet<string>
|
||||
): TabGroup[] {
|
||||
return groups.flatMap((group) => {
|
||||
const tabOrder = group.tabOrder.filter((tabId) => validTabIds.has(tabId))
|
||||
if (tabOrder.length === 0) {
|
||||
return []
|
||||
}
|
||||
const activeTabId =
|
||||
group.activeTabId && tabOrder.includes(group.activeTabId)
|
||||
? group.activeTabId
|
||||
: (tabOrder[0] ?? null)
|
||||
const recentTabIds = group.recentTabIds?.filter((tabId) => tabOrder.includes(tabId))
|
||||
return [
|
||||
{
|
||||
...group,
|
||||
tabOrder,
|
||||
activeTabId,
|
||||
...(recentTabIds && recentTabIds.length > 0 ? { recentTabIds } : {})
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
function rebaseIncarnationBindings(
|
||||
session: WorkspaceSessionState,
|
||||
prior: WorkspaceSessionState
|
||||
): Record<string, string> | undefined {
|
||||
const terminalTabIds = new Set(
|
||||
Object.values(session.tabsByWorktree).flatMap((tabs) => tabs.map((tab) => tab.id))
|
||||
)
|
||||
const allowedPaneKeys = new Set<string>()
|
||||
for (const tabId of terminalTabIds) {
|
||||
const layout = session.terminalLayoutsByTabId[tabId]
|
||||
if (!layout) {
|
||||
continue
|
||||
}
|
||||
const leafIds = new Set<string>()
|
||||
collectLeafIds(layout.root, leafIds)
|
||||
for (const leafId of leafIds) {
|
||||
allowedPaneKeys.add(`${tabId}:${leafId}`)
|
||||
}
|
||||
}
|
||||
const merged = {
|
||||
...session.terminalPtyIncarnationsByPaneKey,
|
||||
...prior.terminalPtyIncarnationsByPaneKey
|
||||
}
|
||||
const retained = Object.fromEntries(
|
||||
Object.entries(merged).filter(([paneKey]) => {
|
||||
const separator = paneKey.lastIndexOf(':')
|
||||
if (separator < 1) {
|
||||
return false
|
||||
}
|
||||
const tabId = paneKey.slice(0, separator)
|
||||
return session.terminalLayoutsByTabId[tabId]
|
||||
? allowedPaneKeys.has(paneKey)
|
||||
: terminalTabIds.has(tabId)
|
||||
})
|
||||
)
|
||||
return Object.keys(retained).length > 0 ? retained : undefined
|
||||
}
|
||||
|
||||
export function advanceTerminalTopologyRevision(
|
||||
session: WorkspaceSessionState,
|
||||
worktreeId: string
|
||||
): WorkspaceSessionState {
|
||||
const repoId = getRepoIdFromWorktreeId(worktreeId)
|
||||
return {
|
||||
...session,
|
||||
terminalTopologyRevisionByRepoId: {
|
||||
...session.terminalTopologyRevisionByRepoId,
|
||||
[repoId]: (session.terminalTopologyRevisionByRepoId?.[repoId] ?? 0) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function hasHostAuthoritativeTerminalMembership(
|
||||
session: WorkspaceSessionState | undefined,
|
||||
worktreeId: string
|
||||
): boolean {
|
||||
const repoId = getRepoIdFromWorktreeId(worktreeId)
|
||||
return (
|
||||
(session?.terminalTopologyRevisionByRepoId?.[repoId] ?? 0) > 0 ||
|
||||
Object.values(session?.terminalSurfaceTombstonesByPaneKey ?? {}).some(
|
||||
(tombstone) => tombstone.worktreeId === worktreeId
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function rebaseWorkspaceSessionTerminalMembership(
|
||||
incoming: WorkspaceSessionState,
|
||||
prior: WorkspaceSessionState | undefined
|
||||
): WorkspaceSessionState {
|
||||
if (!prior?.terminalTopologyRevisionByRepoId) {
|
||||
return incoming
|
||||
}
|
||||
const terminalTopologyRevisionByRepoId = { ...incoming.terminalTopologyRevisionByRepoId }
|
||||
for (const [repoId, revision] of Object.entries(prior.terminalTopologyRevisionByRepoId)) {
|
||||
terminalTopologyRevisionByRepoId[repoId] = Math.max(
|
||||
revision,
|
||||
terminalTopologyRevisionByRepoId[repoId] ?? 0
|
||||
)
|
||||
}
|
||||
const tabsByWorktree = { ...incoming.tabsByWorktree }
|
||||
const terminalLayoutsByTabId = { ...incoming.terminalLayoutsByTabId }
|
||||
const unifiedTabs = { ...incoming.unifiedTabs }
|
||||
const tabGroups = { ...incoming.tabGroups }
|
||||
const tabGroupLayouts = { ...incoming.tabGroupLayouts }
|
||||
const activeTabIdByWorktree = { ...incoming.activeTabIdByWorktree }
|
||||
let includeUnifiedTabs = incoming.unifiedTabs !== undefined
|
||||
let includeTabGroups = incoming.tabGroups !== undefined
|
||||
let includeTabGroupLayouts = incoming.tabGroupLayouts !== undefined
|
||||
let rebasedMembership = false
|
||||
const worktreeIds = new Set([
|
||||
...Object.keys(prior.tabsByWorktree),
|
||||
...Object.keys(incoming.tabsByWorktree)
|
||||
])
|
||||
for (const worktreeId of worktreeIds) {
|
||||
const repoId = getRepoIdFromWorktreeId(worktreeId)
|
||||
const revision = terminalTopologyRevisionByRepoId[repoId] ?? 0
|
||||
const priorRevision = prior.terminalTopologyRevisionByRepoId[repoId] ?? 0
|
||||
const incomingRevision = incoming.terminalTopologyRevisionByRepoId?.[repoId] ?? 0
|
||||
if (revision <= 0 || incomingRevision > priorRevision) {
|
||||
continue
|
||||
}
|
||||
rebasedMembership = true
|
||||
const currentTabs = prior.tabsByWorktree[worktreeId] ?? []
|
||||
const candidateTabsById = new Map(
|
||||
(incoming.tabsByWorktree[worktreeId] ?? []).map((tab) => [tab.id, tab])
|
||||
)
|
||||
const terminalTabIds = new Set(currentTabs.map((tab) => tab.id))
|
||||
const tabs = currentTabs.map((current) => {
|
||||
const candidate = candidateTabsById.get(current.id)
|
||||
return candidate ? { ...candidate, ptyId: current.ptyId } : current
|
||||
})
|
||||
for (const candidate of incoming.tabsByWorktree[worktreeId] ?? []) {
|
||||
if (!terminalTabIds.has(candidate.id)) {
|
||||
delete terminalLayoutsByTabId[candidate.id]
|
||||
}
|
||||
}
|
||||
for (const tabId of terminalTabIds) {
|
||||
const layout = rebaseLayout(
|
||||
incoming.terminalLayoutsByTabId[tabId],
|
||||
prior.terminalLayoutsByTabId[tabId]
|
||||
)
|
||||
if (layout) {
|
||||
terminalLayoutsByTabId[tabId] = layout
|
||||
} else {
|
||||
delete terminalLayoutsByTabId[tabId]
|
||||
}
|
||||
}
|
||||
const rebasedUnifiedTabs = rebaseUnifiedTabs(
|
||||
incoming.unifiedTabs?.[worktreeId] ?? [],
|
||||
prior.unifiedTabs?.[worktreeId] ?? [],
|
||||
terminalTabIds
|
||||
)
|
||||
if (includeUnifiedTabs || rebasedUnifiedTabs.length > 0) {
|
||||
unifiedTabs[worktreeId] = rebasedUnifiedTabs
|
||||
includeUnifiedTabs = true
|
||||
}
|
||||
const validTabIds = new Set([...terminalTabIds, ...rebasedUnifiedTabs.map((tab) => tab.id)])
|
||||
const rebasedGroups = rebaseTabGroups(
|
||||
incoming.tabGroups?.[worktreeId] ?? prior.tabGroups?.[worktreeId] ?? [],
|
||||
validTabIds
|
||||
)
|
||||
if (includeTabGroups || rebasedGroups.length > 0) {
|
||||
tabGroups[worktreeId] = rebasedGroups
|
||||
includeTabGroups = true
|
||||
}
|
||||
const rebasedGroupLayout = pruneTabGroupLayoutAfterRetirement(
|
||||
incoming.tabGroupLayouts?.[worktreeId] ?? prior.tabGroupLayouts?.[worktreeId],
|
||||
new Set(rebasedGroups.map((group) => group.id))
|
||||
)
|
||||
if (rebasedGroupLayout) {
|
||||
tabGroupLayouts[worktreeId] = rebasedGroupLayout
|
||||
includeTabGroupLayouts = true
|
||||
} else {
|
||||
delete tabGroupLayouts[worktreeId]
|
||||
}
|
||||
if (!validTabIds.has(activeTabIdByWorktree[worktreeId] ?? '')) {
|
||||
activeTabIdByWorktree[worktreeId] =
|
||||
(prior.activeTabIdByWorktree?.[worktreeId] &&
|
||||
validTabIds.has(prior.activeTabIdByWorktree[worktreeId] ?? '')
|
||||
? prior.activeTabIdByWorktree[worktreeId]
|
||||
: (rebasedGroups[0]?.activeTabId ?? tabs[0]?.id)) ?? null
|
||||
}
|
||||
tabsByWorktree[worktreeId] = tabs
|
||||
}
|
||||
const next: WorkspaceSessionState = {
|
||||
...incoming,
|
||||
terminalTopologyRevisionByRepoId,
|
||||
...(rebasedMembership
|
||||
? {
|
||||
tabsByWorktree,
|
||||
terminalLayoutsByTabId,
|
||||
activeTabIdByWorktree,
|
||||
...(includeUnifiedTabs ? { unifiedTabs } : {}),
|
||||
...(includeTabGroups ? { tabGroups } : {}),
|
||||
...(includeTabGroupLayouts ? { tabGroupLayouts } : {})
|
||||
}
|
||||
: {})
|
||||
}
|
||||
return rebasedMembership
|
||||
? { ...next, terminalPtyIncarnationsByPaneKey: rebaseIncarnationBindings(next, prior) }
|
||||
: next
|
||||
}
|
||||
Reference in New Issue
Block a user