From 5ff60af36f1330b119399f45d1ac1159382447d3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:38:28 -0700 Subject: [PATCH 01/38] fix(native-chat): identify the owner when resume create is refused --- ...structured-agent-session-adopted-import.ts | 2 +- ...ured-agent-session-create-adoption.test.ts | 23 ++++++++++++- .../structured-agent-session-create.ts | 9 +++-- ...red-agent-session-history-adoption.test.ts | 1 + ...ructured-agent-session-history-adoption.ts | 6 +++- .../agent-session-founding-admission.ts | 18 ++++++++-- .../agent-session-reservation-admission.ts | 3 +- ...ctured-agent-session-create-intent.test.ts | 33 +++++++++++++++++++ ...ed-agent-session-precommit-refusal.test.ts | 27 +++++++++++---- ...uctured-agent-session-precommit-refusal.ts | 9 +++-- .../structured-session-create-support.ts | 11 +++++-- ...tructured-agent-session-create-adoption.ts | 26 ++++++++------- ...red-agent-session-launch-admission.test.ts | 32 ++++-------------- ...ructured-agent-session-launch-admission.ts | 23 +++++-------- ...ctured-agent-session-launch-create-call.ts | 19 ++++++----- ...-agent-session-launch-exited-owner.test.ts | 27 ++++++++++++++- .../agent-session-definitive-refusal.ts | 17 +++++++++- src/shared/agent-session-refusal-details.ts | 26 +++++++++++++-- .../agent-session-refusal-reason-words.ts | 3 +- .../agent-session-wire-refusals.test.ts | 17 ++++++++++ 20 files changed, 241 insertions(+), 91 deletions(-) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts index d3aabd2e52aa..fe4db165d609 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts @@ -57,7 +57,7 @@ async function readAdoptedTranscript( } if (prepared.items.length === 0) { throw agentSessionRefusalError('agent_session_identity_required', { - reason: 'transcriptUnreadable' + reason: 'transcriptEmpty' }) } return prepared.items diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index a31b48c23bdb..49c82f5fc807 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -117,7 +117,14 @@ it('refuses concurrent adoption of a provider conversation by another session', expect(results.filter((result) => result.ok)).toHaveLength(1) expect(results.filter((result) => !result.ok)).toMatchObject([ { - refusal: { code: 'agent_session_conflict', details: { reason: 'conversationHeldElsewhere' } } + refusal: { + code: 'agent_session_conflict', + details: { + reason: 'conversationHeldElsewhere', + owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } + }, + createAttemptRefusedBeforeCommit: true + } } ]) expect(rig.store.listRecords()).toHaveLength(1) @@ -125,6 +132,20 @@ it('refuses concurrent adoption of a provider conversation by another session', expect(rig.adapter.acquire).not.toHaveBeenCalled() }) +it('distinguishes an empty saved source from an unreadable one without founding a chat', async () => { + const params = await adoptedParams() + await writeFile(join(rig.root, 'rollout.jsonl'), '') + expect(await rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { + details: { reason: 'transcriptEmpty' }, + createAttemptRefusedBeforeCommit: true + } + }) + expect(rig.store.listRecords()).toEqual([]) + expect(rig.store.listOperationRows()).toEqual([]) +}) + it('refuses concurrent founding under a tab another chat already owns', async () => { const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) const results = await Promise.all([ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create.ts index d9c149c50af0..45ad97d2ec15 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create.ts @@ -1,4 +1,5 @@ import { isFloatingWorkspaceId } from '../../../shared/floating-workspace-worktree' +import { isAgentSessionCreateAdmissionRefusal } from '../../../shared/agent-session-definitive-refusal' import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' import { @@ -156,11 +157,9 @@ async function foundConversation( const { refusal } = prepared return { ok: false, - refusal: - refusal.code === 'agent_session_identity_required' && - refusal.details?.reason === 'transcriptUnreadable' - ? { ...refusal, createAttemptRefusedBeforeCommit: true } - : refusal + refusal: isAgentSessionCreateAdmissionRefusal(refusal) + ? { ...refusal, createAttemptRefusedBeforeCommit: true } + : refusal } } const existing = context.sessions.get(sessionId) diff --git a/src/main/native-chat/structured-agent-session-history-adoption.test.ts b/src/main/native-chat/structured-agent-session-history-adoption.test.ts index 44154317b906..e251752f8d1d 100644 --- a/src/main/native-chat/structured-agent-session-history-adoption.test.ts +++ b/src/main/native-chat/structured-agent-session-history-adoption.test.ts @@ -60,6 +60,7 @@ function ownership( ): StructuredAgentSessionAdoptionOwnership { return { sessionId: 'codex_owner', + workspaceId: 'workspace-owner', provider: 'codex', providerSessionId: 'thread-1', lease: agentSessionLeaseFixture(), diff --git a/src/main/native-chat/structured-agent-session-history-adoption.ts b/src/main/native-chat/structured-agent-session-history-adoption.ts index 8d06a282a6ee..8da3cb967bc5 100644 --- a/src/main/native-chat/structured-agent-session-history-adoption.ts +++ b/src/main/native-chat/structured-agent-session-history-adoption.ts @@ -21,6 +21,7 @@ import { export type StructuredAgentSessionAdoptionOwnership = { sessionId: string + workspaceId: string /** Any agent's chat may hold the conversation, though only one with an importer adopts. */ provider: StructuredAgentId providerSessionId: string @@ -110,7 +111,10 @@ export function structuredAdoptionConflictError( agentSessionLeaseAdmitsWriter(ownership.lease) ? 'agent_session_conflict' : 'agent_session_ownership_unknown', - { reason: 'conversationHeldElsewhere' } + { + reason: 'conversationHeldElsewhere', + owner: { sessionId: ownership.sessionId, workspaceId: ownership.workspaceId } + } ) } diff --git a/src/main/runtime/agent-session-founding-admission.ts b/src/main/runtime/agent-session-founding-admission.ts index 0d83131c3224..f95455eefef8 100644 --- a/src/main/runtime/agent-session-founding-admission.ts +++ b/src/main/runtime/agent-session-founding-admission.ts @@ -1,4 +1,8 @@ -import { agentSessionRefusalError } from '../../shared/agent-session-wire-refusals' +import { + AgentSessionRefusalError, + agentSessionRefusalError, + isAgentSessionRefusalError +} from '../../shared/agent-session-wire-refusals' import { agentSessionOperationKey } from '../../shared/agent-session-operation-ledger' import { foundAgentSessionRecord } from './agent-session-record-founding' import { @@ -41,7 +45,17 @@ export function commitAgentSessionFounding( if (state.records.has(request.sessionId)) { throw agentSessionRefusalError('agent_session_conflict', { reason: 'sessionExists' }) } - assertAdoptedConversationUnowned(state, request) + try { + assertAdoptedConversationUnowned(state, request) + } catch (error) { + if (isAgentSessionRefusalError(error)) { + throw new AgentSessionRefusalError({ + ...error.refusal, + createAttemptRefusedBeforeCommit: true + }) + } + throw error + } assertReservedTabUnheld(state, request) const founded = foundAgentSessionRecord(request, request) const record = request.adoptedHandleLink diff --git a/src/main/runtime/agent-session-reservation-admission.ts b/src/main/runtime/agent-session-reservation-admission.ts index eb956e4b34c4..17d220f39aa9 100644 --- a/src/main/runtime/agent-session-reservation-admission.ts +++ b/src/main/runtime/agent-session-reservation-admission.ts @@ -250,7 +250,8 @@ export function assertAdoptedConversationUnowned( ) if (holdsSameConversation) { throw agentSessionRefusalError('agent_session_conflict', { - reason: 'conversationHeldElsewhere' + reason: 'conversationHeldElsewhere', + owner: { sessionId: record.sessionId, workspaceId: record.location.workspaceId } }) } } diff --git a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts index 8b87429e8948..6284c30602a1 100644 --- a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts +++ b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts @@ -7,6 +7,9 @@ const applyAgentWorkspaceTrust = vi.hoisted(() => vi.fn(async () => ({}))) vi.mock('../agent-workspace-trust', () => ({ applyAgentWorkspaceTrust })) import { OrcaRuntimeService } from './orca-runtime' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' +import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants' import { attachFingerprintFields } from '../native-chat/agent-session-wire/structured-agent-session-attach' @@ -15,6 +18,7 @@ beforeEach(() => { }) afterEach(() => { + setStructuredAgentSessionHost(null) vi.unstubAllEnvs() }) @@ -99,6 +103,35 @@ describe('structured Codex folder trust', () => { }) describe('structured agent-session create intent', () => { + it('returns the recorded owner before any new-launch support or account preparation', async () => { + const record = agentSessionRecordFixture() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: early ownership admission only reads the host's record list. + setStructuredAgentSessionHost({ + deps: { store: { listRecords: () => [record] } } + } as unknown as StructuredAgentSessionHost) + const runtime = new OrcaRuntimeService() + const support = vi + .spyOn(runtime, 'getStructuredAgentSessionCreateSupport') + .mockRejectedValue(new Error('fresh launch is unavailable')) + await expect( + runtime.resolveStructuredAgentSessionCreateIntent({ + envelope: { sessionId: 'new-chat', clientOperationId: 'operation-1' }, + worktree: 'id:another-workspace', + agent: 'claude', + resumeFrom: { providerSessionId: 'provider-session-alpha-1' } + }) + ).rejects.toMatchObject({ + refusal: { + code: 'agent_session_conflict', + details: { + reason: 'conversationHeldElsewhere', + owner: { sessionId: record.sessionId, workspaceId: record.location.workspaceId } + } + } + }) + expect(support).not.toHaveBeenCalled() + }) + it('pins the selected Codex launch home after normal launch preparation', async () => { const prepareCodexStructuredLaunch = vi.fn(() => '/accounts/selected/home') const runtime = new OrcaRuntimeService( diff --git a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts index 5a9842645211..8f3e5096d864 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts @@ -131,18 +131,31 @@ afterEach(() => { }) describe('a create refused before it commits', () => { - it('answers missing history before commit as a definite failed attempt', async () => { + it.each([ + ['agent_session_identity_required', { reason: 'transcriptNotFound' }], + [ + 'agent_session_conflict', + { + reason: 'conversationHeldElsewhere', + owner: { sessionId: 'owner', workspaceId: 'workspace' } + } + ], + [ + 'agent_session_ownership_unknown', + { + reason: 'conversationHeldElsewhere', + owner: { sessionId: 'owner', workspaceId: 'workspace' } + } + ] + ] as const)('answers %s before commit as a definite failed attempt', async (code, details) => { const response = await create({ resolveStructuredAgentSessionCreateIntent: vi.fn(async () => { - throw agentSessionRefusalError('agent_session_identity_required', { - reason: 'transcriptNotFound' - }) + throw agentSessionRefusalError(code, details) }) }) - expect(refusalOf(response)).toMatchObject({ - code: 'agent_session_identity_required', - details: { reason: 'transcriptNotFound' }, + code, + details, createAttemptRefusedBeforeCommit: true }) expect(attach).not.toHaveBeenCalled() diff --git a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.ts index 9ca93701beaa..30f9672e7047 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.ts @@ -18,6 +18,7 @@ import { type AgentSessionWireRefusal, type AgentSessionWireRefusalCode } from '../../../../shared/agent-session-wire' +import { isAgentSessionCreateAdmissionRefusal } from '../../../../shared/agent-session-definitive-refusal' export type StructuredCreateRefused = { refusal: AgentSessionWireRefusal } @@ -77,11 +78,9 @@ export async function resolveUncommittedStructuredCreate( } catch (error) { const refusal = precommitRefusal(error) return { - refusal: - refusal.code === 'agent_session_identity_required' && - refusal.details?.reason === 'transcriptNotFound' - ? { ...refusal, createAttemptRefusedBeforeCommit: true } - : refusal + refusal: isAgentSessionCreateAdmissionRefusal(refusal) + ? { ...refusal, createAttemptRefusedBeforeCommit: true } + : refusal } } } diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index 69b71691da57..8d8d54973aff 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -4,6 +4,7 @@ import { OrcaRuntimeWithGetWorktreePs } from '../workspaces/workspace-process-li import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/structured-agent-session-registry' import { resolveCommittedStructuredAgentSessionAdoptionIntent, + requireUnownedStructuredAgentSessionAdoption, resolveStructuredAgentSessionAdoptionForCreate } from '../structured-agent-session-create-adoption' import { isNativeLocalLocation, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' @@ -151,6 +152,14 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte callerKey?: string resumeFrom?: { providerSessionId: string } }): Promise { + if (input.resumeFrom) { + requireUnownedStructuredAgentSessionAdoption({ + host: getStructuredAgentSessionHost(), + agent: input.agent, + providerSessionId: input.resumeFrom.providerSessionId, + selfSessionId: input.envelope.sessionId + }) + } const hostLaunchDirectory = isFloatingWorkspaceSelector(input.worktree) ? (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path : undefined @@ -237,12 +246,10 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte const adoption = input.resumeFrom && transcriptImport ? await resolveStructuredAgentSessionAdoptionForCreate({ - host, settings, agent: input.agent, transcriptImport, providerSessionId: input.resumeFrom.providerSessionId, - selfSessionId: input.envelope.sessionId, selectedAccountHome, launchEnv: await resolveHostStructuredAgentLaunchEnvironment(input.agent, settings), workspaceCwd: (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index 627da4a842bb..d9a870f4b546 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -60,29 +60,33 @@ export function resolveCommittedStructuredAgentSessionAdoptionIntent(input: { } } -export async function resolveStructuredAgentSessionAdoptionForCreate(input: { +export function requireUnownedStructuredAgentSessionAdoption(input: { host: StructuredAgentSessionHost | null - settings: StructuredAgentTranscriptImportSettings agent: StructuredAgentId - /** The agent's registered importer; only an agent with one adopts. */ - transcriptImport: StructuredAgentTranscriptImport providerSessionId: string selfSessionId: string - selectedAccountHome: AgentSessionAccountHome - launchEnv: NodeJS.ProcessEnv - workspaceCwd: string -}) { +}): void { const conflict = input.host ? findConflictingStructuredAdoption({ - agent: input.agent, - providerSessionId: input.providerSessionId, - selfSessionId: input.selfSessionId, + ...input, ownership: listStructuredProviderSessionOwnership(input.host.deps.store.listRecords()) }) : null if (conflict) { throw structuredAdoptionConflictError(conflict) } +} + +export async function resolveStructuredAgentSessionAdoptionForCreate(input: { + settings: StructuredAgentTranscriptImportSettings + agent: StructuredAgentId + /** The agent's registered importer; only an agent with one adopts. */ + transcriptImport: StructuredAgentTranscriptImport + providerSessionId: string + selectedAccountHome: AgentSessionAccountHome + launchEnv: NodeJS.ProcessEnv + workspaceCwd: string +}) { return resolveStructuredAgentSessionAdoption({ providerSessionId: input.providerSessionId, candidateAccountHomes: input.transcriptImport.accountHomeCandidates(input), diff --git a/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts b/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts index 2cdb6dbe5012..b62c665177cd 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts @@ -27,8 +27,6 @@ import { useAppStore } from '@/store' import { adoptAgentSessionLaunchVerdict } from './agent-session-launch-plan' import { beginStructuredAgentSessionProvisionalLaunch } from './structured-agent-session-provisional-tab' import { beginDirectWorkItemStructuredLaunch } from './launch-work-item-direct-agent-routing' -import type { AiVaultSession } from '../../../shared/ai-vault-types' -import { resumeAiVaultSessionInNewChat } from '@/components/right-sidebar/ai-vault-session-resume-in-chat-launch' import { getStructuredAgentLaunchStatus } from './structured-agent-session-launch-status' import { getStructuredAgentSessionLaunchSelection } from './structured-agent-session-launch-options' import { peekWebSessionFocusIntent } from '@/runtime/web-session-focus-intent' @@ -152,38 +150,20 @@ describe('a structured chat launch on a paired server', () => { expectNoChatCommitted() }) - it('says once that the server cannot be reached when a vault resume needs it', async () => { - mocks.createSupport.mockRejectedValue(new Error('connection lost')) - // The vault names no host; the workspace's owner, the paired server, is resolved for it. - useAppStore.setState({ activeWorkspaceExecutionHostId: 'runtime:server-1' }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: resume reads only the id fields the preparation mock ignores. - const session = { id: 'vault-1', sessionId: 'provider-1' } as AiVaultSession - - await resumeAiVaultSessionInNewChat(session, 'claude', WORKTREE, 'resume-click') - - await vi.waitFor(() => expect(mocks.toastError).toHaveBeenCalled()) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(mocks.toastError).toHaveBeenCalledOnce() - expect(mocks.toastError).toHaveBeenCalledWith( - expect.stringContaining('Could not reach'), - expect.anything() - ) - expectNoChatCommitted() - }) - - it('fails a resume the server declines, since a resume has no terminal equivalent', async () => { + it('sends a resume to create even when the fresh-launch probe would decline', async () => { mocks.createSupport.mockResolvedValue({ supported: false }) const onHostDeclined = vi.fn() - const launch = beginStructuredAgentSessionProvisionalLaunch({ plan: pairedPlan({ resumeFrom: { providerSessionId: 'provider-1' } }), hooks: {}, onHostDeclined }) - - await expect(launch?.settlement).resolves.toMatchObject({ kind: 'failed' }) + await vi.waitFor(() => + expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toHaveLength(1) + ) + expect(mocks.createSupport).not.toHaveBeenCalled() expect(onHostDeclined).not.toHaveBeenCalled() - expectNoChatCommitted() + launch?.cancel() }) // The picker shows what create will run: the server's saved selection, not this machine's. diff --git a/src/renderer/src/lib/structured-agent-session-launch-admission.ts b/src/renderer/src/lib/structured-agent-session-launch-admission.ts index d44f0ea4ca84..d10c8a7c24d8 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-admission.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-admission.ts @@ -13,7 +13,6 @@ import { type StructuredLaunchAdmission } from '@/lib/structured-agent-session-host-admission' import { holdEmptyWorkspaceDefaultSurfaceForLaunch } from '@/lib/empty-workspace-default-surface-claims' -import { StructuredAgentSessionCreateRefusalError } from '@/lib/structured-agent-session-launch-errors' import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' import type { StructuredAgentLaunchHooks, @@ -161,11 +160,14 @@ export function beginHostAdmittedStructuredLaunch(args: { const releaseHold = holdEmptyWorkspaceDefaultSurfaceForLaunch(args.worktreeId) const settlement = (async (): Promise => { try { - const asked = await admitStructuredLaunchOnHost( - args.target, - toRuntimeWorktreeSelector(args.worktreeId), - plan.agent - ) + // Resuming asks create for the existing owner before fresh-launch prerequisites. + const asked: StructuredLaunchAdmission = plan.resumeFrom + ? { kind: 'admitted' } + : await admitStructuredLaunchOnHost( + args.target, + toRuntimeWorktreeSelector(args.worktreeId), + plan.agent + ) if (isCancelled()) { resolveDelivery(NOT_DELIVERED) return { kind: 'cancelled', sessionId: null } @@ -188,15 +190,6 @@ export function beginHostAdmittedStructuredLaunch(args: { } } if (admission.kind === 'declined') { - if (plan.resumeFrom) { - resolveDelivery(NOT_DELIVERED) - return { - kind: 'failed', - error: new StructuredAgentSessionCreateRefusalError( - 'structured_agent_session_unsupported' - ) - } - } // The notice explains a server's refusal; on this machine the terminal opening is the answer. if (paired) { notifyHostDeclined(plan.agent) diff --git a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts index 613686742b43..e31be1214987 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts @@ -3,7 +3,10 @@ import type { AgentSessionMutationResult } from '../../../shared/agent-session-wire' import { hasRuntimeRpcErrorCode } from '../../../shared/runtime-rpc-error-code' -import { isDefinitiveAgentSessionCreateRefusal } from '../../../shared/agent-session-definitive-refusal' +import { + isAgentSessionCreateAdmissionRefusal, + isDefinitiveAgentSessionCreateRefusal +} from '../../../shared/agent-session-definitive-refusal' import { readAgentSessionRefusalReference } from '../../../shared/agent-session-wire-refusals' import { readAgentSessionErrorRefusal } from '../../../shared/agent-session-write-failure' import { @@ -81,7 +84,8 @@ export async function launchStructuredAgentSession( onHostSeed?: StructuredLaunchHostSeedListener, priorCreateOutcomeUnknown = false ): Promise { - const hostSeed = await requireHostCreateSupport(intent) + // A resume's owner must answer even when a fresh launch is unavailable. + const hostSeed = intent.params.resumeFrom ? undefined : await requireHostCreateSupport(intent) if (intent.target.kind !== 'local') { onHostSeed?.(hostSeed) } @@ -120,15 +124,14 @@ export async function launchStructuredAgentSession( if (!result.ok) { const { code, message, ownerVerdict } = result.refusal const refusal = readAgentSessionRefusalReference(result.refusal) - const transcriptRefusedBeforeCommit = + const attemptRefusedBeforeCommit = !priorCreateOutcomeUnknown && result.refusal.createAttemptRefusedBeforeCommit === true && - refusal?.code === 'agent_session_identity_required' && - (refusal.details?.reason === 'transcriptNotFound' || - refusal.details?.reason === 'transcriptUnreadable') - // A proven precommit transcript refusal lets a new operation retry. + refusal !== undefined && + isAgentSessionCreateAdmissionRefusal(refusal) + // Attempt proof cannot settle an earlier create whose reply was lost. if ( - !transcriptRefusedBeforeCommit && + !attemptRefusedBeforeCommit && !isDefinitiveAgentSessionCreateRefusal(code) && ownerVerdict !== 'exited' ) { diff --git a/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts b/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts index c90c22da7b63..3600ac79ac23 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts @@ -65,6 +65,7 @@ let replayVerdict: AgentSessionOwnerVerdict | undefined /** A host that answers the proven exit on the first call, not only on replay. */ let refuseFirstCall = false let missingHistory: boolean | 'legacy' = false +let ownershipRefusal: AgentSessionWireRefusal | null = null let failedOperation: string | null = null let publishedSessionId: string | null = null const createdOperations: string[] = [] @@ -92,7 +93,7 @@ function hostCreate(envelope: AgentSessionMutationEnvelope): unknown { message: EXIT_REASON, ...(replayVerdict ? { ownerVerdict: replayVerdict } : {}) } - return { ok: false, refusal } + return { ok: false, refusal: ownershipRefusal ?? refusal } } async function settle(sessionId: string): Promise { @@ -116,6 +117,7 @@ beforeEach(() => { replayVerdict = 'exited' refuseFirstCall = false missingHistory = false + ownershipRefusal = null failedOperation = null publishedSessionId = null createdOperations.length = 0 @@ -154,6 +156,29 @@ describe('structured launch after a host-failed create', () => { expect(getStructuredAgentSessionLaunchLifecycle(WORKTREE, sessionId)).toBeNull() }) + it.each(['agent_session_conflict', 'agent_session_ownership_unknown'] as const)( + 'settles a proven first-attempt %s with its owner, but keeps an earlier lost reply unknown', + async (code) => { + const details = { + reason: 'conversationHeldElsewhere' as const, + owner: { sessionId: 'owner-chat', workspaceId: 'owner-workspace' } + } + ownershipRefusal = { code, details, message: code, createAttemptRefusedBeforeCommit: true } + refuseFirstCall = true + replayVerdict = undefined + const started = startStructuredAgentLaunch(WORKTREE, 'codex', { requestId: 'owned-click' }) + await expect(started.launchResult).rejects.toMatchObject({ refusal: { code, details } }) + await settle(started.sessionId) + expect(getStructuredAgentSessionLaunchLifecycle(WORKTREE, started.sessionId)).toBe('failed') + refuseFirstCall = false + createdOperations.length = 0 + failedOperation = null + const unknown = launch() + await settle(unknown) + expect(getStructuredAgentSessionLaunchLifecycle(WORKTREE, unknown)).toBe('visibility-unknown') + } + ) + it('retains a missing-history failed tab with Retry, then starts a new attempt', async () => { refuseFirstCall = true missingHistory = true diff --git a/src/shared/agent-session-definitive-refusal.ts b/src/shared/agent-session-definitive-refusal.ts index 80721592ed9a..ddbfc33e6d7b 100644 --- a/src/shared/agent-session-definitive-refusal.ts +++ b/src/shared/agent-session-definitive-refusal.ts @@ -12,7 +12,22 @@ * never falls back. */ -import type { AgentSessionWireRefusalCode } from './agent-session-wire' +import type { AgentSessionWireRefusal, AgentSessionWireRefusalCode } from './agent-session-wire' + +/** Admission reasons eligible for attempt-level proof, only at a boundary before commit. */ +export function isAgentSessionCreateAdmissionRefusal( + refusal: Pick +): boolean { + return ( + ((refusal.code === 'agent_session_conflict' || + refusal.code === 'agent_session_ownership_unknown') && + refusal.details?.reason === 'conversationHeldElsewhere') || + (refusal.code === 'agent_session_identity_required' && + (refusal.details?.reason === 'transcriptNotFound' || + refusal.details?.reason === 'transcriptEmpty' || + refusal.details?.reason === 'transcriptUnreadable')) + ) +} /** Proves the host neither created a session nor will on a retry. */ const DEFINITIVE_REFUSAL_CODES: ReadonlySet = new Set([ diff --git a/src/shared/agent-session-refusal-details.ts b/src/shared/agent-session-refusal-details.ts index 8aea50584bf6..2301fbddf990 100644 --- a/src/shared/agent-session-refusal-details.ts +++ b/src/shared/agent-session-refusal-details.ts @@ -116,7 +116,12 @@ export const AGENT_SESSION_REFUSAL_REASONS = { ], execution_owner_reconciling: ['hostReconciling', 'recordUnreadable'], agent_session_checkpoint_stale: ['fenceStale', 'leaseMoved', 'recordMissing'], - agent_session_identity_required: ['recordMissing', 'transcriptNotFound', 'transcriptUnreadable'], + agent_session_identity_required: [ + 'recordMissing', + 'transcriptNotFound', + 'transcriptEmpty', + 'transcriptUnreadable' + ], agent_session_operation_conflict: ['fingerprintMismatch', 'operationIdReused', 'handoffInFlight'], agent_session_operation_expired: ['operationExpired'], agent_session_operation_capacity: ['operationCapacity'], @@ -165,6 +170,10 @@ type PromptFacts = { type NoFacts = Record +export type AgentSessionConversationOwner = { sessionId: string; workspaceId: string } + +type ConversationOwnerFacts = { owner?: AgentSessionConversationOwner } + /** The facts a code carries beside its reason. */ type AgentSessionRefusalFactsByCode = { agent_session_operation_invalid: RewindFacts & { @@ -181,8 +190,8 @@ type AgentSessionRefusalFactsByCode = { } agent_session_item_revision_stale: PromptFacts agent_session_already_resolved: PromptFacts - agent_session_ownership_unknown: NoFacts - agent_session_conflict: NoFacts + agent_session_ownership_unknown: ConversationOwnerFacts + agent_session_conflict: ConversationOwnerFacts execution_owner_reconciling: NoFacts agent_session_identity_required: NoFacts agent_session_operation_conflict: NoFacts @@ -303,9 +312,20 @@ export function readAgentSessionRefusalDetails 0 && + typeof value.owner.workspaceId === 'string' && + value.owner.workspaceId.trim().length > 0 + ? { sessionId: value.owner.sessionId, workspaceId: value.owner.workspaceId } + : undefined const read = { ...(isAgentSessionRefusalReason(code, value.reason) ? { reason: value.reason } : {}), ...facts, + ...(owner ? { owner } : {}), ...(code === 'agent_session_operation_invalid' && value.reason === 'notSignedIn' && (value.account === 'managed' || value.account === 'system') diff --git a/src/shared/agent-session-refusal-reason-words.ts b/src/shared/agent-session-refusal-reason-words.ts index 4c9da698eb58..64a50e96157f 100644 --- a/src/shared/agent-session-refusal-reason-words.ts +++ b/src/shared/agent-session-refusal-reason-words.ts @@ -157,7 +157,8 @@ const REASON_WORDS = { agent_session_identity_required: { recordMissing: causeWords('chatNotFound', 'goElsewhere', 'startNewChat'), transcriptNotFound: codeWords('retry'), - transcriptUnreadable: codeWords('hostFinding') + transcriptEmpty: codeWords('retry'), + transcriptUnreadable: causeWords('historyUnavailable', 'retry', 'tryAgain') }, agent_session_operation_conflict: { fingerprintMismatch: codeWords('hostFinding'), diff --git a/src/shared/agent-session-wire-refusals.test.ts b/src/shared/agent-session-wire-refusals.test.ts index af017a617e74..c93999cf0607 100644 --- a/src/shared/agent-session-wire-refusals.test.ts +++ b/src/shared/agent-session-wire-refusals.test.ts @@ -29,6 +29,23 @@ function asReleasedClientSeesIt(refusal: AgentSessionWireRefusal): unknown { } describe('a refusal names only a reason its code lists', () => { + it('decodes only a complete owner pointer from an ownership refusal', () => { + const owner = { sessionId: 'chat-1', workspaceId: 'workspace-2' } + for (const code of ['agent_session_conflict', 'agent_session_ownership_unknown'] as const) { + const details = { reason: 'conversationHeldElsewhere', owner } + expect(readAgentSessionRefusalReference({ code, details })).toEqual({ code, details }) + expect( + readAgentSessionRefusalDetails(code, { + ...details, + owner: { sessionId: 'chat-1' } + }) + ).toEqual({ reason: 'conversationHeldElsewhere' }) + } + expect( + readAgentSessionRefusalDetails('agent_session_identity_required', { owner }) + ).toBeUndefined() + }) + it('rejects a reason another code lists, at compile time', () => { // @ts-expect-error `promptGone` is an operation_invalid reason, not a conflict one. refuse('agent_session_conflict', { reason: 'promptGone' }, 'm') From 8256fa6999c40559ffce0046ad75e7a26353e9a4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:39:34 -0700 Subject: [PATCH 02/38] test(native-chat): consolidate transcript refusal cases --- ...ured-agent-session-create-adoption.test.ts | 47 ++++++++----------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index 49c82f5fc807..74bb802e599f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -132,20 +132,6 @@ it('refuses concurrent adoption of a provider conversation by another session', expect(rig.adapter.acquire).not.toHaveBeenCalled() }) -it('distinguishes an empty saved source from an unreadable one without founding a chat', async () => { - const params = await adoptedParams() - await writeFile(join(rig.root, 'rollout.jsonl'), '') - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { - details: { reason: 'transcriptEmpty' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) -}) - it('refuses concurrent founding under a tab another chat already owns', async () => { const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) const results = await Promise.all([ @@ -160,20 +146,25 @@ it('refuses concurrent founding under a tab another chat already owns', async () expect(rig.adapter.acquire).not.toHaveBeenCalled() }) -it('refuses history lost after discovery before founding anything', async () => { - const params = await adoptedParams() - await rm(join(rig.root, 'rollout.jsonl')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_identity_required', - details: { reason: 'transcriptUnreadable' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) -}) +it.each(['missing', 'empty'] as const)( + 'refuses %s history before founding anything', + async (source) => { + const params = await adoptedParams() + await (source === 'missing' + ? rm(join(rig.root, 'rollout.jsonl')) + : writeFile(join(rig.root, 'rollout.jsonl'), '')) + expect(await rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: source === 'missing' ? 'transcriptUnreadable' : 'transcriptEmpty' }, + createAttemptRefusedBeforeCommit: true + } + }) + expect(rig.store.listRecords()).toEqual([]) + expect(rig.store.listOperationRows()).toEqual([]) + } +) it('does not found a record whose account namespace its agent cannot drive', async () => { const params = createTestParams(undefined, { From 0ebb6f4e079af12cd2cd599dad84bfaf1763cb58 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:43:03 -0700 Subject: [PATCH 03/38] test(native-chat): keep ownership coverage at the launch boundary --- src/shared/agent-session-wire-refusals.test.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/shared/agent-session-wire-refusals.test.ts b/src/shared/agent-session-wire-refusals.test.ts index c93999cf0607..af017a617e74 100644 --- a/src/shared/agent-session-wire-refusals.test.ts +++ b/src/shared/agent-session-wire-refusals.test.ts @@ -29,23 +29,6 @@ function asReleasedClientSeesIt(refusal: AgentSessionWireRefusal): unknown { } describe('a refusal names only a reason its code lists', () => { - it('decodes only a complete owner pointer from an ownership refusal', () => { - const owner = { sessionId: 'chat-1', workspaceId: 'workspace-2' } - for (const code of ['agent_session_conflict', 'agent_session_ownership_unknown'] as const) { - const details = { reason: 'conversationHeldElsewhere', owner } - expect(readAgentSessionRefusalReference({ code, details })).toEqual({ code, details }) - expect( - readAgentSessionRefusalDetails(code, { - ...details, - owner: { sessionId: 'chat-1' } - }) - ).toEqual({ reason: 'conversationHeldElsewhere' }) - } - expect( - readAgentSessionRefusalDetails('agent_session_identity_required', { owner }) - ).toBeUndefined() - }) - it('rejects a reason another code lists, at compile time', () => { // @ts-expect-error `promptGone` is an operation_invalid reason, not a conflict one. refuse('agent_session_conflict', { reason: 'promptGone' }, 'm') From 1e649eb772e1a4622f84f948f0ac81bd72644e89 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:51:38 -0700 Subject: [PATCH 04/38] test(native-chat): update adoption fixture for early ownership admission --- .../structured-agent-cli-conversation-adoption.test.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts index 42009e6d884f..d93743961005 100644 --- a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts +++ b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts @@ -141,12 +141,10 @@ function adopt( throw new Error(`${agent} registers no transcript import`) } return resolveStructuredAgentSessionAdoptionForCreate({ - host: null, settings: {}, agent, transcriptImport, providerSessionId, - selfSessionId: 'chat-1', selectedAccountHome, launchEnv, workspaceCwd From 19a79bf4fb55dd877671c5567703567d86b0a527 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:25:37 -0700 Subject: [PATCH 05/38] test(native-chat): align resume admission assertions with host ownership --- ...ructured-agent-session-precommit-refusal.test.ts | 7 ------- ...red-agent-session-launch-resume-identity.test.ts | 13 +++++++++---- src/shared/agent-session-refusal-notice.test.ts | 5 ++++- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts index 8f3e5096d864..2b90b51af6f7 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts @@ -139,13 +139,6 @@ describe('a create refused before it commits', () => { reason: 'conversationHeldElsewhere', owner: { sessionId: 'owner', workspaceId: 'workspace' } } - ], - [ - 'agent_session_ownership_unknown', - { - reason: 'conversationHeldElsewhere', - owner: { sessionId: 'owner', workspaceId: 'workspace' } - } ] ] as const)('answers %s before commit as a definite failed attempt', async (code, details) => { const response = await create({ diff --git a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts index 12cc3c06c5ee..ae482e0c5d96 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts @@ -91,10 +91,15 @@ describe('a launch that adopts a conversation is its own identity', () => { // A resumed conversation may keep its own model, so its picker names no listed default. expect(getStructuredAgentSessionLaunchResumes(resume.sessionId)).toBe(true) expect(getStructuredAgentSessionLaunchResumes(blank.sessionId)).toBe(false) - expect(createParams()).toEqual([ - expect.not.objectContaining({ resumeFrom: expect.anything() }), - expect.objectContaining({ resumeFrom: { providerSessionId: 'thread-1' } }) - ]) + const requests = createParams() + expect(requests).toHaveLength(2) + const blankRequest = requests.find((params) => params.envelope.sessionId === blank.sessionId) + expect(blankRequest).toMatchObject({ resumeFrom: undefined }) + expect( + requests.find((params) => params.envelope.sessionId === resume.sessionId)?.resumeFrom + ).toEqual({ + providerSessionId: 'thread-1' + }) }) it('does not hand a blank launch the resume already pending for the same worktree', async () => { diff --git a/src/shared/agent-session-refusal-notice.test.ts b/src/shared/agent-session-refusal-notice.test.ts index 1586c9c92b00..cf9826ed9c82 100644 --- a/src/shared/agent-session-refusal-notice.test.ts +++ b/src/shared/agent-session-refusal-notice.test.ts @@ -465,7 +465,10 @@ describe('the notice for every reason a host names', () => { failure.details?.reason !== 'hostUnsupported' && write !== 'read-history' const saysNotDone = - write === 'read-history' && failure.code === 'agent_session_journal_unreadable' + write === 'read-history' && + (failure.code === 'agent_session_journal_unreadable' || + (failure.code === 'agent_session_identity_required' && + failure.details?.reason === 'transcriptUnreadable')) // "Run /clear when it's done" already says the command has yet to happen. const clearWhileWorking = ( [ From 92e477381caa7aaca7f97bab3c306f084ca23437 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:26:16 -0700 Subject: [PATCH 06/38] test(native-chat): keep RPC coverage focused on ownership proof --- ...tured-agent-session-precommit-refusal.test.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts index 2b90b51af6f7..2085f4a8ca57 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts @@ -131,16 +131,12 @@ afterEach(() => { }) describe('a create refused before it commits', () => { - it.each([ - ['agent_session_identity_required', { reason: 'transcriptNotFound' }], - [ - 'agent_session_conflict', - { - reason: 'conversationHeldElsewhere', - owner: { sessionId: 'owner', workspaceId: 'workspace' } - } - ] - ] as const)('answers %s before commit as a definite failed attempt', async (code, details) => { + it('answers an ownership refusal before commit as a definite failed attempt', async () => { + const code = 'agent_session_conflict' + const details = { + reason: 'conversationHeldElsewhere' as const, + owner: { sessionId: 'owner', workspaceId: 'workspace' } + } const response = await create({ resolveStructuredAgentSessionCreateIntent: vi.fn(async () => { throw agentSessionRefusalError(code, details) From bd557bf796d142357af1201e2794b974826c38fd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:28:56 -0700 Subject: [PATCH 07/38] test(native-chat): assert blank request presence before optional source --- .../lib/structured-agent-session-launch-exited-owner.test.ts | 1 - .../structured-agent-session-launch-resume-identity.test.ts | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts b/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts index 3600ac79ac23..863e087cb81f 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-exited-owner.test.ts @@ -165,7 +165,6 @@ describe('structured launch after a host-failed create', () => { } ownershipRefusal = { code, details, message: code, createAttemptRefusedBeforeCommit: true } refuseFirstCall = true - replayVerdict = undefined const started = startStructuredAgentLaunch(WORKTREE, 'codex', { requestId: 'owned-click' }) await expect(started.launchResult).rejects.toMatchObject({ refusal: { code, details } }) await settle(started.sessionId) diff --git a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts index ae482e0c5d96..50847c5b8d14 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts @@ -94,7 +94,8 @@ describe('a launch that adopts a conversation is its own identity', () => { const requests = createParams() expect(requests).toHaveLength(2) const blankRequest = requests.find((params) => params.envelope.sessionId === blank.sessionId) - expect(blankRequest).toMatchObject({ resumeFrom: undefined }) + expect(blankRequest?.envelope.sessionId).toBe(blank.sessionId) + expect(blankRequest?.resumeFrom).toBeUndefined() expect( requests.find((params) => params.envelope.sessionId === resume.sessionId)?.resumeFrom ).toEqual({ From 4ce33f991f3e8062b6bd20cf92616809a44e8495 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:43:36 -0700 Subject: [PATCH 08/38] fix(native-chat): admit the actual CLI source during chat creation --- ...session-scanner-discovery-wsl-gate.test.ts | 12 ++ .../ai-vault/session-scanner-discovery.ts | 3 +- src/main/claude/claude-cli-conversations.ts | 6 +- src/main/codex/codex-cli-conversations.ts | 6 +- src/main/grok/grok-transcript-import.ts | 5 +- .../adopted-transcript-source.ts | 83 ++++++++++++ .../journal-legacy-import.ts | 18 +++ ...structured-agent-session-adopted-import.ts | 4 +- .../structured-agent-session-attach.ts | 1 + .../native-chat/codex-adoption-preparation.ts | 37 ++++++ src/main/native-chat/session-file-resolver.ts | 36 ++++-- .../structured-agent-cli-conversations.ts | 20 ++- .../structured-agent-cli-source.ts | 34 +++++ ...red-agent-session-source-admission.test.ts | 118 ++++++++++++++++++ .../transcript-opencode-sqlite-query.test.ts | 2 + .../transcript-opencode-sqlite-query.ts | 8 +- .../transcript-opencode2-sqlite.test.ts | 5 +- .../transcript-opencode2-sqlite.ts | 6 +- .../native-chat/transcript-path-admission.ts | 18 +++ src/main/omp/omp-session-cwd-lookup.ts | 5 +- src/main/omp/omp-transcript-import.ts | 18 ++- .../opencode/opencode-transcript-import.ts | 43 ++++--- src/main/pi/pi-transcript-import.ts | 4 +- ...ctured-agent-session-create-intent.test.ts | 9 +- .../structured-session-create-support.ts | 35 +++--- ...tructured-agent-session-create-adoption.ts | 62 +++++++-- src/shared/protocol-version.ts | 3 +- .../structured-agent-session-params.ts | 9 +- .../structured-agent-session-create.test.ts | 21 +++- src/shared/structured-agent-session-create.ts | 2 + .../structured-agent-session-mutation.ts | 4 +- ...ured-agent-session-surface-capabilities.ts | 5 + 32 files changed, 560 insertions(+), 82 deletions(-) create mode 100644 src/main/native-chat/agent-session-journal/adopted-transcript-source.ts create mode 100644 src/main/native-chat/codex-adoption-preparation.ts create mode 100644 src/main/native-chat/structured-agent-cli-source.ts create mode 100644 src/main/native-chat/structured-agent-session-source-admission.test.ts create mode 100644 src/main/native-chat/transcript-path-admission.ts diff --git a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts index 5e0e686651c6..313ee76a5616 100644 --- a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts +++ b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts @@ -148,3 +148,15 @@ describe('discoverFiles containment for a stalled WSL root', () => { } }) }) + +it('execution admission preserves native access errors while confirmed missing roots remain absent', async () => { + for (const code of ['EACCES', 'ENOENT']) { + const failure = Object.assign(new Error(code), { code }) + const search = walkSessionFiles('/account/sessions', 'codex', [], { + extensions: new Set(['.jsonl']), strictErrors: true, + readDirectory: async () => { throw failure } + }) + if (code === 'ENOENT') await expect(search).resolves.toEqual([]) + else await expect(search).rejects.toBe(failure) + } +}) diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index 24ba97ebf4c8..762c3bf5cb38 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -234,6 +234,7 @@ export type SessionFileWalkOptions = { // Return false to skip descending into a directory; depth 0 is a child of // rootDir, so pruned subtrees are never stat'd or parsed. directoryPredicate?: (name: string, depth: number) => boolean + strictErrors?: boolean readDirectory?: (dirPath: string) => Promise signal?: AbortSignal } @@ -271,7 +272,7 @@ export async function forEachSessionFile( options.signal?.throwIfAborted() // Why: a gate refusal means the scan could not run, not that the tree is // empty — swallowing it would misreport a stalled distro as "no transcript". - if (error instanceof WslTranscriptFsError) { + if (error instanceof WslTranscriptFsError || (options.strictErrors && !isMissingSidecarError(error))) { throw error } return diff --git a/src/main/claude/claude-cli-conversations.ts b/src/main/claude/claude-cli-conversations.ts index 47e44e00fc56..0a7be1041b82 100644 --- a/src/main/claude/claude-cli-conversations.ts +++ b/src/main/claude/claude-cli-conversations.ts @@ -11,14 +11,16 @@ import { } from '../native-chat/structured-agent-cli-conversations' const CLAUDE_TRANSCRIPT_IMPORT = directoryTranscriptImport({ + transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'projects'), accountHomeCandidates: ({ selectedAccountHomePath }) => [ selectedAccountHomePath, join(homedir(), '.claude'), ...(getClaudeProfileRouter()?.accountHomes() ?? []) ], - findTranscript: ({ providerSessionId, accountHomePath }) => + findTranscript: ({ providerSessionId, accountHomePath, strictErrors }) => resolveSessionFilePath('claude', providerSessionId, { - claudeProjectsDir: join(accountHomePath, 'projects') + claudeProjectsDir: join(accountHomePath, 'projects'), + strictErrors }) }) diff --git a/src/main/codex/codex-cli-conversations.ts b/src/main/codex/codex-cli-conversations.ts index 49f1e0c6f6e3..2b4e971afddf 100644 --- a/src/main/codex/codex-cli-conversations.ts +++ b/src/main/codex/codex-cli-conversations.ts @@ -10,6 +10,7 @@ import { import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' const CODEX_TRANSCRIPT_IMPORT = directoryTranscriptImport({ + transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), accountHomeCandidates: ({ settings, selectedAccountHomePath }) => [ selectedAccountHomePath, ...(settings.codexManagedAccounts ?? []).map((account) => account.managedHomePath), @@ -17,9 +18,10 @@ const CODEX_TRANSCRIPT_IMPORT = directoryTranscriptImport({ getOrcaManagedCodexHomePath(), getSystemCodexHomePath() ], - findTranscript: ({ providerSessionId, accountHomePath }) => + findTranscript: ({ providerSessionId, accountHomePath, strictErrors }) => resolveSessionFilePath('codex', providerSessionId, { - codexSessionsDirs: [join(accountHomePath, 'sessions')] + codexSessionsDirs: [join(accountHomePath, 'sessions')], + strictErrors }) }) diff --git a/src/main/grok/grok-transcript-import.ts b/src/main/grok/grok-transcript-import.ts index 7590bef9dc3f..8f995210adfb 100644 --- a/src/main/grok/grok-transcript-import.ts +++ b/src/main/grok/grok-transcript-import.ts @@ -4,19 +4,20 @@ import { resolveSessionFilePath } from '../native-chat/session-file-resolver' import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-conversations' export const GROK_TRANSCRIPT_IMPORT = directoryTranscriptImport({ + transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), // The chat's own home, then the one Session History lists Grok's conversations from. accountHomeCandidates: ({ selectedAccountHomePath }) => [ selectedAccountHomePath, resolveGrokHomeDir() ], - findTranscript: async ({ providerSessionId, accountHomePath, workspaceCwd }) => { + findTranscript: async ({ providerSessionId, accountHomePath, workspaceCwd, strictErrors }) => { const sessionsDir = join(accountHomePath, 'sessions') return ( (await findGrokChatHistoryByCwd({ sessionId: providerSessionId, cwd: workspaceCwd, sessionsDir - })) ?? resolveSessionFilePath('grok', providerSessionId, { grokSessionsDir: sessionsDir }) + })) ?? resolveSessionFilePath('grok', providerSessionId, { grokSessionsDir: sessionsDir, strictErrors }) ) } }) diff --git a/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts new file mode 100644 index 000000000000..7950e2e13725 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts @@ -0,0 +1,83 @@ +import { sessionIdFromFileName } from '../../ai-vault/session-scanner-accumulator' +import { dirname, join } from 'node:path' +import type { AgentType } from '../../../shared/agent-status-types' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader' +import { asRecord, extractString, parseJsonObject } from '../../ai-vault/session-scanner-values' +import { readOpenCodeTranscriptSignalViaWorker } from '../../ai-vault/session-scanner-opencode-sqlite-worker-spawn' +import { samePiDirectory } from '../../pi/rpc-launch-resolution' +import { admitTranscriptPath } from '../transcript-path-admission' + +export type AdoptedTranscriptSource = { providerSessionId: string; workspaceCwd: string } + +export function assertAdoptedSourceIdentity( + source: AdoptedTranscriptSource, + actual: { sessionId: string | null; cwd: string | null }, + requireCwd = true +): void { + if (actual.sessionId !== source.providerSessionId) { + throw new Error('The saved conversation does not match the requested provider identity.') + } + if (requireCwd && (!actual.cwd || normalizeRuntimePathForComparison(actual.cwd.trim()) !== + normalizeRuntimePathForComparison(source.workspaceCwd.trim()))) { + throw new Error('This conversation belongs to another directory.') + } +} + +/** Metadata is observed from the same lines that become the imported journal. */ +export async function adoptedTranscriptSourceObserver(input: { + agent: AgentType + filePath: string + source: AdoptedTranscriptSource + maxSourceBytes: number +}) { + let sessionId: string | null = input.agent === 'claude' || input.agent === 'codex' + ? sessionIdFromFileName(input.filePath) : null + let cwd: string | null = null + let sawCodexMetadata = false + if (input.agent === 'grok') { + const summaryPath = join(dirname(input.filePath), 'summary.json') + if (!(await admitTranscriptPath(dirname(input.filePath), summaryPath))) { + throw new Error('The conversation summary is outside its storage directory.') + } + const { buffer } = await readNodeFileWithinLimit(summaryPath, input.maxSourceBytes, { regularFileOnly: true }) + const summary = asRecord(asRecord(JSON.parse(buffer.toString('utf8')))?.info) + sessionId = extractString(summary?.id) ?? sessionIdFromFileName(dirname(input.filePath)) + cwd = extractString(summary?.cwd) + } + return { + observe(line: string) { + const record = parseJsonObject(line) + if (!record) return + if (input.agent === 'claude') { + sessionId = extractString(record.sessionId) ?? sessionId + cwd ??= extractString(record.cwd) + } else if (input.agent === 'codex' && record.type === 'session_meta' && !sawCodexMetadata) { + sawCodexMetadata = true + const payload = asRecord(record.payload) + sessionId = extractString(payload?.id) ?? sessionId + } else if ((input.agent === 'omp' || input.agent === 'pi') && record.type === 'session') { + sessionId = extractString(record.id) + cwd = extractString(record.cwd) + } + }, + async validate() { + if (input.agent === 'pi' && sessionIdFromFileName(input.filePath) !== sessionId) { + throw new Error('The saved conversation header does not match its file identity.') + } + if (input.agent === 'pi' && cwd && await samePiDirectory(cwd, input.source.workspaceCwd)) { + cwd = input.source.workspaceCwd + } + assertAdoptedSourceIdentity(input.source, { sessionId, cwd }, input.agent !== 'codex') + } + } +} + +export async function validateAdoptedOpenCodeSource( + dbPath: string, source: AdoptedTranscriptSource +): Promise { + const signal = await readOpenCodeTranscriptSignalViaWorker({ dbPath, sessionId: source.providerSessionId }) + assertAdoptedSourceIdentity(source, { + sessionId: signal ? source.providerSessionId : null, cwd: signal?.cwd ?? null + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index e69abd28a676..dcbde8dccf03 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -10,6 +10,7 @@ // never be spliced into a sequence space that a structured session is also // writing; a later structured resume rolls the epoch again and rebuilds. +import { adoptedTranscriptSourceObserver, validateAdoptedOpenCodeSource, type AdoptedTranscriptSource } from './adopted-transcript-source' import { createReadStream } from 'node:fs' import { stat } from 'node:fs/promises' import type { AgentType } from '../../../shared/agent-status-types' @@ -44,6 +45,7 @@ import type { AgentSessionJournal } from './journal-store' export type LegacyImportOptions = ResolveSessionFileOptions & { /** Resolve directly to this file, skipping path discovery. */ filePath?: string + source?: AdoptedTranscriptSource limits?: JournalPayloadLimits decodedMessageIdentities?: true } @@ -127,6 +129,7 @@ export async function prepareLegacyTranscriptImport(input: { transcriptAgent, agent: input.agent, sessionId: input.sessionId, + source: options.source, decodedMessageIdentities: options.decodedMessageIdentities }) } catch (err) { @@ -148,6 +151,14 @@ async function prepareOpenCodeImport(input: { limits: JournalPayloadLimits }): Promise<{ ok: true; items: JournalReplacementItem[] } | { ok: false; error: string }> { const dbPath = input.options?.filePath + if (input.options?.source) { + if (!dbPath) return { ok: false, error: 'The conversation database is unavailable.' } + try { + await validateAdoptedOpenCodeSource(dbPath, input.options.source) + } catch (error) { + return { ok: false, error: error instanceof Error ? error.message : String(error) } + } + } const read = await readOpenCodeNativeChatTranscriptFull( input.sessionId, dbPath ? { resolveDbPath: async () => dbPath } : {} @@ -201,7 +212,12 @@ async function decodeWithIdentities(input: { agent: AgentType sessionId: string decodedMessageIdentities?: true + source?: AdoptedTranscriptSource }): Promise<{ messages: NativeChatMessage[]; identities: AgentJournalItemIdentity[] }> { + const source = input.source ? await adoptedTranscriptSourceObserver({ + agent: input.agent, filePath: input.filePath, source: input.source, + maxSourceBytes: MAX_LEGACY_IMPORT_SOURCE_BYTES + }) : null const tracker = createLegacyIdentityTracker({ transcriptAgent: input.transcriptAgent, agent: input.agent, @@ -219,6 +235,7 @@ async function decodeWithIdentities(input: { input.filePath, 0, (line, fallbackId) => { + source?.observe(line) const trackedIdentity = tracker.identify(line, lineIndex) lineIndex += 1 if (pi) { @@ -243,6 +260,7 @@ async function decodeWithIdentities(input: { true, MAX_LEGACY_IMPORT_SOURCE_BYTES ) + await source?.validate() if (pi) { return pi.project() } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts index fe4db165d609..6e0a3478512b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts @@ -50,7 +50,7 @@ async function readAdoptedTranscript( const prepared = await prepareLegacyTranscriptImport({ agent: params.agent, sessionId: adopt.providerHandle.nativeId, - options: { filePath: adopt.transcriptPath } + options: { filePath: adopt.transcriptPath, source: adopt.source } }) if (!prepared.ok) { throw new Error(prepared.error) @@ -111,7 +111,7 @@ async function applyAdoptedTranscript( agent: params.agent, sessionId: adopt.providerHandle.nativeId, fence: record.lease.runtimeFence, - options: { filePath: adopt.transcriptPath } + options: { filePath: adopt.transcriptPath, source: adopt.source } }) if (!imported.ok) { throw new Error(imported.error) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts index c0ce0923e436..756d0fc95581 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts @@ -81,6 +81,7 @@ export type AgentSessionAttachParams = { providerHandle: AgentSessionProviderHandle /** Omitted only when the exact committed operation replays an already-imported journal. */ transcriptPath?: string + source?: { providerSessionId: string; workspaceCwd: string } } } diff --git a/src/main/native-chat/codex-adoption-preparation.ts b/src/main/native-chat/codex-adoption-preparation.ts new file mode 100644 index 000000000000..45a11ce330a0 --- /dev/null +++ b/src/main/native-chat/codex-adoption-preparation.ts @@ -0,0 +1,37 @@ +import { stat } from 'node:fs/promises' +import { join } from 'node:path' +import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome } from '../../shared/agent-session-account-home' +import type { AiVaultSessionResumePreparation } from '../../shared/ai-vault-resume-preparation' +import { getSystemCodexHomePath } from '../codex/codex-home-paths' +import type { StructuredAgentSessionAdoption } from './structured-agent-session-history-adoption' +import { admitTranscriptPath } from './transcript-path-admission' +import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' + +/** Use the existing host preparation before pinning credentials and importing history. */ +export async function prepareCodexAdoption( + source: StructuredAgentSessionAdoption, + providerSessionId: string, + prepare: AiVaultSessionResumePreparation | undefined, + recognizedHomes: readonly AgentSessionAccountHome[] +): Promise { + if (!prepare || !isLegacyAgentSessionAccountHome(source.accountHome)) return source + const result = await prepare({ + agent: 'codex', sessionId: providerSessionId, filePath: source.transcriptPath, + codexHome: source.accountHome.path, executionHostId: 'local' + }) + const home = result.useRealCodexHome ? getSystemCodexHomePath() : result.substituteCodexHome + if (!home || normalizeRuntimePathForComparison(home) === + normalizeRuntimePathForComparison(source.accountHome.path)) return source + if (!result.useRealCodexHome && !recognizedHomes.some((candidate) => + isLegacyAgentSessionAccountHome(candidate) && normalizeRuntimePathForComparison(candidate.path) === + normalizeRuntimePathForComparison(home))) { + throw new Error('The prepared conversation account is not recognized on this host.') + } + const original = await admitTranscriptPath(join(source.accountHome.path, 'sessions'), source.transcriptPath) + if (!original?.relativePath) throw new Error('The conversation path could not be verified.') + const prepared = await admitTranscriptPath(join(home, 'sessions'), join(home, 'sessions', original.relativePath)) + if (!prepared || !(await stat(prepared.path)).isFile()) { + throw new Error('The prepared conversation history is unavailable.') + } + return { accountHome: { variable: 'CODEX_HOME', path: home }, transcriptPath: prepared.path } +} diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index d7f674e6eae7..72d31536045e 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -63,6 +63,8 @@ function grokSessionsDir(): string { } export type ResolveSessionFileOptions = { + /** Execution admission must distinguish an unreadable tree from an absent source. */ + strictErrors?: boolean /** Override the Claude projects root (used by tests / isolated scans). */ claudeProjectsDir?: string /** Override the Codex sessions roots, searched in order (tests / isolated @@ -177,7 +179,8 @@ async function resolveSessionFileById( const override = options.claudeProjectsDir return resolveTiered('claude', trimmedId, override ? [override] : claudeProjectsDirs(), { wslTier: !override, - signal + signal, + strictErrors: options.strictErrors }) } if (transcriptAgent === 'codex') { @@ -185,14 +188,16 @@ async function resolveSessionFileById( return resolveTiered('codex', trimmedId, override ?? codexSessionsDirs(), { wslTier: !override, ...(override ? {} : { accountDirs: codexAccountSessionsDirs }), - signal + signal, + strictErrors: options.strictErrors }) } if (transcriptAgent === 'grok') { const override = options.grokSessionsDir return resolveTiered('grok', trimmedId, [override ?? grokSessionsDir()], { wslTier: !override, - signal + signal, + strictErrors: options.strictErrors }) } if (transcriptAgent === 'omp') { @@ -200,7 +205,8 @@ async function resolveSessionFileById( const root = resolveOmpSessionsDir({ sessionsDir: override }) return resolveTiered('omp', trimmedId, root ? [root] : [], { wslTier: override === undefined, - signal + signal, + strictErrors: options.strictErrors }) } // Why: a new transcript agent must pick its own resolver. Falling through to @@ -218,15 +224,15 @@ async function resolveTiered( agent: SessionIdLookupAgent, sessionId: string, hostDirs: readonly string[], - options: { wslTier: boolean; accountDirs?: () => readonly string[]; signal?: AbortSignal } + options: { wslTier: boolean; accountDirs?: () => readonly string[]; signal?: AbortSignal; strictErrors?: boolean } ): Promise { const { signal } = options - const hit = await findFirstInDirs(agent, sessionId, hostDirs, signal) + const hit = await findFirstInDirs(agent, sessionId, hostDirs, signal, options.strictErrors) if (hit) { return hit } const accountDirs = (options.accountDirs?.() ?? []).filter((dir) => !hostDirs.includes(dir)) - const accountHit = await findFirstInDirs(agent, sessionId, accountDirs, signal) + const accountHit = await findFirstInDirs(agent, sessionId, accountDirs, signal, options.strictErrors) if (accountHit || !options.wslTier) { return accountHit } @@ -235,27 +241,29 @@ async function resolveTiered( // user left stopped. Only pay that after this host's own roots miss (#10326, #13789). const wslDirs = (await wslAgentSessionsDirs(agent)).filter((dir) => !hostDirs.includes(dir)) signal?.throwIfAborted() - return findFirstInDirs(agent, sessionId, wslDirs, signal) + return findFirstInDirs(agent, sessionId, wslDirs, signal, options.strictErrors) } async function findFirstInDirs( agent: SessionIdLookupAgent, sessionId: string, dirs: readonly string[], - signal?: AbortSignal + signal?: AbortSignal, + strictErrors?: boolean ): Promise { let unavailable: WslTranscriptFsError | undefined for (const dir of dirs) { try { const hit = isWslUncPath(dir) ? await findWslSessionPath(agent, dir, sessionId, signal) - : await findHostSessionFile(agent, dir, sessionId, signal) + : await findHostSessionFile(agent, dir, sessionId, signal, strictErrors) if (hit) { return hit } } catch (error) { // A caller abort that races the refusal stays authoritative. signal?.throwIfAborted() + if (strictErrors) throw error // Why: one stalled distro must not hide another root's hit. unavailable = wslTranscriptFsRefusal(error) } @@ -271,9 +279,10 @@ async function findHostSessionFile( agent: SessionIdLookupAgent, root: string, sessionId: string, - signal?: AbortSignal + signal?: AbortSignal, + strictErrors?: boolean ): Promise { - if (agent === 'grok') { + if (agent === 'grok' && !strictErrors) { // Why: Native Chat runs on the main thread; use the bounded async direct-layout // lookup instead of a recursive full-tree scan. signal?.throwIfAborted() @@ -291,7 +300,8 @@ async function findHostSessionFile( directoryPredicate: directoryPredicate ? (name, depth) => directoryPredicate(name, depth, wanted) : undefined, - signal + signal, + strictErrors }) return files[0] ?? null } diff --git a/src/main/native-chat/structured-agent-cli-conversations.ts b/src/main/native-chat/structured-agent-cli-conversations.ts index 3e84138c0c74..8e93b27eb823 100644 --- a/src/main/native-chat/structured-agent-cli-conversations.ts +++ b/src/main/native-chat/structured-agent-cli-conversations.ts @@ -1,6 +1,7 @@ // How a structured agent's chats meet the conversations its own CLI records: adopting one into a new // chat, and owning the Session History rows a chat's conversation shows as. +import { admitTranscriptPath } from './transcript-path-admission' import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome @@ -22,6 +23,12 @@ export type StructuredAgentTranscriptImport = { settings: StructuredAgentTranscriptImportSettings selectedAccountHome: AgentSessionAccountHome }) => AgentSessionAccountHome[] + /** Admit hook and fallback paths against this account's own storage. */ + admitTranscriptPath: (input: { + accountHome: AgentSessionAccountHome + transcriptPath: string + launchEnv: NodeJS.ProcessEnv + }) => Promise /** Where the transcript is (its file, or OpenCode's database); null when the home lacks it. */ findTranscript: (input: { providerSessionId: string @@ -29,6 +36,7 @@ export type StructuredAgentTranscriptImport = { /** The execution host's effective agent environment before account binding. */ launchEnv: NodeJS.ProcessEnv workspaceCwd: string + strictErrors?: boolean }) => Promise /** The adopted chat's handle names the transcript's path, not the conversation id (Pi). */ handleNamesTranscript?: true @@ -36,6 +44,7 @@ export type StructuredAgentTranscriptImport = { /** The import of an agent whose account is one directory, named by the chat's own variable. */ export function directoryTranscriptImport(directories: { + transcriptRoot: (input: { accountHomePath: string; launchEnv: NodeJS.ProcessEnv }) => string | null accountHomeCandidates: (input: { settings: StructuredAgentTranscriptImportSettings selectedAccountHomePath: string @@ -45,10 +54,16 @@ export function directoryTranscriptImport(directories: { accountHomePath: string launchEnv: NodeJS.ProcessEnv workspaceCwd: string + strictErrors?: boolean }) => Promise handleNamesTranscript?: true }): StructuredAgentTranscriptImport { return { + admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { + if (!isLegacyAgentSessionAccountHome(accountHome)) return null + const root = directories.transcriptRoot({ accountHomePath: accountHome.path, launchEnv }) + return root ? (await admitTranscriptPath(root, transcriptPath))?.path ?? null : null + }, ...(directories.handleNamesTranscript ? { handleNamesTranscript: true } : {}), accountHomeCandidates: ({ settings, selectedAccountHome }) => isLegacyAgentSessionAccountHome(selectedAccountHome) @@ -58,13 +73,14 @@ export function directoryTranscriptImport(directories: { .filter((path) => path.length > 0) .map((path) => ({ variable: selectedAccountHome.variable, path })) : [], - findTranscript: async ({ providerSessionId, accountHome, launchEnv, workspaceCwd }) => + findTranscript: async ({ providerSessionId, accountHome, launchEnv, workspaceCwd, strictErrors }) => isLegacyAgentSessionAccountHome(accountHome) ? directories.findTranscript({ providerSessionId, accountHomePath: accountHome.path, launchEnv, - workspaceCwd + workspaceCwd, + strictErrors }) : null } diff --git a/src/main/native-chat/structured-agent-cli-source.ts b/src/main/native-chat/structured-agent-cli-source.ts new file mode 100644 index 000000000000..affaa15862fb --- /dev/null +++ b/src/main/native-chat/structured-agent-cli-source.ts @@ -0,0 +1,34 @@ +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' +import type { StructuredAgentSessionResumeSource } from '../../shared/structured-agent-session-create' +import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' +import { agentSessionRefusalError } from '../../shared/agent-session-wire-refusals' +import { adoptsCliConversations, CLI_CONVERSATION_ADOPTING_AGENTS } from '../../shared/structured-agent-cli-conversation-adoption' +import { isWslUncPath } from '../../shared/wsl-paths' +import { needsWslHostResolution } from './host-readable-transcript-path' +import { parseSshTranscriptPath } from './ssh-transcript-path' + +/** A client names a pane; only this host supplies its provider path. */ +export function structuredAgentCliSourcePath(input: { + agent: StructuredAgentId + resumeFrom: StructuredAgentSessionResumeSource + workspaceId: string + rows: readonly AgentStatusIpcPayload[] +}): string | undefined { + const source = input.resumeFrom.cliSource + if (!source) return undefined + const row = input.rows.find((candidate) => + source.workspaceId === input.workspaceId && candidate.worktreeId === source.workspaceId && + candidate.paneKey === source.paneKey && !candidate.connectionId && !candidate.structuredHost && + adoptsCliConversations(candidate.agentType) && + CLI_CONVERSATION_ADOPTING_AGENTS[candidate.agentType] === input.agent && + candidate.providerSession?.id === input.resumeFrom.providerSessionId) + if (!row) { + throw agentSessionRefusalError('agent_session_identity_required', + { reason: 'transcriptUnreadable' }, 'The source conversation is no longer available.') + } + const path = row.providerSession?.transcriptPath?.trim() + if (path && (isWslUncPath(path) || needsWslHostResolution(path) || parseSshTranscriptPath(path))) { + throw agentSessionRefusalError('structured_agent_session_unsupported', { reason: 'hostUnsupported' }) + } + return path || undefined +} diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts new file mode 100644 index 000000000000..a301674d297e --- /dev/null +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -0,0 +1,118 @@ +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { CLAUDE_CLI_CONVERSATIONS } from '../claude/claude-cli-conversations' +import { resolveStructuredAgentSessionAdoptionForCreate } from '../runtime/structured-agent-session-create-adoption' +import { structuredAgentCliSourcePath } from './structured-agent-cli-source' +import { prepareAdoptedTranscript } from './agent-session-wire/structured-agent-session-adopted-import' +import type { AgentSessionAttachParams } from './agent-session-wire/structured-agent-session-attach' +import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' +import { prepareLegacyTranscriptImport } from './agent-session-journal/journal-legacy-import' +import { prepareCodexAdoption } from './codex-adoption-preparation' +import { prepareLegacySharedCodexSessionResume } from '../codex/codex-legacy-session-resume' +import * as codexHomes from '../codex/codex-home-paths' + +let root: string +beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-source-admission-')) }) +afterEach(async () => { vi.restoreAllMocks(); await rm(root, { recursive: true, force: true }) }) +const id = 'provider-session' +async function file(path: string, records: unknown[]) { + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, records.map((record) => JSON.stringify(record)).join('\n') + '\n') + return path +} +function params(agent: StructuredAgentId, transcriptPath: string): AgentSessionAttachParams { + return { + envelope: { sessionId: 'new-chat', clientOperationId: 'create', expectedRuntimeFence: null, payloadFingerprint: '' }, + location: { executionHostId: 'local', workspaceId: 'folder', workspaceKind: 'folder', wslDistro: null }, + agent, provider: agent, runtimeKind: 'native', accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, + adopt: { providerHandle: { agent, transport: 'terminal-transcript', nativeId: id }, transcriptPath, + source: { providerSessionId: id, workspaceCwd: root } } + } +} + +it('creates from the host hook path when Claude filename differs, then checks actual recorded cwd', async () => { + const transcriptPath = await file(join(root, 'projects', 'folder', 'different-uuid.jsonl'), [ + { type: 'user', uuid: 'first', sessionId: id, cwd: root, message: { role: 'user', content: 'hello' } }, + { type: 'assistant', uuid: 'reply', sessionId: id, cwd: '/later-drift', message: { role: 'assistant', content: 'reply' } } + ]) + const sourcePath = () => structuredAgentCliSourcePath({ + agent: 'claude', workspaceId: 'folder', resumeFrom: { providerSessionId: id, + cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } }, + rows: [{ paneKey: 'tab:leaf', worktreeId: 'folder', agentType: 'claude', state: 'waiting', + connectionId: null, receivedAt: 1, stateStartedAt: 1, + providerSession: { key: 'session_id', id, transcriptPath } }] + }) + const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! + const find = vi.spyOn(importer, 'findTranscript') + const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ + host: null, settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selfSessionId: 'new-chat', selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, + launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: sourcePath + }) + expect(adoption.transcriptPath).toBe(transcriptPath) + expect(find).not.toHaveBeenCalled() + expect(await prepareAdoptedTranscript(params('claude', adoption.transcriptPath))).toMatchObject({ ok: true }) + const wrongDirectory = params('claude', adoption.transcriptPath) + if (wrongDirectory.adopt?.source) wrongDirectory.adopt.source.workspaceCwd = '/another-folder' + expect(await prepareAdoptedTranscript(wrongDirectory)).toMatchObject({ ok: false, + refusal: { details: { reason: 'transcriptUnreadable' } } }) + + const foreign = await file(join(root, 'foreign.jsonl'), []) + const escaped = process.platform === 'win32' ? foreign : join(root, 'projects', 'escaped.jsonl') + if (process.platform !== 'win32') await symlink(foreign, escaped) + await expect(resolveStructuredAgentSessionAdoptionForCreate({ + host: null, settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selfSessionId: 'another-chat', selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, + launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: () => escaped + })).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) + expect(find).not.toHaveBeenCalled() +}) + +it('checks canonical provider metadata during the existing import, including Codex copied parent metadata', async () => { + const codex = await file(join(root, 'rollout.jsonl'), [ + { type: 'session_meta', payload: { id } }, + { type: 'session_meta', payload: { id: 'copied-parent' } }, + { type: 'response_item', payload: { type: 'message', role: 'user', content: 'hello' } } + ]) + expect(await prepareAdoptedTranscript(params('codex', codex))).toMatchObject({ ok: true }) + for (const agent of ['omp', 'pi'] as const) { + const transcript = await file(join(root, `${id}.jsonl`), [ + { type: 'session', id, cwd: root }, + { type: 'message', id: 'turn', message: { role: 'user', content: [{ type: 'text', text: 'hello' }] } } + ]) + expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: true }) + await file(transcript, [{ type: 'session', id: 'foreign', cwd: root }]) + expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: false }) + } + const grok = await file(join(root, id, 'chat_history.jsonl'), [{ type: 'user', content: 'hello' }]) + await file(join(root, id, 'summary.json'), [{ info: { id, cwd: root } }]) + expect(await prepareAdoptedTranscript(params('grok', grok))).toMatchObject({ ok: true }) + await rm(join(root, id, 'summary.json')) + expect(await prepareAdoptedTranscript(params('grok', grok))).toMatchObject({ ok: false, + refusal: { details: { reason: 'transcriptUnreadable' } } }) + await writeFile(codex, '{malformed json') + expect(await prepareLegacyTranscriptImport({ agent: 'codex', sessionId: id, + options: { filePath: codex, source: { providerSessionId: id, workspaceCwd: root } } })).toMatchObject({ ok: false }) +}) + +it('materializes legacy Codex into the system home and pins a verified selected account alias', async () => { + const legacy = join(root, 'legacy') + const system = join(root, 'system') + const selected = join(root, 'codex-accounts', 'selected', 'home') + const suffix = join('sessions', '2026', '10', '15', `rollout-stamp-${id}.jsonl`) + const transcriptPath = await file(join(legacy, suffix), [{ type: 'session_meta', payload: { id } }]) + vi.spyOn(codexHomes, 'getSystemCodexHomePath').mockReturnValue(system) + const source = { accountHome: { variable: 'CODEX_HOME' as const, path: legacy }, transcriptPath } + const migrated = await prepareCodexAdoption(source, id, + (args) => prepareLegacySharedCodexSessionResume(args, { + legacyCodexHomePath: legacy, systemCodexHomePath: system, isHostSystemDefaultRealHomeSelected: () => true + }), [source.accountHome]) + expect(migrated).toEqual({ accountHome: { variable: 'CODEX_HOME', path: system }, transcriptPath: join(system, suffix) }) + await file(join(selected, suffix), [{ type: 'session_meta', payload: { id } }]) + expect(await prepareCodexAdoption(migrated, id, async () => ({ useRealCodexHome: false, substituteCodexHome: selected }), + [{ variable: 'CODEX_HOME', path: selected }])).toEqual({ accountHome: { variable: 'CODEX_HOME', path: selected }, transcriptPath: join(selected, suffix) }) + await expect(prepareCodexAdoption(source, id, async () => { throw new Error('EACCES selected account') }, + [source.accountHome])).rejects.toThrow('EACCES selected account') +}) diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts b/src/main/native-chat/transcript-opencode-sqlite-query.test.ts index 6e500b7b9748..79d05fa69140 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts +++ b/src/main/native-chat/transcript-opencode-sqlite-query.test.ts @@ -503,8 +503,10 @@ describe('readOpenCodeTranscriptSignal', () => { insertPart(db, { id: 'prt-1', messageId: 'msg-1', time: 10, data: { type: 'text', text: 'a' } }) insertPart(db, { id: 'prt-2', messageId: 'msg-2', time: 20, data: { type: 'text', text: 'b' } }) + db.exec("ALTER TABLE session ADD COLUMN directory TEXT; UPDATE session SET directory = '/folder'") const signal = readOpenCodeTranscriptSignal(path, 'ses-1') expect(signal).toEqual({ + cwd: '/folder', messageCount: 2, partCount: 2, maxMessageRowId: 2, diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.ts b/src/main/native-chat/transcript-opencode-sqlite-query.ts index 99b1c0d1577b..603113b64c5a 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.ts +++ b/src/main/native-chat/transcript-opencode-sqlite-query.ts @@ -7,7 +7,8 @@ import { } from './transcript-opencode2-sqlite' import type { NativeChatMessage } from '../../shared/native-chat-types' import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' -import { extractString, parseJsonObject } from '../ai-vault/session-scanner-values' +import { columnExists } from '../opencode-usage/schema-helpers' +import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' import type SyncDatabase from '../sqlite/sync-database' type BindValue = SyncDatabase.BindValue @@ -31,6 +32,7 @@ export type OpenCodeTranscriptPage = { } export type OpenCodeTranscriptSignal = { + cwd?: string | null messageCount: number partCount: number maxMessageRowId: number @@ -112,7 +114,11 @@ export function readOpenCodeTranscriptSignal( sessionId, ...(agent === 'zcode' ? [sessionId] : []) ) + const source = columnExists(db, 'session', 'directory') + ? asRecord(db.prepare('SELECT directory FROM session WHERE id = ?').get(sessionId)) + : null return { + cwd: extractString(source?.directory), messageCount: messageRow?.message_count ?? 0, partCount: partRow?.part_count ?? 0, maxMessageRowId: messageRow?.max_message_rowid ?? 0, diff --git a/src/main/native-chat/transcript-opencode2-sqlite.test.ts b/src/main/native-chat/transcript-opencode2-sqlite.test.ts index df36bbc78a1e..9637aefbfe36 100644 --- a/src/main/native-chat/transcript-opencode2-sqlite.test.ts +++ b/src/main/native-chat/transcript-opencode2-sqlite.test.ts @@ -25,7 +25,9 @@ function fixture() { db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY); CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session');`) + INSERT INTO session_v2 VALUES ('session'); + ALTER TABLE session_v2 ADD COLUMN directory TEXT; + UPDATE session_v2 SET directory = '/folder';`) const insertMessage = db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)') let sequence = 0 const insert = (id: string, type: string, data: unknown, time = 1) => @@ -41,6 +43,7 @@ describe('OpenCode 2 native transcript', () => { insert('two', 'assistant', { content: [{ type: 'text', text: 'first reply' }] }) insert('three', 'user', { text: 'second prompt' }) insert('last-empty', 'idle', { outcome: 'succeeded' }) + expect(readOpenCodeTranscriptSignal(path, 'session')?.cwd).toBe('/folder') const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 2 }) expect(page?.items.map((item) => item.message.id)).toEqual(['opencode:two', 'opencode:three']) expect(page?.hasMore).toBe(true) diff --git a/src/main/native-chat/transcript-opencode2-sqlite.ts b/src/main/native-chat/transcript-opencode2-sqlite.ts index 1b4f01033e9c..4a4c5a490d1e 100644 --- a/src/main/native-chat/transcript-opencode2-sqlite.ts +++ b/src/main/native-chat/transcript-opencode2-sqlite.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto' import type SyncDatabase from '../sqlite/sync-database' import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' import { columnExists, tableExists } from '../opencode-usage/schema-helpers' -import { asRecord, parseJsonObject } from '../ai-vault/session-scanner-values' +import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' import { opencodeMessages, OPENCODE_TRANSCRIPT_MAX_ROW_BYTES @@ -48,7 +48,11 @@ export function readOpenCode2TranscriptSignal( ) { throw new Error('OpenCode transcript signal is invalid') } + const source = columnExists(db, 'session_v2', 'directory') + ? asRecord(db.prepare('SELECT directory FROM session_v2 WHERE id = ?').get(sessionId)) + : null return { + cwd: extractString(source?.directory), messageCount: row.count, partCount: 0, maxMessageRowId: row.latest, diff --git a/src/main/native-chat/transcript-path-admission.ts b/src/main/native-chat/transcript-path-admission.ts new file mode 100644 index 000000000000..3e2d6651edc1 --- /dev/null +++ b/src/main/native-chat/transcript-path-admission.ts @@ -0,0 +1,18 @@ +import { isAbsolute, relative, resolve } from 'node:path' +import { isDescendantOrEqual, normalizeExistingPath } from '../ipc/filesystem-path-containment' +import { isWslUncPath } from '../../shared/wsl-paths' +import { needsWslHostResolution } from './host-readable-transcript-path' + +/** Account containment must survive symlinks and host-native path translation. */ +export async function admitTranscriptPath(root: string, candidate: string) { + if (!isAbsolute(root) || !isAbsolute(candidate) || isWslUncPath(root) || + isWslUncPath(candidate) || needsWslHostResolution(candidate)) { + return null + } + const [canonicalRoot, canonicalCandidate] = await Promise.all([ + normalizeExistingPath(resolve(root)), normalizeExistingPath(resolve(candidate)) + ]) + return isDescendantOrEqual(canonicalCandidate, canonicalRoot) + ? { path: canonicalCandidate, relativePath: relative(canonicalRoot, canonicalCandidate) } + : null +} diff --git a/src/main/omp/omp-session-cwd-lookup.ts b/src/main/omp/omp-session-cwd-lookup.ts index 023fe67292e8..b5127333c83f 100644 --- a/src/main/omp/omp-session-cwd-lookup.ts +++ b/src/main/omp/omp-session-cwd-lookup.ts @@ -54,6 +54,7 @@ export async function findOmpSessionByCwd(input: { cwd: string homeDir: string env: NodeJS.ProcessEnv + strictErrors?: boolean }): Promise { const sessionId = input.sessionId.trim() if (!sessionId || !isAbsolute(input.cwd)) { @@ -80,7 +81,9 @@ export async function findOmpSessionByCwd(input: { return file } } - } catch { + } catch (error) { + if (input.strictErrors && !(error instanceof Error && 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR'))) throw error // A stale or unreadable bucket must not replace a missing history with a blank chat. } } diff --git a/src/main/omp/omp-transcript-import.ts b/src/main/omp/omp-transcript-import.ts index eb0c4ca1cd37..4e250f81d130 100644 --- a/src/main/omp/omp-transcript-import.ts +++ b/src/main/omp/omp-transcript-import.ts @@ -3,23 +3,29 @@ import { resolveOmpSessionsDir } from '../ai-vault/omp-session-root' import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-conversations' import { findOmpSessionByCwd } from './omp-session-cwd-lookup' +function sessionsRoot(accountHomePath: string, launchEnv: NodeJS.ProcessEnv) { + return resolveOmpSessionsDir({ + env: { ...launchEnv, PI_CODING_AGENT_DIR: accountHomePath }, + homeDir: (process.platform === 'win32' ? launchEnv.USERPROFILE : launchEnv.HOME) || homedir() + }) +} + export const OMP_TRANSCRIPT_IMPORT = directoryTranscriptImport({ + transcriptRoot: ({ accountHomePath, launchEnv }) => sessionsRoot(accountHomePath, launchEnv), accountHomeCandidates: ({ selectedAccountHomePath }) => [selectedAccountHomePath], // Where OMP itself keeps the account's sessions, which is not always under it (XDG_DATA_HOME). - findTranscript: async ({ providerSessionId, accountHomePath, launchEnv, workspaceCwd }) => { + findTranscript: async ({ providerSessionId, accountHomePath, launchEnv, workspaceCwd, strictErrors }) => { const homeDir = (process.platform === 'win32' ? launchEnv.USERPROFILE : launchEnv.HOME) || homedir() - const sessionsDir = resolveOmpSessionsDir({ - env: { ...launchEnv, PI_CODING_AGENT_DIR: accountHomePath }, - homeDir - }) + const sessionsDir = sessionsRoot(accountHomePath, launchEnv) return sessionsDir ? findOmpSessionByCwd({ sessionsDir, sessionId: providerSessionId, cwd: workspaceCwd, homeDir, - env: launchEnv + env: launchEnv, + strictErrors }) : null } diff --git a/src/main/opencode/opencode-transcript-import.ts b/src/main/opencode/opencode-transcript-import.ts index 359cef811c16..52fe1dec1182 100644 --- a/src/main/opencode/opencode-transcript-import.ts +++ b/src/main/opencode/opencode-transcript-import.ts @@ -1,4 +1,6 @@ -import { existsSync } from 'node:fs' +import { stat } from 'node:fs/promises' +import { admitTranscriptPath } from '../native-chat/transcript-path-admission' +import { dirname } from 'node:path' import { homedir } from 'node:os' import { isLegacyAgentSessionAccountHome } from '../../shared/agent-session-account-home' import { getManagedDataAccountService } from '../managed-data-accounts/service' @@ -6,7 +8,25 @@ import type { StructuredAgentTranscriptImport } from '../native-chat/structured- import { resolveOpenCodeDatabasePath } from './opencode-data-directory' import { environmentForStructuredOpenCodeAccountHome } from './opencode-structured-account-home' +function accountDatabase(accountHome: Parameters[0]['accountHome'], launchEnv: NodeJS.ProcessEnv) { + if (isLegacyAgentSessionAccountHome(accountHome)) return null + const env = environmentForStructuredOpenCodeAccountHome(accountHome, { + managedAccounts: getManagedDataAccountService(), baseEnvironment: launchEnv + }) + return resolveOpenCodeDatabasePath(env, + (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir()) +} + export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { + admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { + const dbPath = accountDatabase(accountHome, launchEnv) + if (!dbPath) return null + const [expected, actual] = await Promise.all([ + admitTranscriptPath(dirname(dbPath), dbPath), + admitTranscriptPath(dirname(dbPath), transcriptPath) + ]) + return expected && actual && expected.path === actual.path ? actual.path : null + }, // The selected account, then the unmanaged environment this chat would launch with. accountHomeCandidates: ({ selectedAccountHome }) => [ selectedAccountHome, @@ -14,19 +34,14 @@ export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { ], // The database the account's OpenCode opens, which is the only one its chat can load from. findTranscript: async ({ providerSessionId, accountHome, launchEnv }) => { - if (isLegacyAgentSessionAccountHome(accountHome)) { - return null - } - const env = environmentForStructuredOpenCodeAccountHome(accountHome, { - managedAccounts: getManagedDataAccountService(), - baseEnvironment: launchEnv - }) - const dbPath = resolveOpenCodeDatabasePath( - env, - (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir() - ) - if (!dbPath || !existsSync(dbPath)) { - return null + const dbPath = accountDatabase(accountHome, launchEnv) + if (!dbPath) return null + try { + if (!(await stat(dbPath)).isFile()) return null + } catch (error) { + if (error instanceof Error && 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return null + throw error } const { readOpenCodeTranscriptSignalViaWorker } = await import('../ai-vault/session-scanner-opencode-sqlite-worker-spawn') diff --git a/src/main/pi/pi-transcript-import.ts b/src/main/pi/pi-transcript-import.ts index d2db4dca167d..573d3b78fd9c 100644 --- a/src/main/pi/pi-transcript-import.ts +++ b/src/main/pi/pi-transcript-import.ts @@ -7,14 +7,16 @@ import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-c import { readPiSessionHeader } from './rpc-launch-resolution' export const PI_TRANSCRIPT_IMPORT = directoryTranscriptImport({ + transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), // Session History's host source is authoritative, including when the chat chose another home. accountHomeCandidates: () => [ process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), '.pi', 'agent') ], // The file Session History lists under this id. - findTranscript: async ({ providerSessionId }) => { + findTranscript: async ({ providerSessionId, strictErrors }) => { const files = await walkSessionFiles(piSessionHistorySessionsDir(), 'pi', [], { extensions: new Set(['.jsonl']), + strictErrors, filePredicate: (path) => sessionIdFromFileName(path) === providerSessionId }) if (files.length !== 1) { diff --git a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts index 6284c30602a1..2f0c4905cd74 100644 --- a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts +++ b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts @@ -1,3 +1,4 @@ +import { prepareAdoptedTranscript } from '../native-chat/agent-session-wire/structured-agent-session-adopted-import' import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -489,18 +490,18 @@ describe('adopting a conversation recorded outside Orca', () => { expect(intent.accountHome).toEqual({ variable: 'PI_CODING_AGENT_DIR', path: accountHome }) expect(intent.adopt).toEqual({ providerHandle: { transport: 'jsonl-rpc', agent: 'pi', nativeId: file }, - transcriptPath: file + transcriptPath: file, + source: { providerSessionId: '0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a', workspaceCwd: '/repos/workspace-1' } }) workspaceDirectory = '/different-folder' - await expect( - runtime.resolveStructuredAgentSessionCreateIntent({ + const refused = await runtime.resolveStructuredAgentSessionCreateIntent({ envelope: { sessionId: 'session-2', clientOperationId: 'operation-2' }, worktree: 'id:workspace-1', agent: 'pi', resumeFrom: { providerSessionId: '0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a' } }) - ).rejects.toMatchObject({ refusal: { code: 'agent_session_identity_required' } }) + expect(await prepareAdoptedTranscript(refused)).toMatchObject({ ok: false, refusal: { code: 'agent_session_identity_required' } }) } finally { vi.unstubAllEnvs() await rm(accountHome, { recursive: true, force: true }) diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index 8d8d54973aff..1cb1788e78ab 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -1,3 +1,5 @@ +import type { StructuredAgentSessionResumeSource } from '../../../shared/structured-agent-session-create' +import { structuredAgentCliSourcePath } from '../../native-chat/structured-agent-cli-source' import type { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce as RestoreStructuredAgentSessionTabsOnceMethods } from './structured-session-tab-restoration' import { agentSessionRefusalError } from '../../../shared/agent-session-wire-refusals' import { OrcaRuntimeWithGetWorktreePs } from '../workspaces/workspace-process-listing' @@ -27,7 +29,6 @@ import { import { parseWorkspaceKey } from '../../../shared/workspace-scope' import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' import type { StructuredAgentId } from '../../../shared/agent-session-provider-handle' -import { readPiSessionHeader, samePiDirectory } from '../../pi/rpc-launch-resolution' export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport extends OrcaRuntimeWithGetWorktreePs { protected abstract restoreStructuredAgentSessionTabsOnce( @@ -150,7 +151,7 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte worktree: string agent: StructuredAgentId callerKey?: string - resumeFrom?: { providerSessionId: string } + resumeFrom?: StructuredAgentSessionResumeSource }): Promise { if (input.resumeFrom) { requireUnownedStructuredAgentSessionAdoption({ @@ -202,7 +203,7 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte worktree: string agent: StructuredAgentId callerKey?: string - resumeFrom?: { providerSessionId: string } + resumeFrom?: StructuredAgentSessionResumeSource }, resolveAccountHome: (context: { launchEnv: NodeJS.ProcessEnv @@ -238,32 +239,30 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte if (committedReplay) { return committedReplay } + const resumeFrom = input.resumeFrom + const workspaceCwd = resumeFrom ? (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path : '' const selectedAccountHome = await resolveAccountHome({ launchEnv, location }) // Adopting pins the account home to wherever the conversation actually lives, which is not // necessarily the one a fresh create would pick: Codex resolves its rollout under // `accountHome.path`, and Claude reads its transcript under `/projects`. Resuming under // the wrong home finds nothing and lands the user in a blank chat wearing the old chat's name. const adoption = - input.resumeFrom && transcriptImport + resumeFrom && transcriptImport ? await resolveStructuredAgentSessionAdoptionForCreate({ settings, agent: input.agent, transcriptImport, - providerSessionId: input.resumeFrom.providerSessionId, + providerSessionId: resumeFrom.providerSessionId, + resolveTranscriptPath: () => structuredAgentCliSourcePath({ + agent: input.agent, resumeFrom, workspaceId: location.workspaceId, + rows: this.getAgentProviderSessionRows() + }), + prepareCodexResume: this.prepareAiVaultSessionResumeFn ?? undefined, selectedAccountHome, launchEnv: await resolveHostStructuredAgentLaunchEnvironment(input.agent, settings), - workspaceCwd: (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path + workspaceCwd: workspaceCwd }) : null - if (input.agent === 'pi' && adoption) { - const header = await readPiSessionHeader(adoption.transcriptPath) - const targetDirectory = (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path - if (!header || !(await samePiDirectory(header.cwd, targetDirectory))) { - throw agentSessionRefusalError('agent_session_identity_required', { - reason: 'transcriptNotFound' - }) - } - } return { envelope: { sessionId: input.envelope.sessionId, @@ -289,7 +288,11 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte ? adoption.transcriptPath : input.resumeFrom.providerSessionId }, - transcriptPath: adoption.transcriptPath + transcriptPath: adoption.transcriptPath, + source: { + providerSessionId: input.resumeFrom.providerSessionId, + workspaceCwd: workspaceCwd + } } } : {}), diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index d9a870f4b546..8c6ea56341a3 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -1,3 +1,7 @@ +import { stat } from 'node:fs/promises' +import { agentSessionRefusalError, isAgentSessionRefusalError } from '../../shared/agent-session-wire-refusals' +import { prepareCodexAdoption } from '../native-chat/codex-adoption-preparation' +import type { AiVaultSessionResumePreparation } from '../../shared/ai-vault-resume-preparation' import type { AgentSessionAccountHome } from '../../shared/agent-session-account-home' import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' @@ -86,12 +90,56 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { selectedAccountHome: AgentSessionAccountHome launchEnv: NodeJS.ProcessEnv workspaceCwd: string + resolveTranscriptPath?: () => string | undefined + prepareCodexResume?: AiVaultSessionResumePreparation }) { - return resolveStructuredAgentSessionAdoption({ - providerSessionId: input.providerSessionId, - candidateAccountHomes: input.transcriptImport.accountHomeCandidates(input), - resolveTranscript: input.transcriptImport.findTranscript, - launchEnv: input.launchEnv, - workspaceCwd: input.workspaceCwd - }) + try { + const transcriptPath = input.resolveTranscriptPath?.() + const candidates = input.transcriptImport.accountHomeCandidates(input) + const admitted = transcriptPath + ? await Promise.all(candidates.map(async (accountHome) => ({ + accountHome, + path: await input.transcriptImport.admitTranscriptPath({ + accountHome, transcriptPath, launchEnv: input.launchEnv + }) + }))) + : null + if (admitted && !admitted.some((candidate) => candidate.path)) { + throw new Error('The conversation account is not available on this host.') + } + const adoption = await resolveStructuredAgentSessionAdoption({ + providerSessionId: input.providerSessionId, + candidateAccountHomes: admitted + ? admitted.filter((candidate) => candidate.path).map((candidate) => candidate.accountHome) + : candidates, + resolveTranscript: async (args) => { + const exact = transcriptPath && await input.transcriptImport.admitTranscriptPath({ + ...args, transcriptPath + }) + if (exact) { + try { + if ((await stat(exact)).isFile()) return exact + } catch (error) { + if (!(error instanceof Error && 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR'))) throw error + } + } + const found = await input.transcriptImport.findTranscript({ ...args, strictErrors: true }) + if (!found) return null + const path = await input.transcriptImport.admitTranscriptPath({ ...args, transcriptPath: found }) + if (!path) throw new Error('The conversation path is outside its account storage.') + return path + }, + launchEnv: input.launchEnv, + workspaceCwd: input.workspaceCwd + }) + return input.agent === 'codex' + ? await prepareCodexAdoption(adoption, input.providerSessionId, input.prepareCodexResume, candidates) + : adoption + } catch (error) { + if (isAgentSessionRefusalError(error)) throw error + throw agentSessionRefusalError('agent_session_identity_required', + { reason: 'transcriptUnreadable' }, error instanceof Error ? error.message : String(error)) + } + } diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index e7bc4cb31e91..3d153cf32981 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -23,7 +23,8 @@ export { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY, PI_STRUCTURED_DIALOGS_RUNTIME_CAPABILITY, - STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY + STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY } from './structured-agent-session-surface-capabilities' import { AGENT_SESSION_ATTENTION_RUNTIME_CAPABILITIES } from './agent-session-attention-capabilities' export { diff --git a/src/shared/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts index 21a6c6821203..0fa504c3e549 100644 --- a/src/shared/rpc-contract/structured-agent-session-params.ts +++ b/src/shared/rpc-contract/structured-agent-session-params.ts @@ -116,7 +116,14 @@ export const AttachParams = z * the provider child launches against; both are derived host-side from this id instead. */ export const ResumeSource = z .object({ - providerSessionId: Identifier('Invalid provider session id') + providerSessionId: Identifier('Invalid provider session id'), + cliSource: z + .object({ + workspaceId: Identifier('Invalid workspace id'), + paneKey: Identifier('Invalid pane key') + }) + .strict() + .optional() }) .strict() diff --git a/src/shared/structured-agent-session-create.test.ts b/src/shared/structured-agent-session-create.test.ts index f83658659a12..b4aa2ca38963 100644 --- a/src/shared/structured-agent-session-create.test.ts +++ b/src/shared/structured-agent-session-create.test.ts @@ -1,3 +1,5 @@ +import { ResumeSource } from './rpc-contract/structured-agent-session-params' +import { STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY } from './structured-agent-session-surface-capabilities' import { describe, expect, it } from 'vitest' import { NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES, RUNTIME_CAPABILITIES } from './protocol-version' import { @@ -7,7 +9,8 @@ import { import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from './electron-remote-runtime-client-capabilities' import { structuredAgentSessionCreateParams, - type StructuredAgentSessionFirstMessage + type StructuredAgentSessionFirstMessage, + type StructuredAgentSessionResumeSource } from './structured-agent-session-create' import { structuredAgentSessionCreateFingerprint, @@ -26,7 +29,7 @@ function nextUuid(): string { function createParams( overrides: { - resumeFrom?: { providerSessionId: string } + resumeFrom?: StructuredAgentSessionResumeSource tabId?: string firstMessage?: StructuredAgentSessionFirstMessage options?: Record @@ -158,3 +161,17 @@ describe('the tab id a create reserves', () => { expect(AGENT_SESSION_CREATE_TAB_ID_RUNTIME_CAPABILITY).toBe('agentSession.create.tab-id.v1') }) }) + +it('negotiates a strict pane identity and includes it in the create fingerprint without accepting paths', () => { + const source = { providerSessionId: 'thread-abc', cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } } + expect(RUNTIME_CAPABILITIES).toContain(STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY) + expect(ResumeSource.parse(source)).toEqual(source) + expect(ResumeSource.safeParse({ ...source, transcriptPath: '/client/path' }).success).toBe(false) + expect(ResumeSource.safeParse({ ...source, cliSource: { ...source.cliSource, accountHome: '/client/home' } }).success).toBe(false) + const first = createParams({ resumeFrom: source }) + expect(first.envelope.payloadFingerprint).not.toBe(createParams({ resumeFrom: RESUME }).envelope.payloadFingerprint) + expect(first.envelope.payloadFingerprint).toBe(createParams({ resumeFrom: source }).envelope.payloadFingerprint) + expect(first.envelope.payloadFingerprint).not.toBe(createParams({ resumeFrom: { + ...source, cliSource: { ...source.cliSource, paneKey: 'other:leaf' } + } }).envelope.payloadFingerprint) +}) diff --git a/src/shared/structured-agent-session-create.ts b/src/shared/structured-agent-session-create.ts index c4ef6fb40c5b..d1e4e23e1610 100644 --- a/src/shared/structured-agent-session-create.ts +++ b/src/shared/structured-agent-session-create.ts @@ -18,6 +18,8 @@ import { export type StructuredAgentSessionResumeSource = { /** claude: the session id. codex: the thread id. */ providerSessionId: string + /** Host-owned pane evidence; send only with the CLI-source create capability. */ + cliSource?: { workspaceId: string; paneKey: string } } export type StructuredAgentSessionCreateParams = { diff --git a/src/shared/structured-agent-session-mutation.ts b/src/shared/structured-agent-session-mutation.ts index 9b20c9b170e3..6a0237ce272e 100644 --- a/src/shared/structured-agent-session-mutation.ts +++ b/src/shared/structured-agent-session-mutation.ts @@ -1,5 +1,5 @@ import { sha256 } from './sha256' -import type { StructuredAgentSessionFirstMessage } from './structured-agent-session-create' +import type { StructuredAgentSessionFirstMessage, StructuredAgentSessionResumeSource } from './structured-agent-session-create' import type { StructuredAgentId } from './agent-session-provider-handle' function canonicalize(value: unknown): string { @@ -44,7 +44,7 @@ export function structuredAgentSessionCreateFingerprint(input: { sessionId: string worktree: string agent: StructuredAgentId - resumeFrom?: { providerSessionId: string } + resumeFrom?: StructuredAgentSessionResumeSource tabId?: string firstMessage?: StructuredAgentSessionFirstMessage options?: Readonly> diff --git a/src/shared/structured-agent-session-surface-capabilities.ts b/src/shared/structured-agent-session-surface-capabilities.ts index 4aba07206f7c..d8bdf74c27d3 100644 --- a/src/shared/structured-agent-session-surface-capabilities.ts +++ b/src/shared/structured-agent-session-surface-capabilities.ts @@ -32,11 +32,16 @@ export const STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY = export const AGENT_SESSION_MODEL_CATALOG_SAVED_ONLY_RUNTIME_CAPABILITY = 'agent-session.model-catalog.saved-only.v1' as const +/** Strict create source identity is sent only after host negotiation. */ +export const STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY = + 'agent-session.structured.cli-source.v1' as const + export const STRUCTURED_AGENT_SESSION_SURFACE_RUNTIME_CAPABILITIES = [ STRUCTURED_AGENT_SESSION_HOLD_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY, PI_STRUCTURED_DIALOGS_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY, AGENT_SESSION_MODEL_CATALOG_SAVED_ONLY_RUNTIME_CAPABILITY ] as const From 1a2a3f760f127b8e202be4e32b53799b3c2dd2d8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:00:32 -0700 Subject: [PATCH 09/38] fix(native-chat): satisfy source admission lint checks --- ...session-scanner-discovery-wsl-gate.test.ts | 12 +++-- .../adopted-transcript-source.ts | 35 +++++++++---- .../journal-legacy-import.ts | 4 +- .../native-chat/codex-adoption-preparation.ts | 50 ++++++++++++++----- src/main/native-chat/session-file-resolver.ts | 4 +- .../structured-agent-cli-conversations.ts | 4 +- .../structured-agent-cli-source.ts | 42 +++++++++++----- ...red-agent-session-source-admission.test.ts | 10 ++-- .../transcript-opencode-sqlite-query.ts | 30 ++++------- .../native-chat/transcript-path-admission.ts | 12 +++-- src/main/omp/omp-session-cwd-lookup.ts | 12 ++++- .../opencode/opencode-transcript-import.ts | 39 +++++++++++---- ...tructured-agent-session-create-adoption.ts | 20 ++++++-- 13 files changed, 190 insertions(+), 84 deletions(-) diff --git a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts index 313ee76a5616..dcbda1113a7a 100644 --- a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts +++ b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts @@ -153,10 +153,14 @@ it('execution admission preserves native access errors while confirmed missing r for (const code of ['EACCES', 'ENOENT']) { const failure = Object.assign(new Error(code), { code }) const search = walkSessionFiles('/account/sessions', 'codex', [], { - extensions: new Set(['.jsonl']), strictErrors: true, - readDirectory: async () => { throw failure } + extensions: new Set(['.jsonl']), + strictErrors: true, + readDirectory: async () => { + throw failure + } }) - if (code === 'ENOENT') await expect(search).resolves.toEqual([]) - else await expect(search).rejects.toBe(failure) + await (code === 'ENOENT' + ? expect(search).resolves.toEqual([]) + : expect(search).rejects.toBe(failure)) } }) diff --git a/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts index 7950e2e13725..bf0aa5cb8598 100644 --- a/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts +++ b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts @@ -1,5 +1,5 @@ -import { sessionIdFromFileName } from '../../ai-vault/session-scanner-accumulator' import { dirname, join } from 'node:path' +import { sessionIdFromFileName } from '../../ai-vault/session-scanner-accumulator' import type { AgentType } from '../../../shared/agent-status-types' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader' @@ -18,8 +18,12 @@ export function assertAdoptedSourceIdentity( if (actual.sessionId !== source.providerSessionId) { throw new Error('The saved conversation does not match the requested provider identity.') } - if (requireCwd && (!actual.cwd || normalizeRuntimePathForComparison(actual.cwd.trim()) !== - normalizeRuntimePathForComparison(source.workspaceCwd.trim()))) { + if ( + requireCwd && + (!actual.cwd || + normalizeRuntimePathForComparison(actual.cwd.trim()) !== + normalizeRuntimePathForComparison(source.workspaceCwd.trim())) + ) { throw new Error('This conversation belongs to another directory.') } } @@ -31,8 +35,8 @@ export async function adoptedTranscriptSourceObserver(input: { source: AdoptedTranscriptSource maxSourceBytes: number }) { - let sessionId: string | null = input.agent === 'claude' || input.agent === 'codex' - ? sessionIdFromFileName(input.filePath) : null + let sessionId: string | null = + input.agent === 'claude' || input.agent === 'codex' ? sessionIdFromFileName(input.filePath) : null let cwd: string | null = null let sawCodexMetadata = false if (input.agent === 'grok') { @@ -40,7 +44,9 @@ export async function adoptedTranscriptSourceObserver(input: { if (!(await admitTranscriptPath(dirname(input.filePath), summaryPath))) { throw new Error('The conversation summary is outside its storage directory.') } - const { buffer } = await readNodeFileWithinLimit(summaryPath, input.maxSourceBytes, { regularFileOnly: true }) + const { buffer } = await readNodeFileWithinLimit(summaryPath, input.maxSourceBytes, { + regularFileOnly: true + }) const summary = asRecord(asRecord(JSON.parse(buffer.toString('utf8')))?.info) sessionId = extractString(summary?.id) ?? sessionIdFromFileName(dirname(input.filePath)) cwd = extractString(summary?.cwd) @@ -48,7 +54,9 @@ export async function adoptedTranscriptSourceObserver(input: { return { observe(line: string) { const record = parseJsonObject(line) - if (!record) return + if (!record) { + return + } if (input.agent === 'claude') { sessionId = extractString(record.sessionId) ?? sessionId cwd ??= extractString(record.cwd) @@ -65,7 +73,7 @@ export async function adoptedTranscriptSourceObserver(input: { if (input.agent === 'pi' && sessionIdFromFileName(input.filePath) !== sessionId) { throw new Error('The saved conversation header does not match its file identity.') } - if (input.agent === 'pi' && cwd && await samePiDirectory(cwd, input.source.workspaceCwd)) { + if (input.agent === 'pi' && cwd && (await samePiDirectory(cwd, input.source.workspaceCwd))) { cwd = input.source.workspaceCwd } assertAdoptedSourceIdentity(input.source, { sessionId, cwd }, input.agent !== 'codex') @@ -74,10 +82,15 @@ export async function adoptedTranscriptSourceObserver(input: { } export async function validateAdoptedOpenCodeSource( - dbPath: string, source: AdoptedTranscriptSource + dbPath: string, + source: AdoptedTranscriptSource ): Promise { - const signal = await readOpenCodeTranscriptSignalViaWorker({ dbPath, sessionId: source.providerSessionId }) + const signal = await readOpenCodeTranscriptSignalViaWorker({ + dbPath, + sessionId: source.providerSessionId + }) assertAdoptedSourceIdentity(source, { - sessionId: signal ? source.providerSessionId : null, cwd: signal?.cwd ?? null + sessionId: signal ? source.providerSessionId : null, + cwd: signal?.cwd ?? null }) } diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index dcbde8dccf03..045d617a6f20 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -152,7 +152,9 @@ async function prepareOpenCodeImport(input: { }): Promise<{ ok: true; items: JournalReplacementItem[] } | { ok: false; error: string }> { const dbPath = input.options?.filePath if (input.options?.source) { - if (!dbPath) return { ok: false, error: 'The conversation database is unavailable.' } + if (!dbPath) { + return { ok: false, error: 'The conversation database is unavailable.' } + } try { await validateAdoptedOpenCodeSource(dbPath, input.options.source) } catch (error) { diff --git a/src/main/native-chat/codex-adoption-preparation.ts b/src/main/native-chat/codex-adoption-preparation.ts index 45a11ce330a0..0d903129e86d 100644 --- a/src/main/native-chat/codex-adoption-preparation.ts +++ b/src/main/native-chat/codex-adoption-preparation.ts @@ -1,6 +1,9 @@ import { stat } from 'node:fs/promises' import { join } from 'node:path' -import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome } from '../../shared/agent-session-account-home' +import { + isLegacyAgentSessionAccountHome, + type AgentSessionAccountHome +} from '../../shared/agent-session-account-home' import type { AiVaultSessionResumePreparation } from '../../shared/ai-vault-resume-preparation' import { getSystemCodexHomePath } from '../codex/codex-home-paths' import type { StructuredAgentSessionAdoption } from './structured-agent-session-history-adoption' @@ -14,22 +17,45 @@ export async function prepareCodexAdoption( prepare: AiVaultSessionResumePreparation | undefined, recognizedHomes: readonly AgentSessionAccountHome[] ): Promise { - if (!prepare || !isLegacyAgentSessionAccountHome(source.accountHome)) return source + if (!prepare || !isLegacyAgentSessionAccountHome(source.accountHome)) { + return source + } const result = await prepare({ - agent: 'codex', sessionId: providerSessionId, filePath: source.transcriptPath, - codexHome: source.accountHome.path, executionHostId: 'local' + agent: 'codex', + sessionId: providerSessionId, + filePath: source.transcriptPath, + codexHome: source.accountHome.path, + executionHostId: 'local' }) const home = result.useRealCodexHome ? getSystemCodexHomePath() : result.substituteCodexHome - if (!home || normalizeRuntimePathForComparison(home) === - normalizeRuntimePathForComparison(source.accountHome.path)) return source - if (!result.useRealCodexHome && !recognizedHomes.some((candidate) => - isLegacyAgentSessionAccountHome(candidate) && normalizeRuntimePathForComparison(candidate.path) === - normalizeRuntimePathForComparison(home))) { + if ( + !home || + normalizeRuntimePathForComparison(home) === + normalizeRuntimePathForComparison(source.accountHome.path) + ) { + return source + } + if ( + !result.useRealCodexHome && + !recognizedHomes.some( + (candidate) => + isLegacyAgentSessionAccountHome(candidate) && + normalizeRuntimePathForComparison(candidate.path) === normalizeRuntimePathForComparison(home) + ) + ) { throw new Error('The prepared conversation account is not recognized on this host.') } - const original = await admitTranscriptPath(join(source.accountHome.path, 'sessions'), source.transcriptPath) - if (!original?.relativePath) throw new Error('The conversation path could not be verified.') - const prepared = await admitTranscriptPath(join(home, 'sessions'), join(home, 'sessions', original.relativePath)) + const original = await admitTranscriptPath( + join(source.accountHome.path, 'sessions'), + source.transcriptPath + ) + if (!original?.relativePath) { + throw new Error('The conversation path could not be verified.') + } + const prepared = await admitTranscriptPath( + join(home, 'sessions'), + join(home, 'sessions', original.relativePath) + ) if (!prepared || !(await stat(prepared.path)).isFile()) { throw new Error('The prepared conversation history is unavailable.') } diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 72d31536045e..49d4ab5869e6 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -263,7 +263,9 @@ async function findFirstInDirs( } catch (error) { // A caller abort that races the refusal stays authoritative. signal?.throwIfAborted() - if (strictErrors) throw error + if (strictErrors) { + throw error + } // Why: one stalled distro must not hide another root's hit. unavailable = wslTranscriptFsRefusal(error) } diff --git a/src/main/native-chat/structured-agent-cli-conversations.ts b/src/main/native-chat/structured-agent-cli-conversations.ts index 8e93b27eb823..0c9bb3c67a33 100644 --- a/src/main/native-chat/structured-agent-cli-conversations.ts +++ b/src/main/native-chat/structured-agent-cli-conversations.ts @@ -60,7 +60,9 @@ export function directoryTranscriptImport(directories: { }): StructuredAgentTranscriptImport { return { admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { - if (!isLegacyAgentSessionAccountHome(accountHome)) return null + if (!isLegacyAgentSessionAccountHome(accountHome)) { + return null + } const root = directories.transcriptRoot({ accountHomePath: accountHome.path, launchEnv }) return root ? (await admitTranscriptPath(root, transcriptPath))?.path ?? null : null }, diff --git a/src/main/native-chat/structured-agent-cli-source.ts b/src/main/native-chat/structured-agent-cli-source.ts index affaa15862fb..0601327368ad 100644 --- a/src/main/native-chat/structured-agent-cli-source.ts +++ b/src/main/native-chat/structured-agent-cli-source.ts @@ -2,7 +2,10 @@ import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' import type { StructuredAgentSessionResumeSource } from '../../shared/structured-agent-session-create' import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' import { agentSessionRefusalError } from '../../shared/agent-session-wire-refusals' -import { adoptsCliConversations, CLI_CONVERSATION_ADOPTING_AGENTS } from '../../shared/structured-agent-cli-conversation-adoption' +import { + adoptsCliConversations, + CLI_CONVERSATION_ADOPTING_AGENTS +} from '../../shared/structured-agent-cli-conversation-adoption' import { isWslUncPath } from '../../shared/wsl-paths' import { needsWslHostResolution } from './host-readable-transcript-path' import { parseSshTranscriptPath } from './ssh-transcript-path' @@ -15,20 +18,35 @@ export function structuredAgentCliSourcePath(input: { rows: readonly AgentStatusIpcPayload[] }): string | undefined { const source = input.resumeFrom.cliSource - if (!source) return undefined - const row = input.rows.find((candidate) => - source.workspaceId === input.workspaceId && candidate.worktreeId === source.workspaceId && - candidate.paneKey === source.paneKey && !candidate.connectionId && !candidate.structuredHost && - adoptsCliConversations(candidate.agentType) && - CLI_CONVERSATION_ADOPTING_AGENTS[candidate.agentType] === input.agent && - candidate.providerSession?.id === input.resumeFrom.providerSessionId) + if (!source) { + return undefined + } + const row = input.rows.find( + (candidate) => + source.workspaceId === input.workspaceId && + candidate.worktreeId === source.workspaceId && + candidate.paneKey === source.paneKey && + !candidate.connectionId && + !candidate.structuredHost && + adoptsCliConversations(candidate.agentType) && + CLI_CONVERSATION_ADOPTING_AGENTS[candidate.agentType] === input.agent && + candidate.providerSession?.id === input.resumeFrom.providerSessionId + ) if (!row) { - throw agentSessionRefusalError('agent_session_identity_required', - { reason: 'transcriptUnreadable' }, 'The source conversation is no longer available.') + throw agentSessionRefusalError( + 'agent_session_identity_required', + { reason: 'transcriptUnreadable' }, + 'The source conversation is no longer available.' + ) } const path = row.providerSession?.transcriptPath?.trim() - if (path && (isWslUncPath(path) || needsWslHostResolution(path) || parseSshTranscriptPath(path))) { - throw agentSessionRefusalError('structured_agent_session_unsupported', { reason: 'hostUnsupported' }) + if ( + path && + (isWslUncPath(path) || needsWslHostResolution(path) || parseSshTranscriptPath(path)) + ) { + throw agentSessionRefusalError('structured_agent_session_unsupported', { + reason: 'hostUnsupported' + }) } return path || undefined } diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index a301674d297e..138592fe3eda 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -19,7 +19,7 @@ afterEach(async () => { vi.restoreAllMocks(); await rm(root, { recursive: true, const id = 'provider-session' async function file(path: string, records: unknown[]) { await mkdir(dirname(path), { recursive: true }) - await writeFile(path, records.map((record) => JSON.stringify(record)).join('\n') + '\n') + await writeFile(path, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`) return path } function params(agent: StructuredAgentId, transcriptPath: string): AgentSessionAttachParams { @@ -55,13 +55,17 @@ it('creates from the host hook path when Claude filename differs, then checks ac expect(find).not.toHaveBeenCalled() expect(await prepareAdoptedTranscript(params('claude', adoption.transcriptPath))).toMatchObject({ ok: true }) const wrongDirectory = params('claude', adoption.transcriptPath) - if (wrongDirectory.adopt?.source) wrongDirectory.adopt.source.workspaceCwd = '/another-folder' + if (wrongDirectory.adopt?.source) { + wrongDirectory.adopt.source.workspaceCwd = '/another-folder' + } expect(await prepareAdoptedTranscript(wrongDirectory)).toMatchObject({ ok: false, refusal: { details: { reason: 'transcriptUnreadable' } } }) const foreign = await file(join(root, 'foreign.jsonl'), []) const escaped = process.platform === 'win32' ? foreign : join(root, 'projects', 'escaped.jsonl') - if (process.platform !== 'win32') await symlink(foreign, escaped) + if (process.platform !== 'win32') { + await symlink(foreign, escaped) + } await expect(resolveStructuredAgentSessionAdoptionForCreate({ host: null, settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, selfSessionId: 'another-chat', selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.ts b/src/main/native-chat/transcript-opencode-sqlite-query.ts index 603113b64c5a..3f2072166985 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.ts +++ b/src/main/native-chat/transcript-opencode-sqlite-query.ts @@ -7,7 +7,7 @@ import { } from './transcript-opencode2-sqlite' import type { NativeChatMessage } from '../../shared/native-chat-types' import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' -import { columnExists } from '../opencode-usage/schema-helpers' +import { columnExists, tableExists } from '../opencode-usage/schema-helpers' import { asRecord, extractString, parseJsonObject } from '../ai-vault/session-scanner-values' import type SyncDatabase from '../sqlite/sync-database' @@ -42,10 +42,10 @@ export type OpenCodeTranscriptSignal = { const PART_ID_BATCH = 100 function sessionExists(db: SyncDatabase, sessionId: string): boolean { - const table = rowsOf<{ name: string }>( - db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'") + return ( + tableExists(db, 'session') && + db.prepare('SELECT 1 FROM session WHERE id = ?').get(sessionId) != null ) - return table.length > 0 && db.prepare('SELECT 1 FROM session WHERE id = ?').get(sessionId) != null } function rowsOf(statement: SqliteStatement, ...params: BindValue[]): T[] { @@ -114,11 +114,12 @@ export function readOpenCodeTranscriptSignal( sessionId, ...(agent === 'zcode' ? [sessionId] : []) ) - const source = columnExists(db, 'session', 'directory') - ? asRecord(db.prepare('SELECT directory FROM session WHERE id = ?').get(sessionId)) - : null return { - cwd: extractString(source?.directory), + cwd: columnExists(db, 'session', 'directory') + ? extractString( + asRecord(db.prepare('SELECT directory FROM session WHERE id = ?').get(sessionId))?.directory + ) + : null, messageCount: messageRow?.message_count ?? 0, partCount: partRow?.part_count ?? 0, maxMessageRowId: messageRow?.max_message_rowid ?? 0, @@ -302,10 +303,11 @@ function mapMessageRows( ? [{ message_id: row.id, time_updated: row.time_updated, data: null }] : partList ) + const updated = partList.reduce((max, row) => (row.time_updated > max ? row.time_updated : max), 0) for (const message of messages.toReversed()) { items.push({ rowid: row.message_rowid, - fingerprint: `${row.time_updated}:${partList.length}:${maxPartTimeUpdated(partList)}`, + fingerprint: `${row.time_updated}:${partList.length}:${updated}`, message: { ...message, transcriptOffset: row.message_rowid, @@ -316,13 +318,3 @@ function mapMessageRows( } return items } - -function maxPartTimeUpdated(partRows: PartRow[]): number { - let max = 0 - for (const partRow of partRows) { - if (partRow.time_updated > max) { - max = partRow.time_updated - } - } - return max -} diff --git a/src/main/native-chat/transcript-path-admission.ts b/src/main/native-chat/transcript-path-admission.ts index 3e2d6651edc1..2e7d2b36bf6f 100644 --- a/src/main/native-chat/transcript-path-admission.ts +++ b/src/main/native-chat/transcript-path-admission.ts @@ -5,12 +5,18 @@ import { needsWslHostResolution } from './host-readable-transcript-path' /** Account containment must survive symlinks and host-native path translation. */ export async function admitTranscriptPath(root: string, candidate: string) { - if (!isAbsolute(root) || !isAbsolute(candidate) || isWslUncPath(root) || - isWslUncPath(candidate) || needsWslHostResolution(candidate)) { + if ( + !isAbsolute(root) || + !isAbsolute(candidate) || + isWslUncPath(root) || + isWslUncPath(candidate) || + needsWslHostResolution(candidate) + ) { return null } const [canonicalRoot, canonicalCandidate] = await Promise.all([ - normalizeExistingPath(resolve(root)), normalizeExistingPath(resolve(candidate)) + normalizeExistingPath(resolve(root)), + normalizeExistingPath(resolve(candidate)) ]) return isDescendantOrEqual(canonicalCandidate, canonicalRoot) ? { path: canonicalCandidate, relativePath: relative(canonicalRoot, canonicalCandidate) } diff --git a/src/main/omp/omp-session-cwd-lookup.ts b/src/main/omp/omp-session-cwd-lookup.ts index b5127333c83f..18fd11b3c968 100644 --- a/src/main/omp/omp-session-cwd-lookup.ts +++ b/src/main/omp/omp-session-cwd-lookup.ts @@ -82,8 +82,16 @@ export async function findOmpSessionByCwd(input: { } } } catch (error) { - if (input.strictErrors && !(error instanceof Error && 'code' in error && - (error.code === 'ENOENT' || error.code === 'ENOTDIR'))) throw error + if ( + input.strictErrors && + !( + error instanceof Error && + 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR') + ) + ) { + throw error + } // A stale or unreadable bucket must not replace a missing history with a blank chat. } } diff --git a/src/main/opencode/opencode-transcript-import.ts b/src/main/opencode/opencode-transcript-import.ts index 52fe1dec1182..2e43b963ce1a 100644 --- a/src/main/opencode/opencode-transcript-import.ts +++ b/src/main/opencode/opencode-transcript-import.ts @@ -8,19 +8,29 @@ import type { StructuredAgentTranscriptImport } from '../native-chat/structured- import { resolveOpenCodeDatabasePath } from './opencode-data-directory' import { environmentForStructuredOpenCodeAccountHome } from './opencode-structured-account-home' -function accountDatabase(accountHome: Parameters[0]['accountHome'], launchEnv: NodeJS.ProcessEnv) { - if (isLegacyAgentSessionAccountHome(accountHome)) return null +function accountDatabase( + accountHome: Parameters[0]['accountHome'], + launchEnv: NodeJS.ProcessEnv +) { + if (isLegacyAgentSessionAccountHome(accountHome)) { + return null + } const env = environmentForStructuredOpenCodeAccountHome(accountHome, { - managedAccounts: getManagedDataAccountService(), baseEnvironment: launchEnv + managedAccounts: getManagedDataAccountService(), + baseEnvironment: launchEnv }) - return resolveOpenCodeDatabasePath(env, - (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir()) + return resolveOpenCodeDatabasePath( + env, + (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir() + ) } export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { const dbPath = accountDatabase(accountHome, launchEnv) - if (!dbPath) return null + if (!dbPath) { + return null + } const [expected, actual] = await Promise.all([ admitTranscriptPath(dirname(dbPath), dbPath), admitTranscriptPath(dirname(dbPath), transcriptPath) @@ -35,12 +45,21 @@ export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { // The database the account's OpenCode opens, which is the only one its chat can load from. findTranscript: async ({ providerSessionId, accountHome, launchEnv }) => { const dbPath = accountDatabase(accountHome, launchEnv) - if (!dbPath) return null + if (!dbPath) { + return null + } try { - if (!(await stat(dbPath)).isFile()) return null + if (!(await stat(dbPath)).isFile()) { + return null + } } catch (error) { - if (error instanceof Error && 'code' in error && - (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return null + if ( + error instanceof Error && + 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR') + ) { + return null + } throw error } const { readOpenCodeTranscriptSignalViaWorker } = diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index 8c6ea56341a3..27635f110a7f 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -118,16 +118,24 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { }) if (exact) { try { - if ((await stat(exact)).isFile()) return exact + if ((await stat(exact)).isFile()) { + return exact + } } catch (error) { if (!(error instanceof Error && 'code' in error && - (error.code === 'ENOENT' || error.code === 'ENOTDIR'))) throw error + (error.code === 'ENOENT' || error.code === 'ENOTDIR'))) { + throw error + } } } const found = await input.transcriptImport.findTranscript({ ...args, strictErrors: true }) - if (!found) return null + if (!found) { + return null + } const path = await input.transcriptImport.admitTranscriptPath({ ...args, transcriptPath: found }) - if (!path) throw new Error('The conversation path is outside its account storage.') + if (!path) { + throw new Error('The conversation path is outside its account storage.') + } return path }, launchEnv: input.launchEnv, @@ -137,7 +145,9 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { ? await prepareCodexAdoption(adoption, input.providerSessionId, input.prepareCodexResume, candidates) : adoption } catch (error) { - if (isAgentSessionRefusalError(error)) throw error + if (isAgentSessionRefusalError(error)) { + throw error + } throw agentSessionRefusalError('agent_session_identity_required', { reason: 'transcriptUnreadable' }, error instanceof Error ? error.message : String(error)) } From eec3ff8944d95e96ad9eaee3de570001bd6bf5eb Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:20:03 -0700 Subject: [PATCH 10/38] test(native-chat): provide the waiting hook prompt --- .../structured-agent-session-source-admission.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index 138592fe3eda..228609286483 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -40,7 +40,7 @@ it('creates from the host hook path when Claude filename differs, then checks ac const sourcePath = () => structuredAgentCliSourcePath({ agent: 'claude', workspaceId: 'folder', resumeFrom: { providerSessionId: id, cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } }, - rows: [{ paneKey: 'tab:leaf', worktreeId: 'folder', agentType: 'claude', state: 'waiting', + rows: [{ paneKey: 'tab:leaf', worktreeId: 'folder', agentType: 'claude', state: 'waiting', prompt: '', connectionId: null, receivedAt: 1, stateStartedAt: 1, providerSession: { key: 'session_id', id, transcriptPath } }] }) From 8fbcdac794b0491d5b4c202f9d39bd8ce2c2b418 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:53:24 -0700 Subject: [PATCH 11/38] test(native-chat): isolate source admission fixtures from host homes --- ...ructured-agent-cli-conversation-adoption.test.ts | 7 +++++++ ...tructured-agent-session-source-admission.test.ts | 13 ++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts index d93743961005..430aa129fbb2 100644 --- a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts +++ b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts @@ -21,6 +21,7 @@ import { writeOpenCodeSqliteDatabase } from '../ai-vault/session-scanner-opencod import { resolveAcpLaunchInvocation } from '../acp/acp-structured-launch-resolution' import { acpLaunchSpecFor } from '../acp/acp-launch-specs' import { resolveOpenCodeDatabasePath } from '../opencode/opencode-data-directory' +import * as hostReadableTranscriptPath from './host-readable-transcript-path' // The OpenCode reader's worker, run in process. vi.mock('../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (importOriginal) => { @@ -288,6 +289,12 @@ it.each(['win32', 'linux', 'darwin'] as const)( join(userProfile, '.omp', 'profiles', profile, 'agent'), 'USERPROFILE' ) + const nativePlatform = process.platform + const needsWslResolution = hostReadableTranscriptPath.needsWslHostResolution + // Simulated home precedence still reads fixture paths native to the actual host. + vi.spyOn(hostReadableTranscriptPath, 'needsWslHostResolution').mockImplementation((path) => + needsWslResolution(path, nativePlatform) + ) vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) const adoption = await adopt( diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index 228609286483..8481b7b2a2de 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' @@ -14,8 +14,15 @@ import { prepareLegacySharedCodexSessionResume } from '../codex/codex-legacy-ses import * as codexHomes from '../codex/codex-home-paths' let root: string -beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-source-admission-')) }) -afterEach(async () => { vi.restoreAllMocks(); await rm(root, { recursive: true, force: true }) }) +beforeEach(async () => { + root = await realpath(await mkdtemp(join(tmpdir(), 'orca-source-admission-'))) + vi.stubEnv('ORCA_USER_DATA_PATH', join(root, 'user-data')) +}) +afterEach(async () => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + await rm(root, { recursive: true, force: true }) +}) const id = 'provider-session' async function file(path: string, records: unknown[]) { await mkdir(dirname(path), { recursive: true }) From 11030261e501f64eb9f1d5b7185ff72a0770d86f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:09:42 -0700 Subject: [PATCH 12/38] test(native-chat): canonicalize adoption fixture directories --- ...ed-agent-cli-conversation-adoption.test.ts | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts index 430aa129fbb2..58bfd49eb208 100644 --- a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts +++ b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -39,6 +39,10 @@ vi.mock('../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (impor const SESSION_ID = '0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a' let root: string | null = null +async function createAdoptionTestDirectory(prefix: string): Promise { + return realpath(await mkdtemp(prefix)) +} + beforeEach(() => { // Grok and Pi also look where Session History lists them from; keep that off the real home. vi.stubEnv('GROK_HOME', join(tmpdir(), 'orca-adopt-no-grok-home')) @@ -169,7 +173,7 @@ describe('which chats can take over a CLI conversation', () => { it.each([false, true])( 'finds a Grok cwd beyond the generic cap (long path: %s)', async (longPath) => { - root = await mkdtemp(join(tmpdir(), 'orca-grok-adopt-cwd-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-grok-adopt-cwd-')) const workspaceCwd = join(root, longPath ? '中'.repeat(80) : 'workspace') const recorded = await RECORDED.grok(root, 'CURRENT-WORKSPACE') const group = grokEncodedCwdDirName(workspaceCwd) @@ -209,7 +213,7 @@ it.each([false, true])( ) it('looks up OMP history under the configured launch XDG and profile root', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-omp-adopt-env-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-env-')) const ambientData = join(root, 'ambient-data') const launchData = join(root, 'launch-data') const profile = 'work' @@ -245,7 +249,7 @@ it('looks up OMP history under the configured launch XDG and profile root', asyn }) it('uses the configured OMP profile when the ambient profile names another session', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-omp-adopt-profile-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-profile-')) const xdgData = join(root, 'data') const ambientProfile = 'ambient' const launchProfile = 'configured' @@ -280,7 +284,7 @@ it('uses the configured OMP profile when the ambient profile names another sessi it.each(['win32', 'linux', 'darwin'] as const)( 'follows the child home precedence for a named OMP profile on %s', async (platform) => { - root = await mkdtemp(join(tmpdir(), 'orca-omp-adopt-home-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-home-')) const home = join(root, 'home') const userProfile = join(root, 'user-profile') const profile = 'work' @@ -313,7 +317,7 @@ it.each(['win32', 'linux', 'darwin'] as const)( ) it('refuses OMP history from another workspace without creating a blank chat', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-omp-adopt-other-cwd-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-other-cwd-')) await RECORDED.omp(root, 'OTHER-WORKSPACE') await expect( adopt( @@ -330,7 +334,7 @@ it('refuses OMP history from another workspace without creating a blank chat', a describe.each(['grok', 'omp', 'pi'] as const)('adopting a %s CLI conversation', (agent) => { it('finds the conversation under the chat account and imports its history', async () => { - root = await mkdtemp(join(tmpdir(), `orca-${agent}-adopt-`)) + root = await createAdoptionTestDirectory(join(tmpdir(), `orca-${agent}-adopt-`)) const recorded = await RECORDED[agent](root, `ORCA-${agent}-ADOPT`) if (agent === 'pi') { vi.stubEnv('PI_CODING_AGENT_DIR', root) @@ -355,7 +359,7 @@ describe.each(['grok', 'omp', 'pi'] as const)('adopting a %s CLI conversation', }) it('refuses a conversation the account does not hold, rather than opening a blank chat', async () => { - root = await mkdtemp(join(tmpdir(), `orca-${agent}-adopt-missing-`)) + root = await createAdoptionTestDirectory(join(tmpdir(), `orca-${agent}-adopt-missing-`)) await expect( adopt(agent, { variable: ACCOUNT_VARIABLE[agent], path: root }) ).rejects.toMatchObject({ @@ -366,7 +370,7 @@ describe.each(['grok', 'omp', 'pi'] as const)('adopting a %s CLI conversation', describe('adopting a Pi CLI conversation', () => { it('pins the Session History account when another Pi home has the same id', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-pi-adopt-homes-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-pi-adopt-homes-')) const selected = join(root, 'selected') const history = join(root, 'history') await RECORDED.pi(selected, 'SELECTED') @@ -393,7 +397,7 @@ describe('adopting an OpenCode CLI conversation', () => { } it('imports from the configured database the resumed OpenCode child opens', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-opencode-configured-adopt-')) + root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-opencode-configured-adopt-')) const defaultDb = openCodeData(root) const configuredDb = join(root, 'data', 'opencode', 'work.db') writeOpenCodeSqliteDatabase(defaultDb, [ From 7cf362caf4f5b6f11e7c7564df91129445ea2eaa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:03:34 -0700 Subject: [PATCH 13/38] test(native-chat): preserve early ownership admission in source stack --- .../structured-agent-session-source-admission.test.ts | 8 ++++---- ...untime-structured-agent-session-create-intent.test.ts | 9 +++++++-- .../runtime/structured-agent-session-create-adoption.ts | 1 - 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index 8481b7b2a2de..0a485875f5a2 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -54,8 +54,8 @@ it('creates from the host hook path when Claude filename differs, then checks ac const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! const find = vi.spyOn(importer, 'findTranscript') const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ - host: null, settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, - selfSessionId: 'new-chat', selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, + settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: sourcePath }) expect(adoption.transcriptPath).toBe(transcriptPath) @@ -74,8 +74,8 @@ it('creates from the host hook path when Claude filename differs, then checks ac await symlink(foreign, escaped) } await expect(resolveStructuredAgentSessionAdoptionForCreate({ - host: null, settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, - selfSessionId: 'another-chat', selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, + settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: () => escaped })).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) expect(find).not.toHaveBeenCalled() diff --git a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts index 2f0c4905cd74..746341ead836 100644 --- a/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts +++ b/src/main/runtime/orca-runtime-structured-agent-session-create-intent.test.ts @@ -104,7 +104,7 @@ describe('structured Codex folder trust', () => { }) describe('structured agent-session create intent', () => { - it('returns the recorded owner before any new-launch support or account preparation', async () => { + it('returns the recorded owner before CLI source lookup, new-launch support or account preparation', async () => { const record = agentSessionRecordFixture() // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: early ownership admission only reads the host's record list. setStructuredAgentSessionHost({ @@ -114,12 +114,16 @@ describe('structured agent-session create intent', () => { const support = vi .spyOn(runtime, 'getStructuredAgentSessionCreateSupport') .mockRejectedValue(new Error('fresh launch is unavailable')) + const sourceRows = vi.spyOn(runtime, 'getAgentProviderSessionRows').mockImplementation(() => { + throw new Error('source is unavailable') + }) await expect( runtime.resolveStructuredAgentSessionCreateIntent({ envelope: { sessionId: 'new-chat', clientOperationId: 'operation-1' }, worktree: 'id:another-workspace', agent: 'claude', - resumeFrom: { providerSessionId: 'provider-session-alpha-1' } + resumeFrom: { providerSessionId: 'provider-session-alpha-1', + cliSource: { workspaceId: 'another-workspace', paneKey: 'missing-pane' } } }) ).rejects.toMatchObject({ refusal: { @@ -131,6 +135,7 @@ describe('structured agent-session create intent', () => { } }) expect(support).not.toHaveBeenCalled() + expect(sourceRows).not.toHaveBeenCalled() }) it('pins the selected Codex launch home after normal launch preparation', async () => { diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index 27635f110a7f..1346ad094001 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -151,5 +151,4 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { throw agentSessionRefusalError('agent_session_identity_required', { reason: 'transcriptUnreadable' }, error instanceof Error ? error.message : String(error)) } - } From de7b56603e6d0bb789a3832172a51c6427789d53 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:32:20 -0700 Subject: [PATCH 14/38] Resume CLI conversations directly in native chat --- .../AiVaultSessionSurfaceSwitchMenuItems.tsx | 10 +- .../tab-bar/CliChatResumeMenuItems.tsx | 37 +++ .../src/components/tab-bar/SortableTab.tsx | 10 +- .../tab-bar/SortableTabContextMenu.tsx | 6 + .../TabSessionSurfaceSwitchMenuItems.test.tsx | 69 +++--- .../TabSessionSurfaceSwitchMenuItems.tsx | 16 +- .../tab-bar/cli-chat-resume-feedback.ts | 62 +++++ .../tab-bar/cli-chat-resume-run.test.ts | 209 +++++++++++++++++ .../components/tab-bar/cli-chat-resume-run.ts | 140 ++++++++++++ .../tab-bar/cli-chat-resume-source.ts | 55 +++++ .../tab-session-history-switch.test.ts | 15 ++ .../tab-bar/tab-session-history-switch.ts | 3 +- .../use-sortable-tab-context-menu.test.ts | 18 ++ .../tab-bar/use-sortable-tab-context-menu.ts | 17 ++ .../TerminalPaneResumeInChatButton.test.tsx | 216 ++++-------------- .../TerminalPaneResumeInChatButton.tsx | 107 ++------- .../src/lib/ai-vault-tab-title-requests.ts | 11 +- .../lib/launch-structured-agent-session.ts | 1 + .../lib/structured-agent-launch-settlement.ts | 17 +- ...structured-agent-session-launch-callers.ts | 2 + ...ctured-agent-session-launch-create-call.ts | 8 + .../structured-agent-session-launch-errors.ts | 3 + .../lib/structured-agent-session-launch.ts | 11 +- ...tructured-agent-session-provisional-tab.ts | 84 ++++++- .../structured-agent-session-client.ts | 10 + 25 files changed, 811 insertions(+), 326 deletions(-) create mode 100644 src/renderer/src/components/tab-bar/CliChatResumeMenuItems.tsx create mode 100644 src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts create mode 100644 src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts create mode 100644 src/renderer/src/components/tab-bar/cli-chat-resume-run.ts create mode 100644 src/renderer/src/components/tab-bar/cli-chat-resume-source.ts create mode 100644 src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts create mode 100644 src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.ts diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionSurfaceSwitchMenuItems.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionSurfaceSwitchMenuItems.tsx index 74acfc2e07d4..98800405ddcb 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionSurfaceSwitchMenuItems.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionSurfaceSwitchMenuItems.tsx @@ -10,19 +10,25 @@ import { ResumeInNewCliTooltipText } from './ai-vault-session-cli-fork-copy' export function AiVaultSessionSurfaceSwitchMenuItems({ menuKind, tooltipSide, + chatPending, onResumeInNewChat, onResumeInNewCli }: { menuKind: 'dropdown' | 'context' tooltipSide: 'left' | 'right' - onResumeInNewChat?: () => void + chatPending?: boolean + onResumeInNewChat?: (event: Event) => void onResumeInNewCli?: () => void }): React.JSX.Element { const Item = menuKind === 'context' ? ContextMenuItem : DropdownMenuItem return ( <> {onResumeInNewChat ? ( - + {translate( 'auto.components.right.sidebar.AiVaultSessionRow.resumeInNewNativeChat', diff --git a/src/renderer/src/components/tab-bar/CliChatResumeMenuItems.tsx b/src/renderer/src/components/tab-bar/CliChatResumeMenuItems.tsx new file mode 100644 index 000000000000..e4461613c494 --- /dev/null +++ b/src/renderer/src/components/tab-bar/CliChatResumeMenuItems.tsx @@ -0,0 +1,37 @@ +import { useState } from 'react' +import { useAppStore } from '@/store' +import { DropdownMenuSeparator } from '@/components/ui/dropdown-menu' +import type { TerminalTab } from '../../../../shared/terminal-tab-types' +import { AiVaultSessionSurfaceSwitchMenuItems } from '../right-sidebar/AiVaultSessionSurfaceSwitchMenuItems' +import { resolveCliChatResumeSource } from './cli-chat-resume-source' +import { runCliChatResume, useCliChatResumePending } from './cli-chat-resume-run' + +export function CliChatResumeMenuItems({ + tab, + leadingSeparator, + onComplete +}: { + tab: Pick + leadingSeparator: boolean + onComplete?: () => void +}): React.JSX.Element | null { + const [source] = useState(() => resolveCliChatResumeSource(useAppStore.getState(), { tab })) + const pending = useCliChatResumePending(source) + if (!source) { + return null + } + return ( + <> + {leadingSeparator ? : null} + { + event.preventDefault() + void runCliChatResume(source).finally(() => onComplete?.()) + }} + /> + + ) +} diff --git a/src/renderer/src/components/tab-bar/SortableTab.tsx b/src/renderer/src/components/tab-bar/SortableTab.tsx index 1c5a9df5e4c4..8c1f4d35acd2 100644 --- a/src/renderer/src/components/tab-bar/SortableTab.tsx +++ b/src/renderer/src/components/tab-bar/SortableTab.tsx @@ -21,6 +21,7 @@ import { import { preventMiddleButtonDefault } from './middle-button-default-guard' import { useSortableTabRename } from './use-sortable-tab-rename' import { SortableTabContextMenu } from './SortableTabContextMenu' +import { useSortableTabContextMenu } from './use-sortable-tab-context-menu' import { translate } from '@/i18n/i18n' import { TAB_LABEL_WIDTH_CLASSES } from './tab-width-rules' import { useTabStripSlotProps } from './use-tab-strip-slot-props' @@ -139,7 +140,12 @@ export default function SortableTab({ }) // Why: no transform/transition/opacity so tabs stay anchored during drag, only the insertion bar moves (see TabBar.tsx). - const [menuOpen, setMenuOpen] = useState(false) + const { + open: menuOpen, + openingId, + onOpenChange: setMenuOpen, + onComplete + } = useSortableTabContextMenu() const [menuPoint, setMenuPoint] = useState({ x: 0, y: 0 }) const { isEditing, @@ -401,6 +407,8 @@ export default function SortableTab({ groupId={groupId} isActive={isActive} open={menuOpen} + openingId={openingId} + onSessionSwitchComplete={onComplete} point={menuPoint} tabCount={tabCount} hasTabsToRight={hasTabsToRight} diff --git a/src/renderer/src/components/tab-bar/SortableTabContextMenu.tsx b/src/renderer/src/components/tab-bar/SortableTabContextMenu.tsx index d77345a17c61..f3a28face3f2 100644 --- a/src/renderer/src/components/tab-bar/SortableTabContextMenu.tsx +++ b/src/renderer/src/components/tab-bar/SortableTabContextMenu.tsx @@ -95,6 +95,8 @@ type SortableTabContextMenuProps = { groupId: string isActive: boolean open: boolean + openingId?: number + onSessionSwitchComplete?: () => void point: { x: number; y: number } tabCount: number hasTabsToRight: boolean @@ -129,6 +131,8 @@ export function SortableTabContextMenu({ groupId, isActive, open, + openingId, + onSessionSwitchComplete, point, tabCount, hasTabsToRight, @@ -193,9 +197,11 @@ export function SortableTabContextMenu({ ) : null} diff --git a/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.test.tsx b/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.test.tsx index ee50c45b2cbe..fe8d09de36a1 100644 --- a/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.test.tsx +++ b/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.test.tsx @@ -9,32 +9,39 @@ import { import { TooltipProvider } from '@/components/ui/tooltip' import type { AiVaultSession } from '../../../../shared/ai-vault-types' import { resetAiVaultForcedRescanThrottleForTest } from '../right-sidebar/ai-vault-session-refresh' -import { cacheAiVaultSessionList } from '../right-sidebar/ai-vault-session-list-request' import { TabSessionSurfaceSwitchMenuItems } from './TabSessionSurfaceSwitchMenuItems' const mocks = vi.hoisted(() => { const state: { subject: Record | null move: { action: string; worktreeId: string } | null + cliSource: Record | null launchActionArgs: unknown[] - } = { subject: null, move: null, launchActionArgs: [] } + } = { subject: null, move: null, launchActionArgs: [], cliSource: null } return { ...state, handleResumeInNewChat: vi.fn(), handleResumeInNewCli: vi.fn(), resolveSwitch: vi.fn(), + runCliChatResume: vi.fn(async () => {}), listSessions: vi.fn(), cancelListSessions: vi.fn(async () => {}) } }) -vi.mock('../../store', () => ({ +vi.mock('@/store', () => ({ useAppStore: Object.assign( (selector: (state: Record) => unknown) => selector({ settings: null }), { getState: () => ({}) } ) })) +vi.mock('./cli-chat-resume-source', () => ({ resolveCliChatResumeSource: () => mocks.cliSource })) +vi.mock('./cli-chat-resume-run', () => ({ + runCliChatResume: mocks.runCliChatResume, + useCliChatResumePending: () => false +})) + vi.mock('./tab-session-history-switch', async (importOriginal) => ({ ...(await importOriginal>()), resolveTabSessionHistorySubject: () => mocks.subject, @@ -88,20 +95,14 @@ const CHAT_SUBJECT = { request: PANEL_REQUEST } -const CLI_SUBJECT = { - kind: 'cli', - agent: 'claude', - providerSessionId: 'claude-session-1', - workspaceId: 'wt-1', - request: PANEL_REQUEST -} - function listResult(sessions: AiVaultSession[]) { return { sessions, issues: [], scannedAt: 'now' } } beforeEach(() => { resetAiVaultForcedRescanThrottleForTest() + mocks.cliSource = null + mocks.runCliChatResume.mockClear() mocks.subject = null mocks.move = null mocks.launchActionArgs = [] @@ -181,40 +182,22 @@ describe('TabSessionSurfaceSwitchMenuItems', () => { }) }) - it('runs the Session History "Resume in New Native Chat" handler for a CLI tab', async () => { - const cliRow = { ...CHAT_ROW, structuredSession: undefined } - mocks.listSessions.mockResolvedValue({ - sessions: [cliRow], - issues: [], - scannedAt: 'now' - }) - mocks.subject = CLI_SUBJECT - mocks.move = { action: 'resume-in-new-chat', worktreeId: 'wt-1' } - await renderItems() - - expect(screen.queryByText('Resume in New CLI')).toBeNull() - fireEvent.click(screen.getByRole('menuitem', { name: 'Resume in New Native Chat' })) - expect(mocks.handleResumeInNewChat).toHaveBeenCalledWith(cliRow, 'wt-1') - }) - - it('offers nothing before the fresh answer and never shows a stale cached row', async () => { - // The cached row predates a chat taking the conversation; only the fresh reply knows. - const cliRow = { ...CHAT_ROW, structuredSession: undefined } - cacheAiVaultSessionList(PANEL_REQUEST, listResult([cliRow]), { replaceHostEntries: false }) - mocks.listSessions.mockResolvedValue(listResult([CHAT_ROW])) - mocks.subject = CLI_SUBJECT - mocks.move = { action: 'resume-in-new-chat', worktreeId: 'wt-1' } - // The real gate refuses a chat-owned row (pinned in tab-session-history-switch.parity.test.ts). - mocks.resolveSwitch.mockImplementation((_state: unknown, session: AiVaultSession) => - session.structuredSession ? null : mocks.move - ) + it('offers and dispatches a CLI identity while History never answers', async () => { + const source = { + tabId: 'tab-1', + workspaceId: 'wt-1', + paneKey: 'tab-1:leaf', + agent: 'claude', + providerSessionId: 'provider-1', + executionHostId: 'local' + } + mocks.cliSource = source + mocks.listSessions.mockReturnValue(new Promise(() => {})) renderItemsNow() - - expect(screen.queryByRole('menuitem')).toBeNull() + fireEvent.click(screen.getByRole('menuitem', { name: 'Resume in New Native Chat' })) await act(async () => {}) - expect(mocks.listSessions).toHaveBeenCalledWith(expect.objectContaining({ force: undefined })) - expect(mocks.resolveSwitch).toHaveBeenCalledWith(expect.anything(), CHAT_ROW, CLI_SUBJECT) - expect(screen.queryByRole('menuitem')).toBeNull() + expect(mocks.runCliChatResume).toHaveBeenCalledWith(source) + expect(mocks.listSessions).not.toHaveBeenCalled() }) it('offers the move once the fresh answer has it', async () => { diff --git a/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.tsx b/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.tsx index 5daf01e0399d..8d7fc3d22ca7 100644 --- a/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.tsx +++ b/src/renderer/src/components/tab-bar/TabSessionSurfaceSwitchMenuItems.tsx @@ -7,6 +7,7 @@ import type { AiVaultSession } from '../../../../shared/ai-vault-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import { AiVaultSessionSurfaceSwitchMenuItems } from '../right-sidebar/AiVaultSessionSurfaceSwitchMenuItems' import { useAiVaultSessionLaunchActions } from '../right-sidebar/ai-vault-session-launch-actions' +import { CliChatResumeMenuItems } from './CliChatResumeMenuItems' import { lookupTabSessionHistoryRow, resolveTabSessionHistorySubject, @@ -69,7 +70,7 @@ function useTabSessionSwitch( /** The Session History row's "Resume in New Native Chat" / "Resume in New CLI", offered on the tab * that shows that session and hidden wherever the row would not offer it. */ -export function TabSessionSurfaceSwitchMenuItems({ +function HistoryTabSessionSurfaceSwitchMenuItems({ tab, nativeChat, leadingSeparator @@ -119,3 +120,16 @@ export function TabSessionSurfaceSwitchMenuItems({ ) } + +export function TabSessionSurfaceSwitchMenuItems(props: { + tab: Pick + nativeChat?: NativeChatTabSession + leadingSeparator: boolean + onComplete?: () => void +}): React.JSX.Element | null { + return props.nativeChat ? ( + + ) : ( + + ) +} diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts new file mode 100644 index 000000000000..7ca8e68f565c --- /dev/null +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts @@ -0,0 +1,62 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { structuredLaunchFailure } from '@/lib/structured-agent-session-launch-failure' +import { StructuredAgentSessionCreateRefusalError } from '@/lib/structured-agent-session-launch-errors' +import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' +import { agentSessionWriteFailureText } from '../native-chat/agent-session-write-notice-text' +import { agentLabel } from '../../../../shared/ai-vault-session-filters' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import type { CliChatResumeSource } from './cli-chat-resume-source' + +export async function reportCliChatResumeFailure( + source: CliChatResumeSource, + error: unknown, + openOwner: boolean, + target: RuntimeClientTarget +): Promise { + const refusal = + error instanceof StructuredAgentSessionCreateRefusalError ? error.refusal : undefined + if ( + refusal?.code === 'agent_session_conflict' || + refusal?.code === 'agent_session_ownership_unknown' + ) { + const owner = refusal.details?.owner + if (openOwner && owner) { + await activateAiVaultStructuredSession({ structuredSession: owner }, undefined, target) + return + } + toast.error( + translate( + 'auto.components.right.sidebar.AiVaultPanel.resumeInChatConflict', + 'Another chat is already holding this conversation.' + ) + ) + return + } + if (refusal?.code === 'agent_session_identity_required') { + if ( + refusal.details?.reason === 'transcriptNotFound' || + refusal.details?.reason === 'transcriptEmpty' + ) { + toast.error( + translate( + 'components.native-chat.resumeInNewChat.notSavedYet', + "{{agent}} hasn't saved this conversation yet. Try again after it replies.", + { agent: agentLabel(source.agent) } + ) + ) + return + } + const failure = structuredLaunchFailure(error) + if (failure) { + toast.error(agentSessionWriteFailureText(failure, 'read-history')) + return + } + } + toast.error( + translate( + 'auto.components.right.sidebar.AiVaultPanel.resumeInChatFailed', + 'Could not resume this session in a new chat.' + ) + ) +} diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts new file mode 100644 index 000000000000..5ff0e8e4849a --- /dev/null +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -0,0 +1,209 @@ +// @vitest-environment happy-dom +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { CliChatResumeSource } from './cli-chat-resume-source' +import type { AgentSessionWireRefusal } from '../../../../shared/agent-session-wire' +import type { StructuredAgentSessionCreateParams } from '../../../../shared/structured-agent-session-create' + +const mocks = vi.hoisted(() => { + const state: { source: CliChatResumeSource | null } = { source: null } + return { + ...state, + sourceCapability: vi.fn(), + createCapability: vi.fn(), + call: vi.fn(), + toast: vi.fn(), + activate: vi.fn(async () => true) + } +}) +vi.mock('./cli-chat-resume-source', () => ({ resolveCliChatResumeSource: () => mocks.source })) +vi.mock('@/runtime/structured-agent-session-client', () => ({ + supportsStructuredAgentSessionCliSource: mocks.sourceCapability, + supportsStructuredAgentSessionCreateMessage: mocks.createCapability, + callStructuredAgentSession: mocks.call +})) +vi.mock('@/runtime/structured-session-tab-inventory', () => ({ + readStructuredSessionTabInventory: async () => { + throw new Error('Reply unavailable') + } +})) +vi.mock('@/lib/structured-agent-session-create-hydration', () => ({ + publishStructuredAgentSessionCreateHydration: vi.fn() +})) +vi.mock('sonner', () => ({ toast: { error: mocks.toast } })) +vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ + activateAiVaultStructuredSession: mocks.activate +})) + +import { useAppStore } from '@/store' +import { runCliChatResume } from './cli-chat-resume-run' +import { + resetStructuredAgentLaunchRegistryForTests, + structuredLaunchStates +} from '@/lib/structured-agent-session-launch-registry' +import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims' +import { openStructuredAgentSessionProvisionalTab } from '@/lib/structured-agent-session-provisional-tab' +import { + clearWebSessionFocusIntent, + resetWebSessionFocusIntentForTests +} from '@/runtime/web-session-focus-intent' +import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' + +const SOURCE: CliChatResumeSource = { + tabId: 'tab-1', + workspaceId: 'wt-1', + paneKey: 'tab-1:leaf', + agent: 'claude', + providerSessionId: 'provider-1', + executionHostId: 'local' +} +const tabs = () => useAppStore.getState().unifiedTabsByWorktree['wt-1'] ?? [] +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} +function refuse( + reason: 'transcriptNotFound' | 'transcriptEmpty' | 'transcriptUnreadable' +): AgentSessionWireRefusal { + return { + code: 'agent_session_identity_required', + message: 'private host error', + details: { reason }, + createAttemptRefusedBeforeCommit: true + } +} + +beforeEach(() => { + vi.clearAllMocks() + localStorage.clear() + resetStructuredAgentLaunchRegistryForTests() + resetWebSessionFocusIntentForTests() + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ activeWorktreeId: 'wt-1' }) + mocks.source = SOURCE + mocks.sourceCapability.mockResolvedValue(true) + mocks.createCapability.mockResolvedValue(true) + mocks.call.mockImplementation( + async (_target, method, params: StructuredAgentSessionCreateParams) => { + expect(method).toBe('agentSession.create') + return { ok: true, value: { sessionId: params.envelope.sessionId, fence: 1 } } + } + ) +}) + +describe('CLI identity resume through the existing launch owner', () => { + it('shares pending, sends only an advertised source, and survives source closure after dispatch', async () => { + const reply = deferred() + mocks.call.mockReturnValue(reply.promise) + const running = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) + await runCliChatResume({ ...SOURCE, paneKey: 'another-pane' }) + expect(mocks.call).toHaveBeenCalledOnce() + expect(tabs()).toEqual([]) + expect(isEmptyWorkspaceDefaultSurfacePending('wt-1')).toBe(true) + const params: StructuredAgentSessionCreateParams = mocks.call.mock.calls[0][2] + expect(params.resumeFrom).toEqual({ + providerSessionId: 'provider-1', + cliSource: { workspaceId: 'wt-1', paneKey: 'tab-1:leaf' } + }) + mocks.source = null + useAppStore.setState({}) + reply.resolve({ ok: true, value: { sessionId: params.envelope.sessionId, fence: 1 } }) + await running + expect(tabs()).toHaveLength(1) + expect(isEmptyWorkspaceDefaultSurfacePending('wt-1')).toBe(false) + }) + + it('retires an unsent click during create capability waiting, even if the same source returns', async () => { + const capability = deferred() + mocks.createCapability.mockReturnValue(capability.promise) + const running = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.createCapability).toHaveBeenCalledOnce()) + mocks.source = null + useAppStore.setState({}) + await running + mocks.source = SOURCE + capability.resolve(true) + await vi.waitFor(() => expect([...structuredLaunchStates()]).toHaveLength(0)) + expect(mocks.call).not.toHaveBeenCalled() + expect(tabs()).toEqual([]) + expect(mocks.toast).not.toHaveBeenCalled() + }) + + it('uses ID-only create for an older host and retains uncertainty without pre-commit proof', async () => { + mocks.sourceCapability.mockResolvedValue(false) + mocks.call.mockResolvedValue({ + ok: false, + refusal: { code: 'agent_session_conflict', message: 'old host' } + }) + await runCliChatResume(SOURCE, true) + expect(mocks.call.mock.calls[0][2].resumeFrom).toEqual({ providerSessionId: 'provider-1' }) + expect(tabs()).toHaveLength(1) + expect(mocks.activate).not.toHaveBeenCalled() + expect(mocks.toast).not.toHaveBeenCalled() + }) + + it('keeps ordinary refusals hidden and distinguishes unsaved from unreadable content', async () => { + for (const reason of [ + 'transcriptNotFound', + 'transcriptEmpty', + 'transcriptUnreadable' + ] as const) { + mocks.call.mockResolvedValue({ ok: false, refusal: refuse(reason) }) + await runCliChatResume(SOURCE) + expect(tabs()).toEqual([]) + expect([...structuredLaunchStates()]).toEqual([]) + expect(mocks.toast.mock.calls.at(-1)?.[0]).toMatch( + reason === 'transcriptUnreadable' ? /history.*could not/i : /hasn't saved/ + ) + } + }) + + it('opens a proved owner only for the header, on the initiating host, without importing', async () => { + const owner = { sessionId: 'owner-chat', workspaceId: 'owner-workspace' } + mocks.call.mockResolvedValue({ + ok: false, + refusal: { + code: 'agent_session_conflict', + message: 'owner', + details: { reason: 'conversationHeldElsewhere', owner }, + createAttemptRefusedBeforeCommit: true + } + }) + await runCliChatResume(SOURCE) + expect(mocks.toast).toHaveBeenCalledWith('Another chat is already holding this conversation.') + expect(mocks.activate).not.toHaveBeenCalled() + await runCliChatResume(SOURCE, true) + expect(mocks.activate).toHaveBeenCalledWith({ structuredSession: owner }, undefined, { + kind: 'local' + }) + expect(tabs()).toEqual([]) + }) + + it('does not re-activate a published destination over a later selection', async () => { + const reply = deferred() + mocks.call.mockReturnValue(reply.promise) + const running = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) + const sessionId: string = mocks.call.mock.calls[0][2].envelope.sessionId + openStructuredAgentSessionProvisionalTab({ + worktreeId: 'wt-1', + executionHostId: 'local', + sessionId, + agent: 'claude' + }) + clearWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1') + const later = useAppStore + .getState() + .createUnifiedTab('wt-1', 'editor', { entityId: 'later-file', label: 'Later' }) + reply.resolve({ ok: true, value: { sessionId, fence: 1 } }) + await running + const state = useAppStore.getState() + expect(tabs().filter((tab) => tab.entityId === sessionId)).toHaveLength(1) + expect( + state.groupsByWorktree['wt-1'].find((group) => group.id === later.groupId)?.activeTabId + ).toBe(later.id) + }) +}) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts new file mode 100644 index 000000000000..3accb7044b94 --- /dev/null +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts @@ -0,0 +1,140 @@ +import { useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import { newAgentLaunchRequestId } from '@/lib/agent-launch-request-id' +import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session-launch-plan' +import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/structured-agent-session-provisional-tab' +import { supportsStructuredAgentSessionCliSource } from '@/runtime/structured-agent-session-client' +import { structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' +import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../../shared/structured-agent-cli-conversation-adoption' +import { resolveCliChatResumeSource, type CliChatResumeSource } from './cli-chat-resume-source' +import { reportCliChatResumeFailure } from './cli-chat-resume-feedback' + +const pending = new Map() +const listeners = new Set<() => void>() +const changed = () => listeners.forEach((listener) => listener()) +const keyFor = (source: CliChatResumeSource) => + [ + source.executionHostId, + CLI_CONVERSATION_ADOPTING_AGENTS[source.agent], + source.providerSessionId + ].join('\0') +const subscribe = (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function useCliChatResumePending(source: CliChatResumeSource | null): boolean { + return useSyncExternalStore( + subscribe, + () => !!source && pending.has(keyFor(source)), + () => false + ) +} + +export async function runCliChatResume( + source: CliChatResumeSource, + openOwner = false +): Promise { + const key = keyFor(source) + if (pending.has(key)) { + return + } + const target = structuredAgentSessionTargetForHost(source.executionHostId) + if (!target || target.kind !== 'local') { + return + } + const controller = new AbortController() + const isCurrent = () => { + if (controller.signal.aborted) { + return false + } + const current = resolveCliChatResumeSource(useAppStore.getState(), { + tab: { id: source.tabId, worktreeId: source.workspaceId }, + paneKey: source.paneKey + }) + return ( + !!current && + current.executionHostId === source.executionHostId && + current.providerSessionId === source.providerSessionId && + CLI_CONVERSATION_ADOPTING_AGENTS[current.agent] === + CLI_CONVERSATION_ADOPTING_AGENTS[source.agent] + ) + } + if (!isCurrent()) { + return + } + const release = () => { + if (pending.get(key) === controller) { + pending.delete(key) + changed() + } + } + pending.set(key, controller) + changed() + const stopSource = useAppStore.subscribe(() => { + if (!isCurrent()) { + controller.abort() + release() + } + }) + const timer = setTimeout( + () => controller.abort(new Error('Conversation preparation timed out.')), + 30_000 + ) + let dispatched = false + const handoff = () => { + if (dispatched) { + return true + } + if (!isCurrent()) { + return false + } + dispatched = true + stopSource() + clearTimeout(timer) + return true + } + try { + const cliSourceSupported = await waitForPromiseWithSignal( + supportsStructuredAgentSessionCliSource(target), + controller.signal + ) + if (!isCurrent()) { + return + } + const plan = adoptAgentSessionLaunchVerdict({ + route: 'structured-native-chat', + requestId: newAgentLaunchRequestId(), + agent: CLI_CONVERSATION_ADOPTING_AGENTS[source.agent], + worktreeId: source.workspaceId, + executionHostId: source.executionHostId, + resumeFrom: { + providerSessionId: source.providerSessionId, + ...(cliSourceSupported + ? { cliSource: { workspaceId: source.workspaceId, paneKey: source.paneKey } } + : {}) + } + }) + const launch = beginStructuredAgentSessionProvisionalLaunch({ + plan, + hooks: { beforeCreate: handoff }, + deferPublication: true + }) + if (!launch) { + return + } + const result = await waitForPromiseWithSignal(launch.settlement, controller.signal) + if (result.kind === 'failed' && !result.notified && pending.get(key) === controller) { + await reportCliChatResumeFailure(source, result.error, openOwner, target) + } + } catch (error) { + if (pending.get(key) === controller) { + await reportCliChatResumeFailure(source, error, false, target) + } + } finally { + clearTimeout(timer) + stopSource() + release() + } +} diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-source.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-source.ts new file mode 100644 index 000000000000..beba57e98e09 --- /dev/null +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-source.ts @@ -0,0 +1,55 @@ +import type { AppState } from '@/store/types' +import { + collectAgentPaneConversations, + resolvePaneAgentConversation +} from '@/lib/ai-vault-tab-title-requests' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import { + adoptsCliConversations, + type CliConversationRowAgent +} from '../../../../shared/structured-agent-cli-conversation-adoption' +import { canPaneOfferResumeInNewChat } from './tab-session-history-switch' + +export type CliChatResumeSource = { + tabId: string + workspaceId: string + paneKey: string + agent: CliConversationRowAgent + providerSessionId: string + executionHostId: ExecutionHostId +} + +export function resolveCliChatResumeSource( + state: AppState, + args: { tab: { id: string; worktreeId: string }; paneKey?: string } +): CliChatResumeSource | null { + const conversation = args.paneKey + ? resolvePaneAgentConversation( + state, + { worktreeId: args.tab.worktreeId, paneKey: args.paneKey }, + adoptsCliConversations + ) + : collectAgentPaneConversations(state, adoptsCliConversations, { + runningAgentsOnly: true + }).find((candidate) => candidate.tabId === args.tab.id) + if ( + !conversation || + conversation.tabId !== args.tab.id || + conversation.worktreeId !== args.tab.worktreeId || + conversation.executionHostId !== LOCAL_EXECUTION_HOST_ID || + !canPaneOfferResumeInNewChat(state, { + worktreeId: conversation.worktreeId, + paneKey: conversation.paneKey + }) + ) { + return null + } + return { + tabId: conversation.tabId, + workspaceId: conversation.worktreeId, + paneKey: conversation.paneKey, + agent: conversation.agent, + providerSessionId: conversation.providerSession.id, + executionHostId: conversation.executionHostId + } +} diff --git a/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts b/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts index e9c67415fee7..c90ad43d115c 100644 --- a/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts +++ b/src/renderer/src/components/tab-bar/tab-session-history-switch.test.ts @@ -4,6 +4,7 @@ import type { AppState } from '@/store/types' import { makeRepo, makeTerminalTab, makeWorktree } from '../worktree-jump-palette-test-fixtures' import { makeAgentStatusEntry } from '@/runtime/sync-runtime-graph-test-harness' import { collectAiVaultTitleRequests } from '@/lib/ai-vault-tab-title-requests' +import { resolveCliChatResumeSource } from './cli-chat-resume-source' import type { AiVaultListArgs, AiVaultSession } from '../../../../shared/ai-vault-types' import { getDefaultSettings } from '../../../../shared/constants' import { @@ -186,6 +187,20 @@ const exitedAgentRecords: Record> = { } describe('resolveTabSessionHistorySubject', () => { + it('retains the chosen pane in the direct CLI create identity without a History row', () => { + expect( + resolveCliChatResumeSource(makeState(liveClaudeEntry), { + tab: { id: 'term-1', worktreeId: WORKTREE_ID } + }) + ).toMatchObject({ + tabId: 'term-1', + workspaceId: WORKTREE_ID, + paneKey: 'term-1:leaf-1', + agent: 'claude', + providerSessionId: 'claude-session-1', + executionHostId: 'local' + }) + }) it('finds a native chat tab by the chat it shows', () => { expect( resolveTabSessionHistorySubject(makeState(), { diff --git a/src/renderer/src/components/tab-bar/tab-session-history-switch.ts b/src/renderer/src/components/tab-bar/tab-session-history-switch.ts index d3e74a9af3e5..68041fd4e446 100644 --- a/src/renderer/src/components/tab-bar/tab-session-history-switch.ts +++ b/src/renderer/src/components/tab-bar/tab-session-history-switch.ts @@ -77,8 +77,7 @@ function canHostOfferTabSessionMove( return kind === 'chat' && parseExecutionHostId(hostScope)?.kind === 'runtime' } -/** Whether a pane's running agent has a conversation the move could act on, without building the - * list request, for a surface that stays rendered. The history lookup still decides on click. */ +/** The pane's known identity and launch route, without a History request. */ export function canPaneOfferResumeInNewChat( state: AppState, pane: { worktreeId: string; paneKey: string } diff --git a/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts b/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts new file mode 100644 index 000000000000..aa1063d0c3b1 --- /dev/null +++ b/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.test.ts @@ -0,0 +1,18 @@ +// @vitest-environment happy-dom +import { act, renderHook } from '@testing-library/react' +import { expect, it } from 'vitest' +import { useSortableTabContextMenu } from './use-sortable-tab-context-menu' + +it('an old completion cannot close a reopened menu, including retained closing content', () => { + const { result } = renderHook(useSortableTabContextMenu) + act(() => result.current.onOpenChange(true)) + const oldComplete = result.current.onComplete + const oldId = result.current.openingId + act(() => result.current.onOpenChange(false)) + act(() => result.current.onOpenChange(true)) + expect(result.current.openingId).not.toBe(oldId) + act(oldComplete) + expect(result.current.open).toBe(true) + act(result.current.onComplete) + expect(result.current.open).toBe(false) +}) diff --git a/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.ts b/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.ts new file mode 100644 index 000000000000..c0d246d12260 --- /dev/null +++ b/src/renderer/src/components/tab-bar/use-sortable-tab-context-menu.ts @@ -0,0 +1,17 @@ +import { useCallback, useRef, useState } from 'react' + +/** Opening identity survives animated content; dismissal retires it synchronously. */ +export function useSortableTabContextMenu() { + const generation = useRef(0) + const [opening, setOpening] = useState({ id: 0, open: false }) + const onOpenChange = useCallback((open: boolean) => { + const id = ++generation.current + setOpening((previous) => ({ id: open ? id : previous.id, open })) + }, []) + const onComplete = () => { + if (generation.current === opening.id) { + onOpenChange(false) + } + } + return { open: opening.open, openingId: opening.id, onOpenChange, onComplete } +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx index a5acd9341ff0..667645494f14 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx @@ -1,191 +1,53 @@ // @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' -import type { AiVaultSession } from '../../../../shared/ai-vault-types' -import { - claimAiVaultForcedRescan, - resetAiVaultForcedRescanThrottleForTest -} from '../right-sidebar/ai-vault-session-refresh' import { TerminalPaneResumeInChatButton } from './TerminalPaneResumeInChatButton' -const mocks = vi.hoisted(() => { - const state: { - subject: Record | null - move: { action: string; worktreeId: string } | null - subjectArgs: unknown[] - tabOpen: boolean - } = { subject: null, move: null, subjectArgs: [], tabOpen: true } - return { - ...state, - resumeInNewChat: vi.fn(async () => {}), - activateChat: vi.fn(async () => true), - listSessions: vi.fn(), - toastError: vi.fn() - } -}) - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ tabsByWorktree: { 'wt-1': mocks.tabOpen ? [{ id: 'tab-1' }] : [] } }) - } -})) - -vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) - -vi.mock('../tab-bar/tab-session-history-switch', async (importOriginal) => ({ - ...(await importOriginal>()), - resolveTabSessionHistorySubject: (_state: unknown, args: unknown) => { - mocks.subjectArgs.push(args) - return mocks.subject +const mocks = vi.hoisted(() => ({ + source: { + tabId: 'tab-1', + workspaceId: 'wt-1', + paneKey: 'tab-1:leaf', + agent: 'claude', + providerSessionId: 'provider-1', + executionHostId: 'local' }, - resolveTabSessionSwitch: () => mocks.move + resolve: vi.fn(), + run: vi.fn(), + pending: false })) - -vi.mock('../right-sidebar/ai-vault-session-resume-in-chat-launch', () => ({ - resumeAiVaultSessionInNewChat: mocks.resumeInNewChat +vi.mock('@/store', () => ({ useAppStore: (selector: (state: object) => unknown) => selector({}) })) +vi.mock('../tab-bar/cli-chat-resume-source', () => ({ + resolveCliChatResumeSource: (_state: unknown, args: unknown) => { + mocks.resolve(args) + return mocks.source + } })) - -vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: mocks.activateChat +vi.mock('../tab-bar/cli-chat-resume-run', () => ({ + runCliChatResume: mocks.run, + useCliChatResumePending: () => mocks.pending })) - -const CLI_ROW: AiVaultSession = { - id: 'row-1', - executionHostId: 'local', - agent: 'claude', - sessionId: 'claude-session-1', - title: 'Fix the build', - cwd: '/repo/wt', - branch: null, - model: null, - filePath: '/home/.claude/projects/repo/claude-session-1.jsonl', - codexHome: null, - createdAt: null, - updatedAt: null, - modifiedAt: '2026-10-08T00:00:00.000Z', - messageCount: 2, - totalTokens: 10, - previewMessages: [], - queuedMessageCount: 0, - subagentTranscriptCount: 0, - resumeCommand: '', - subagent: null -} - -const CLI_SUBJECT = { - kind: 'cli', - agent: 'claude', - providerSessionId: 'claude-session-1', - workspaceId: 'wt-1', - request: { scopePaths: ['/repo/wt'], executionHostScope: 'local', sessionLimit: 250 } -} - -beforeEach(() => { - resetAiVaultForcedRescanThrottleForTest() - mocks.subject = CLI_SUBJECT - mocks.move = null - mocks.subjectArgs = [] - mocks.tabOpen = true - mocks.resumeInNewChat.mockClear() - mocks.activateChat.mockClear() - mocks.toastError.mockReset() - mocks.listSessions.mockReset() - mocks.listSessions.mockResolvedValue({ sessions: [CLI_ROW], issues: [], scannedAt: 'now' }) - Object.assign(window, { - api: { aiVault: { listSessions: mocks.listSessions, cancelListSessions: vi.fn() } } - }) -}) - afterEach(cleanup) -async function clickResume(): Promise { - render( +it('dispatches the exact pane with owner-opening intent and shares pending', () => { + const { rerender } = render( - + ) - expect(mocks.listSessions).not.toHaveBeenCalled() - await act(async () => { - fireEvent.click(screen.getByRole('button', { name: 'Resume in New Native Chat' })) - }) -} - -describe('TerminalPaneResumeInChatButton', () => { - it("resumes this pane's own conversation in a new native chat", async () => { - mocks.move = { action: 'resume-in-new-chat', worktreeId: 'wt-1' } - await clickResume() - expect(mocks.subjectArgs).toEqual([ - { tab: { id: 'tab-1', worktreeId: 'wt-1' }, paneKey: 'tab-1:leaf-1' } - ]) - expect(mocks.resumeInNewChat).toHaveBeenCalledWith( - CLI_ROW, - 'claude', - 'wt-1', - expect.any(String) - ) - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('resumes a Grok conversation, which a chat can take over too', async () => { - const grokRow = { ...CLI_ROW, agent: 'grok' as const, sessionId: 'grok-session-1' } - mocks.subject = { ...CLI_SUBJECT, agent: 'grok', providerSessionId: 'grok-session-1' } - mocks.move = { action: 'resume-in-new-chat', worktreeId: 'wt-1' } - mocks.listSessions.mockResolvedValue({ sessions: [grokRow], issues: [], scannedAt: 'now' }) - await clickResume() - expect(mocks.resumeInNewChat).toHaveBeenCalledWith(grokRow, 'grok', 'wt-1', expect.any(String)) - }) - - it('opens the native chat that already holds the conversation', async () => { - const owned = { ...CLI_ROW, structuredSession: { sessionId: 'chat-1', workspaceId: 'wt-1' } } - mocks.listSessions.mockResolvedValue({ sessions: [owned], issues: [], scannedAt: 'now' }) - await clickResume() - expect(mocks.activateChat).toHaveBeenCalledWith(owned) - expect(mocks.listSessions).toHaveBeenCalledTimes(1) - expect(mocks.resumeInNewChat).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('says the agent has not saved anything yet, after a fresh scan even inside the budget', async () => { - claimAiVaultForcedRescan() - mocks.listSessions.mockResolvedValue({ sessions: [], issues: [], scannedAt: 'now' }) - await clickResume() - expect(mocks.listSessions).toHaveBeenLastCalledWith(expect.objectContaining({ force: true })) - expect(mocks.toastError).toHaveBeenCalledWith( - "Claude hasn't saved this conversation yet. Try again after it replies." - ) - }) - - it('says plainly when the conversation cannot move, without a retry promise', async () => { - await clickResume() - expect(mocks.resumeInNewChat).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith( - "This Claude conversation can't be resumed in a native chat." - ) - }) - - it('reports a failed lookup as a failure', async () => { - mocks.listSessions.mockRejectedValue(new Error('host unreachable')) - await clickResume() - expect(mocks.resumeInNewChat).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith('Could not resume this session in a new chat.') - }) - - it('does nothing once the tab closed during the lookup', async () => { - mocks.move = { action: 'resume-in-new-chat', worktreeId: 'wt-1' } - mocks.listSessions.mockImplementation(async () => { - mocks.tabOpen = false - return { sessions: [CLI_ROW], issues: [], scannedAt: 'now' } - }) - await clickResume() - expect(mocks.resumeInNewChat).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('looks nothing up when the pane has no conversation any more', async () => { - mocks.subject = null - await clickResume() - expect(mocks.listSessions).not.toHaveBeenCalled() - expect(mocks.toastError).toHaveBeenCalledWith('Could not resume this session in a new chat.') - }) + fireEvent.click(screen.getByRole('button', { name: 'Resume in New Native Chat' })) + expect(mocks.resolve).toHaveBeenCalledWith({ + tab: { id: 'tab-1', worktreeId: 'wt-1' }, + paneKey: 'tab-1:leaf' + }) + expect(mocks.run).toHaveBeenCalledWith(mocks.source, true) + mocks.pending = true + rerender( + + + + ) + expect(screen.getByRole('button').getAttribute('aria-busy')).toBe('true') + expect(screen.getByRole('button').hasAttribute('disabled')).toBe(true) }) diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.tsx index fb804778f3b5..96cf9d6b3825 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.tsx @@ -1,34 +1,12 @@ -import { useState } from 'react' +import { useShallow } from 'zustand/react/shallow' import { MessagesSquare } from 'lucide-react' -import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { translate } from '@/i18n/i18n' -import { createBrowserUuid } from '@/lib/browser-uuid' -import { newAgentLaunchRequestId } from '@/lib/agent-launch-request-id' -import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' import { useAppStore } from '@/store' -import { isAiVaultSessionResumableContent } from '../../../../shared/ai-vault-types' -import { agentLabel } from '../../../../shared/ai-vault-session-filters' -import { adoptsCliConversations } from '../../../../shared/structured-agent-cli-conversation-adoption' -import { resumeAiVaultSessionInNewChat } from '../right-sidebar/ai-vault-session-resume-in-chat-launch' -import { - lookupTabSessionHistoryRow, - resolveTabSessionHistorySubject, - resolveTabSessionSwitch -} from '../tab-bar/tab-session-history-switch' +import { resolveCliChatResumeSource } from '../tab-bar/cli-chat-resume-source' +import { runCliChatResume, useCliChatResumePending } from '../tab-bar/cli-chat-resume-run' -function notifyResumeFailed(): void { - toast.error( - translate( - 'auto.components.right.sidebar.AiVaultPanel.resumeInChatFailed', - 'Could not resume this session in a new chat.' - ) - ) -} - -/** The tab menu's "Resume in New Native Chat" for this pane's own conversation. The history lookup - * runs on click, not per render, so a header that stays on screen never scans in the background. */ export function TerminalPaneResumeInChatButton({ tabId, worktreeId, @@ -38,71 +16,20 @@ export function TerminalPaneResumeInChatButton({ worktreeId: string paneKey: string }): React.JSX.Element { - const [pending, setPending] = useState(false) + const source = useAppStore( + useShallow((state) => + resolveCliChatResumeSource(state, { + tab: { id: tabId, worktreeId }, + paneKey + }) + ) + ) + const pending = useCliChatResumePending(source) const label = translate( 'auto.components.right.sidebar.AiVaultSessionRow.resumeInNewNativeChat', 'Resume in New Native Chat' ) - const resume = async (): Promise => { - const tabIsOpen = (): boolean => - useAppStore.getState().tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId) ?? false - const subject = resolveTabSessionHistorySubject(useAppStore.getState(), { - tab: { id: tabId, worktreeId }, - paneKey - }) - if (subject?.kind !== 'cli') { - notifyResumeFailed() - return - } - const row = await lookupTabSessionHistoryRow( - subject, - (args) => window.api.aiVault.listSessions(args), - { requestToken: createBrowserUuid(), isCancelled: () => !tabIsOpen(), userRequested: true } - ) - // Closing the tab mid-lookup abandons the click rather than opening a chat for it. - if (!tabIsOpen()) { - return - } - if (row === undefined) { - notifyResumeFailed() - return - } - // Already resumed in a chat: open that chat, as the Session History row's Resume does. - if (row?.structuredSession) { - await activateAiVaultStructuredSession(row) - return - } - const agent = agentLabel(subject.agent) - if (!row || !isAiVaultSessionResumableContent(row)) { - toast.error( - translate( - 'components.native-chat.resumeInNewChat.notSavedYet', - "{{agent}} hasn't saved this conversation yet. Try again after it replies.", - { agent } - ) - ) - return - } - const move = resolveTabSessionSwitch(useAppStore.getState(), row, subject) - if (move?.action === 'resume-in-new-chat' && adoptsCliConversations(row.agent)) { - await resumeAiVaultSessionInNewChat( - row, - row.agent, - move.worktreeId, - newAgentLaunchRequestId() - ) - return - } - toast.error( - translate( - 'components.native-chat.resumeInNewChat.cannotResume', - "This {{agent}} conversation can't be resumed in a native chat.", - { agent } - ) - ) - } - return ( @@ -113,13 +40,13 @@ export function TerminalPaneResumeInChatButton({ // Same class as split so it shares the hover/active reveal. className="pane-title-split-trigger" aria-label={label} - disabled={pending} + disabled={!source || pending} + aria-busy={pending || undefined} onClick={(event) => { event.stopPropagation() - setPending(true) - void resume() - .catch(notifyResumeFailed) - .finally(() => setPending(false)) + if (source) { + void runCliChatResume(source, true) + } }} > diff --git a/src/renderer/src/lib/ai-vault-tab-title-requests.ts b/src/renderer/src/lib/ai-vault-tab-title-requests.ts index 3c9da0063b09..600c223c8573 100644 --- a/src/renderer/src/lib/ai-vault-tab-title-requests.ts +++ b/src/renderer/src/lib/ai-vault-tab-title-requests.ts @@ -15,10 +15,14 @@ export type AgentPaneConversation = { providerSession: AgentProviderSessionMetadata refresh: boolean tabId: string + paneKey: string worktreeId: string } -export type AiVaultTitleRequest = AgentPaneConversation +export type AiVaultTitleRequest = Omit< + AgentPaneConversation, + 'paneKey' +> type RequestCandidate = AgentPaneConversation & { priority: number @@ -68,6 +72,7 @@ function registerCandidate( providerSession: args.providerSession, refresh: args.refresh, tabId, + paneKey: args.paneKey, worktreeId, priority }) @@ -86,7 +91,9 @@ function liveCandidate(entry: AgentStatusEntry): Parameters request + ) } /** Each tab's conversation of an agent `isAgent` accepts: live agent, then sleeping, then retained. */ diff --git a/src/renderer/src/lib/launch-structured-agent-session.ts b/src/renderer/src/lib/launch-structured-agent-session.ts index f941f9e40d7a..d7bc79d13b2c 100644 --- a/src/renderer/src/lib/launch-structured-agent-session.ts +++ b/src/renderer/src/lib/launch-structured-agent-session.ts @@ -47,6 +47,7 @@ export type StructuredAgentSessionLaunchIntent = { createMessageSupport?: boolean createPrepared?: true prepareCreate?: () => void + beforeCreate?: () => boolean /** The saved selection create seeds, read when the intent is built. */ seedOptions?: Readonly> } diff --git a/src/renderer/src/lib/structured-agent-launch-settlement.ts b/src/renderer/src/lib/structured-agent-launch-settlement.ts index 044f61b32130..b828802ae764 100644 --- a/src/renderer/src/lib/structured-agent-launch-settlement.ts +++ b/src/renderer/src/lib/structured-agent-launch-settlement.ts @@ -7,6 +7,7 @@ import { type StructuredAgentLaunchOptions } from '@/lib/structured-agent-session-launch' import type { StructuredPromptDeliveryResult } from '@/lib/structured-agent-session-launch-prompt' +import { StructuredAgentSessionCreateAbandonedError } from './structured-agent-session-launch-errors' export type StructuredAgentLaunchSettlement = | { @@ -30,9 +31,12 @@ export type StructuredAgentLaunchHooks = { /** Abort the moment the caller abandons the launch. The loop cancels on the event, not only by * polling after awaits, so a staged prompt is discarded before it can reach the provider. */ signal?: AbortSignal + beforeCreate?: () => boolean } export type StructuredAgentLaunchHandle = { + /** An existing launch retains publication and any draft it already owns. */ + joined?: boolean sessionId: string /** The host the chat is created on. */ executionHostId: ExecutionHostId @@ -80,6 +84,9 @@ async function settleStartedStructuredAgentLaunch( if (isCancelled()) { return cancelled() } + if (error instanceof StructuredAgentSessionCreateAbandonedError) { + return cancelled() + } if (error instanceof StructuredAgentSessionCreateRefusalError) { return { kind: 'failed', error } } @@ -101,8 +108,16 @@ export function beginStructuredAgentLaunchSettlement( options: StructuredAgentLaunchOptions, hooks: StructuredAgentLaunchHooks ): StructuredAgentLaunchHandle { - const launch = startStructuredAgentLaunch(worktreeId, agent, options) + const launch = startStructuredAgentLaunch(worktreeId, agent, { + ...options, + ...(hooks.beforeCreate ? { beforeCreate: hooks.beforeCreate } : {}) + }) + // Joining transfers no source ownership to the already independent destination. + if (launch.joined) { + hooks.beforeCreate?.() + } return { + joined: launch.joined, sessionId: launch.sessionId, executionHostId: launch.executionHostId, settlement: settleStartedStructuredAgentLaunch(worktreeId, launch, hooks), diff --git a/src/renderer/src/lib/structured-agent-session-launch-callers.ts b/src/renderer/src/lib/structured-agent-session-launch-callers.ts index 0733941e683e..8e3258429643 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-callers.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-callers.ts @@ -24,6 +24,8 @@ export type StructuredAgentLaunchOptions = { executionHostId?: ExecutionHostId /** The saved selection a paired host reported it will seed; read only by the starting caller. */ hostSeedOptions?: Readonly> + /** Final admission of a source-bound action, immediately before its first create is sent. */ + beforeCreate?: () => boolean } export type StructuredLaunchCaller = { diff --git a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts index e31be1214987..6074a483065c 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts @@ -22,6 +22,7 @@ import { import type { StructuredAgentLaunchReceipt } from './structured-agent-session-launch-recovery' import { StructuredAgentSessionCreateError, + StructuredAgentSessionCreateAbandonedError, StructuredAgentSessionCreateRefusalError, StructuredAgentSessionCreateUnknownOutcomeError } from './structured-agent-session-launch-errors' @@ -103,6 +104,13 @@ export async function launchStructuredAgentSession( } } let result: AgentSessionMutationResult + if (intent.beforeCreate?.() === false) { + abandonStructuredAgentSessionLaunchIntent(intent) + throw new StructuredAgentSessionCreateAbandonedError( + 'Conversation source retired before create.' + ) + } + delete intent.beforeCreate try { result = await callStructuredAgentSession>( intent.target, diff --git a/src/renderer/src/lib/structured-agent-session-launch-errors.ts b/src/renderer/src/lib/structured-agent-session-launch-errors.ts index bf03c9105708..d60aaf523177 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-errors.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-errors.ts @@ -24,6 +24,9 @@ export class StructuredAgentSessionCreateRefusalError extends StructuredAgentSes } } +/** The source disappeared before any create was sent; no host cancellation is owed. */ +export class StructuredAgentSessionCreateAbandonedError extends StructuredAgentSessionCreateRefusalError {} + /** * Refused with a code that does not prove the session is absent. A sibling opened here would sit * beside a session the host may already hold, so this deliberately is NOT a refusal error: it flows diff --git a/src/renderer/src/lib/structured-agent-session-launch.ts b/src/renderer/src/lib/structured-agent-session-launch.ts index 11468d845d99..ae5848f11db8 100644 --- a/src/renderer/src/lib/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/structured-agent-session-launch.ts @@ -68,9 +68,11 @@ export { useStructuredAgentSessionLaunchSelection } from './structured-agent-ses type StructuredLaunchStateResult = { state: StructuredLaunchState caller: StructuredLaunchCaller + joined: boolean } export type StructuredAgentLaunchResult = { + joined: boolean sessionId: string executionHostId: ExecutionHostId launchResult: Promise @@ -182,7 +184,7 @@ function joinStructuredLaunchState( stagedPrompt }) trackStructuredLaunchPromptOutcome(existing, caller) - return { state: existing, caller } + return { state: existing, caller, joined: true } } function structuredAgentLaunchState( @@ -204,6 +206,7 @@ function structuredAgentLaunchState( options.resumeFrom, options.hostSeedOptions ) + intent.beforeCreate = options.beforeCreate const text = launchPromptText(options) const stagedPrompt = text ? stageStructuredLaunchPrompt(intent.sessionId, text, promptOwner(options)) @@ -241,7 +244,8 @@ function structuredAgentLaunchState( trackLaunchSettlement(state, state.promise) return { state, - caller + caller, + joined: false } } @@ -263,8 +267,9 @@ export function startStructuredAgentLaunch( agent: TuiAgent, options: StructuredAgentLaunchOptions ): StructuredAgentLaunchResult { - const { state, caller } = structuredAgentLaunchState(worktreeId, agent, options) + const { state, caller, joined } = structuredAgentLaunchState(worktreeId, agent, options) return { + joined, sessionId: state.intent.sessionId, executionHostId: state.intent.executionHostId, launchResult: state.promise, diff --git a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts index ab416b89298f..6b5f1caa057a 100644 --- a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts +++ b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts @@ -24,6 +24,18 @@ import { structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' +import { holdEmptyWorkspaceDefaultSurfaceForLaunch } from './empty-workspace-default-surface-claims' +import { + clearWebSessionFocusIntentIfMatches, + peekWebSessionFocusIntent, + resolveWebSessionVisibleTabId +} from '@/runtime/web-session-focus-intent' +import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' +import { + deleteStructuredLaunchStateIfCurrent, + getStructuredLaunchStateBySessionId, + notifyStructuredLaunchListeners +} from './structured-agent-session-launch-registry' type LocalProvisionalLaunch = StructuredAgentLaunchHandle & { tab: Tab } @@ -31,6 +43,7 @@ type LocalProvisionalLaunch = StructuredAgentLaunchHandle & { tab: Tab } export type StructuredAgentSessionProvisionalLaunch = | LocalProvisionalLaunch | HostAdmittedStructuredLaunch + | (StructuredAgentLaunchHandle & { tab: null }) export function openStructuredAgentSessionProvisionalTab(args: { worktreeId: string @@ -45,9 +58,9 @@ export function openStructuredAgentSessionProvisionalTab(args: { const tabId = structuredAgentSessionTabId(args.sessionId) const existing = (state.unifiedTabsByWorktree[args.worktreeId] ?? []).find( (candidate) => - candidate.id === tabId && candidate.contentType === 'agent-session' && - candidate.entityId === args.sessionId + candidate.entityId === args.sessionId && + (!candidate.executionHostId || candidate.executionHostId === args.executionHostId) ) if (existing) { if (args.activate !== false) { @@ -95,6 +108,8 @@ type ProvisionalLaunchArgs = { target?: AgentSessionLaunchTarget targetGroupId?: string activate?: boolean + /** Identity-only resumes publish on commit; unknown outcomes keep their recovery tab. */ + deferPublication?: true /** Lets workspace flows reveal before the chat's tab is owned: before its host is asked, when no * session id exists yet. */ beforeOpen?: (sessionId?: string) => boolean | void @@ -116,7 +131,7 @@ export function beginStructuredAgentSessionProvisionalLaunch( // No host to ask: the launch path refuses it with its own message. return beginLocalProvisionalLaunch(args) } - if (args.beforeOpen?.() === false) { + if (!args.deferPublication && args.beforeOpen?.() === false) { return null } return beginHostAdmittedStructuredLaunch({ @@ -148,7 +163,12 @@ export function beginStructuredAgentSessionProvisionalLaunch( }) } -function beginLocalProvisionalLaunch(args: ProvisionalLaunchArgs): LocalProvisionalLaunch | null { +function beginLocalProvisionalLaunch( + args: ProvisionalLaunchArgs +): LocalProvisionalLaunch | (StructuredAgentLaunchHandle & { tab: null }) | null { + if (args.deferPublication) { + return beginDeferredPublication(args) + } const handle = args.plan.begin(args.hooks, args.target) if (!handle) { return null @@ -177,3 +197,59 @@ function beginLocalProvisionalLaunch(args: ProvisionalLaunchArgs): LocalProvisio throw error } } + +function beginDeferredPublication( + args: ProvisionalLaunchArgs +): (StructuredAgentLaunchHandle & { tab: null }) | null { + const worktreeId = args.target?.worktreeId ?? args.plan.worktreeId + if (!worktreeId || !args.plan.resumeFrom || args.plan.prompt) { + throw new Error('Deferred publication requires an identity-only resume.') + } + const releaseHold = holdEmptyWorkspaceDefaultSurfaceForLaunch(worktreeId) + let handle: StructuredAgentLaunchHandle | null + try { + handle = args.plan.begin(args.hooks, args.target) + } catch (error) { + releaseHold() + throw error + } + if (!handle) { + releaseHold() + return null + } + const launch = handle + const target = structuredAgentSessionTargetForHost(launch.executionHostId) + const settlement = launch.settlement + .then((result) => { + if (result.kind === 'structured' || result.kind === 'visibility-unknown') { + const state = useAppStore.getState() + const owner = target && structuredAgentSessionFocusOwner(target) + const focus = owner && peekWebSessionFocusIntent(owner, worktreeId) + const hostTabId = `agent-session:${launch.sessionId}` + const activate = + args.activate !== false && + focus?.hostTabId === hostTabId && + (focus.expectedCurrentLocalTabId === undefined || + focus.expectedCurrentLocalTabId === resolveWebSessionVisibleTabId(state, worktreeId)) + openStructuredAgentSessionProvisionalTab({ + worktreeId, + executionHostId: launch.executionHostId, + sessionId: launch.sessionId, + agent: args.plan.agent, + ...(args.targetGroupId ? { targetGroupId: args.targetGroupId } : {}), + activate + }) + if (owner) { + clearWebSessionFocusIntentIfMatches(owner, worktreeId, hostTabId) + } + } else if (!launch.joined && (result.kind === 'failed' || result.kind === 'cancelled')) { + const failed = getStructuredLaunchStateBySessionId(launch.sessionId) + if (failed?.callers.outcome === 'failed' && deleteStructuredLaunchStateIfCurrent(failed)) { + notifyStructuredLaunchListeners() + } + } + return result + }) + .finally(releaseHold) + return { ...launch, tab: null, settlement } +} diff --git a/src/renderer/src/runtime/structured-agent-session-client.ts b/src/renderer/src/runtime/structured-agent-session-client.ts index eb12f827567d..06b4d6ff9f8d 100644 --- a/src/renderer/src/runtime/structured-agent-session-client.ts +++ b/src/renderer/src/runtime/structured-agent-session-client.ts @@ -13,6 +13,7 @@ import { AGENT_SESSION_QUESTION_ANSWERS_RUNTIME_CAPABILITY, AGENT_SESSION_REWIND_RUNTIME_CAPABILITY, AGENT_SESSION_REPEATED_STOP_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY, type RuntimeCapability } from '../../../shared/protocol-version' import { AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY } from '../../../shared/agent-session-create-capabilities' @@ -54,6 +55,15 @@ export function supportsStructuredAgentSessionCreateMessage( return structuredAgentSessionHostSupports(target, AGENT_SESSION_CREATE_MESSAGE_RUNTIME_CAPABILITY) } +export function supportsStructuredAgentSessionCliSource( + target: RuntimeClientTarget +): Promise { + return structuredAgentSessionHostSupports( + target, + STRUCTURED_AGENT_SESSION_CLI_SOURCE_RUNTIME_CAPABILITY + ) +} + /** Whether the host writes no row for a Stop that stopped nothing, so a repeated Stop is quiet. */ export function supportsStructuredAgentSessionQuietRepeatedStop( target: RuntimeClientTarget From 2a17fbb1b5f613bfc2a4c8a70dc639c5c527a17f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:33:58 -0700 Subject: [PATCH 15/38] fix(native-chat): preserve resume refusal behavior and honest transcript feedback --- .../journal-legacy-import.ts | 26 +++++++++++----- ...structured-agent-session-adopted-import.ts | 2 +- ...ured-agent-session-create-adoption.test.ts | 6 ++-- .../native-chat/transcript-opencode.test.ts | 16 +++++++++- src/main/native-chat/transcript-opencode.ts | 6 +++- src/main/native-chat/transcript-reader.ts | 1 + ...ault-session-resume-in-chat-launch.test.ts | 15 ++++++++-- .../ai-vault-session-resume-in-chat-launch.ts | 30 ++++++++++++++++--- ...red-agent-session-launch-admission.test.ts | 10 +++---- ...ructured-agent-session-launch-admission.ts | 23 +++++++++----- ...ctured-agent-session-launch-create-call.ts | 3 +- .../agent-session-definitive-refusal.ts | 1 - src/shared/agent-session-refusal-details.ts | 7 +---- .../agent-session-refusal-reason-words.ts | 1 - 14 files changed, 102 insertions(+), 45 deletions(-) diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index e69abd28a676..6fb11768c245 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -63,6 +63,10 @@ export type LegacyImportResult = } | { ok: false; error: string } +type PreparedLegacyImport = + | { ok: true; items: JournalReplacementItem[]; sourceEmpty: boolean } + | { ok: false; error: string } + export async function importLegacyTranscriptIntoJournal(input: { journal: AgentSessionJournal agent: AgentType @@ -87,7 +91,7 @@ export async function prepareLegacyTranscriptImport(input: { agent: AgentType sessionId: string options?: LegacyImportOptions -}): Promise<{ ok: true; items: JournalReplacementItem[] } | { ok: false; error: string }> { +}): Promise { const options = input.options ?? {} const limits = options.limits ?? DEFAULT_JOURNAL_PAYLOAD_LIMITS // OMP is a Pi fork that kept Pi's session format, so OMP's decoder reads Pi's sessions too. @@ -136,7 +140,8 @@ export async function prepareLegacyTranscriptImport(input: { if (decoded.identities.length !== decoded.messages.length) { return { ok: false, error: 'Legacy transcript identity coverage is incomplete' } } - return { ok: true, items: replacementItems(decoded.messages, decoded.identities, limits) } + const items = replacementItems(decoded.messages, decoded.identities, limits) + return { ok: true, items, sourceEmpty: decoded.consumedBytes === 0 } } /** OpenCode keeps conversations in a database (`filePath` names it), read by the reader its @@ -146,7 +151,7 @@ async function prepareOpenCodeImport(input: { sessionId: string options?: LegacyImportOptions limits: JournalPayloadLimits -}): Promise<{ ok: true; items: JournalReplacementItem[] } | { ok: false; error: string }> { +}): Promise { const dbPath = input.options?.filePath const read = await readOpenCodeNativeChatTranscriptFull( input.sessionId, @@ -161,7 +166,8 @@ async function prepareOpenCodeImport(input: { sessionId: input.sessionId, recordId: message.id })) - return { ok: true, items: replacementItems(read.messages, identities, input.limits) } + const items = replacementItems(read.messages, identities, input.limits) + return { ok: true, items, sourceEmpty: read.sourceEmpty === true } } function replacementItems( @@ -201,7 +207,11 @@ async function decodeWithIdentities(input: { agent: AgentType sessionId: string decodedMessageIdentities?: true -}): Promise<{ messages: NativeChatMessage[]; identities: AgentJournalItemIdentity[] }> { +}): Promise<{ + messages: NativeChatMessage[] + identities: AgentJournalItemIdentity[] + consumedBytes: number +}> { const tracker = createLegacyIdentityTracker({ transcriptAgent: input.transcriptAgent, agent: input.agent, @@ -214,7 +224,7 @@ async function decodeWithIdentities(input: { // Count raw bytes while reading: the source can grow after the stat check. const stream = createReadStream(input.filePath) - const { messages } = await decodeTranscriptStream( + const { messages, consumedBytes } = await decodeTranscriptStream( stream, input.filePath, 0, @@ -244,9 +254,9 @@ async function decodeWithIdentities(input: { MAX_LEGACY_IMPORT_SOURCE_BYTES ) if (pi) { - return pi.project() + return { ...pi.project(), consumedBytes } } - return { messages, identities } + return { messages, identities, consumedBytes } } /** diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts index fe4db165d609..376b532770fe 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-adopted-import.ts @@ -57,7 +57,7 @@ async function readAdoptedTranscript( } if (prepared.items.length === 0) { throw agentSessionRefusalError('agent_session_identity_required', { - reason: 'transcriptEmpty' + reason: prepared.sourceEmpty ? 'transcriptNotFound' : 'transcriptUnreadable' }) } return prepared.items diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index 74bb802e599f..dc97dc6f89ac 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -146,18 +146,18 @@ it('refuses concurrent founding under a tab another chat already owns', async () expect(rig.adapter.acquire).not.toHaveBeenCalled() }) -it.each(['missing', 'empty'] as const)( +it.each(['missing', 'empty', 'malformed'] as const)( 'refuses %s history before founding anything', async (source) => { const params = await adoptedParams() await (source === 'missing' ? rm(join(rig.root, 'rollout.jsonl')) - : writeFile(join(rig.root, 'rollout.jsonl'), '')) + : writeFile(join(rig.root, 'rollout.jsonl'), source === 'empty' ? '' : '{broken json}\n')) expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false, refusal: { code: 'agent_session_identity_required', - details: { reason: source === 'missing' ? 'transcriptUnreadable' : 'transcriptEmpty' }, + details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, createAttemptRefusedBeforeCommit: true } }) diff --git a/src/main/native-chat/transcript-opencode.test.ts b/src/main/native-chat/transcript-opencode.test.ts index 7b49dcac3f26..0c2223ea40e8 100644 --- a/src/main/native-chat/transcript-opencode.test.ts +++ b/src/main/native-chat/transcript-opencode.test.ts @@ -54,7 +54,7 @@ describe('readOpenCodeNativeChatTranscriptFull', () => { resolveDbPath: async () => '/fake/opencode.db', readPage }) - expect(result).toEqual({ messages: ids.map(message) }) + expect(result).toEqual({ messages: ids.map(message), sourceEmpty: false }) }) it('reports notFound when the first page misses', async () => { @@ -66,6 +66,20 @@ describe('readOpenCodeNativeChatTranscriptFull', () => { expect(result).toEqual({ error: 'Transcript unavailable', notFound: true }) }) + it.each([ + [null, true], + [42, false] + ])( + 'distinguishes no raw rows from undecodable rows at cursor %s', + async (cursor, sourceEmpty) => { + const result = await readOpenCodeNativeChatTranscriptFull('ses-1', { + resolveDbPath: async () => '/fake/opencode.db', + readPage: async () => ({ items: [], hasMore: false, beforeMessageRowId: cursor }) + }) + expect(result).toEqual({ messages: [], sourceEmpty }) + } + ) + it('reads the selected ZCode store on every full-read page', async () => { const resolveDbPath = vi.fn(async () => '/fake/zcode.db') const readPage = vi.fn(async () => ({ items: [], hasMore: false, beforeMessageRowId: null })) diff --git a/src/main/native-chat/transcript-opencode.ts b/src/main/native-chat/transcript-opencode.ts index 93f14b3bbc63..f58a8d73707a 100644 --- a/src/main/native-chat/transcript-opencode.ts +++ b/src/main/native-chat/transcript-opencode.ts @@ -107,6 +107,7 @@ export async function readOpenCodeNativeChatTranscriptFull( let records = 0 let bytes = 0 let cursor: number | undefined + let sourceEmpty = false try { const dbPath = await (deps.resolveDbPath ?? openCodeTranscriptDefaultDeps.resolveDbPath)( sessionId, @@ -134,6 +135,9 @@ export async function readOpenCodeNativeChatTranscriptFull( } break } + if (pages.length === 0) { + sourceEmpty = page.beforeMessageRowId === null && !page.hasMore + } pages.push(page.items.map((item) => item.message)) records += page.items.length bytes += Buffer.byteLength(JSON.stringify(page.items)) @@ -148,5 +152,5 @@ export async function readOpenCodeNativeChatTranscriptFull( } catch (err) { return { error: errorMessage(err) } } - return { messages: pages.toReversed().flat() } + return { messages: pages.toReversed().flat(), sourceEmpty } } diff --git a/src/main/native-chat/transcript-reader.ts b/src/main/native-chat/transcript-reader.ts index b90b8681b445..15ffcff614db 100644 --- a/src/main/native-chat/transcript-reader.ts +++ b/src/main/native-chat/transcript-reader.ts @@ -22,6 +22,7 @@ export type ReadTranscriptResult = | { messages: NativeChatMessage[] lifecycle?: NativeChatTurnLifecycle + sourceEmpty?: boolean } // notFound marks a retry-worthy miss (transcript not flushed to disk yet, // #8401) as opposed to a real parse/IO error callers surface immediately. diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.test.ts index ba29f3cd9d85..9a90f4dd63d5 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.test.ts @@ -103,13 +103,22 @@ describe('resumeAiVaultSessionInNewChat', () => { }) it.each([ - ['agent_session_conflict', 'Another chat is already holding this conversation.'], + ['agent_session_conflict', undefined, 'Another chat is already holding this conversation.'], [ 'agent_session_identity_required', + 'transcriptNotFound', + "Codex hasn't saved this conversation yet. Try again after it replies." + ], + [ + 'agent_session_identity_required', + 'transcriptUnreadable', "This conversation's history could not be loaded, so it cannot be resumed in chat." ] - ])('toasts the eventual %s refusal', async (code, message) => { - const error = Object.assign(new Error('Host diagnostic'), { code }) + ])('toasts the eventual %s refusal', async (code, reason, message) => { + const error = Object.assign(new Error('Host diagnostic'), { + code, + ...(reason ? { refusal: { code, details: { reason } } } : {}) + }) mocks.beginStructuredAgentSessionProvisionalLaunch.mockReturnValue({ sessionId: 'session-1', tab: { id: 'agent-session:session-1' }, diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts index 9ed8845851ee..6c3e06ccedf7 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts @@ -2,6 +2,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import type { AiVaultSession } from '../../../../shared/ai-vault-types' +import { agentLabel } from '../../../../shared/ai-vault-session-filters' import { CLI_CONVERSATION_ADOPTING_AGENTS, type CliConversationRowAgent @@ -12,6 +13,7 @@ import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session-launch-plan' import type { AgentLaunchRequestId } from '@/lib/agent-launch-request-id' import { activateAndRevealWorkspace } from '@/lib/worktree-activation' import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/structured-agent-session-provisional-tab' +import { structuredLaunchFailure } from '@/lib/structured-agent-session-launch-failure' export function activateAiVaultResumeWorkspace(workspaceId: string): boolean { return activateAndRevealWorkspace(workspaceId) !== false @@ -51,19 +53,22 @@ export async function resumeAiVaultSessionInNewChat( if (launch) { void launch.settlement.then((settlement) => { if (settlement.kind === 'failed' && !settlement.notified) { - notifyAiVaultSessionResumeInChatFailure(settlement.error) + notifyAiVaultSessionResumeInChatFailure(settlement.error, rowAgent) } }) } } catch (error) { - notifyAiVaultSessionResumeInChatFailure(error) + notifyAiVaultSessionResumeInChatFailure(error, rowAgent) } } /** The host refuses an adoption whose conversation another chat already holds, and refuses one it * cannot find under any account home it recognises. Both are actionable, and neither is the * generic "could not prepare" the terminal resume reports. */ -function notifyAiVaultSessionResumeInChatFailure(error: unknown): void { +function notifyAiVaultSessionResumeInChatFailure( + error: unknown, + rowAgent: CliConversationRowAgent +): void { if (hasRuntimeRpcErrorCode(error, 'agent_session_conflict')) { toast.error( translate( @@ -73,7 +78,24 @@ function notifyAiVaultSessionResumeInChatFailure(error: unknown): void { ) return } - if (hasRuntimeRpcErrorCode(error, 'agent_session_identity_required')) { + const failure = structuredLaunchFailure(error) + if ( + failure?.code === 'agent_session_identity_required' && + failure.details?.reason === 'transcriptNotFound' + ) { + toast.error( + translate( + 'components.native-chat.resumeInNewChat.notSavedYet', + "{{agent}} hasn't saved this conversation yet. Try again after it replies.", + { agent: agentLabel(rowAgent) } + ) + ) + return + } + if ( + failure?.code === 'agent_session_identity_required' || + hasRuntimeRpcErrorCode(error, 'agent_session_identity_required') + ) { toast.error( translate( 'auto.components.right.sidebar.AiVaultPanel.resumeInChatTranscriptMissing', diff --git a/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts b/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts index b62c665177cd..15dbbfbedf51 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-admission.test.ts @@ -150,7 +150,7 @@ describe('a structured chat launch on a paired server', () => { expectNoChatCommitted() }) - it('sends a resume to create even when the fresh-launch probe would decline', async () => { + it('leaves no destination when the server declines a resume', async () => { mocks.createSupport.mockResolvedValue({ supported: false }) const onHostDeclined = vi.fn() const launch = beginStructuredAgentSessionProvisionalLaunch({ @@ -158,12 +158,10 @@ describe('a structured chat launch on a paired server', () => { hooks: {}, onHostDeclined }) - await vi.waitFor(() => - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toHaveLength(1) - ) - expect(mocks.createSupport).not.toHaveBeenCalled() + await expect(launch?.settlement).resolves.toMatchObject({ kind: 'failed' }) + expect(mocks.createSupport).toHaveBeenCalledOnce() expect(onHostDeclined).not.toHaveBeenCalled() - launch?.cancel() + expectNoChatCommitted() }) // The picker shows what create will run: the server's saved selection, not this machine's. diff --git a/src/renderer/src/lib/structured-agent-session-launch-admission.ts b/src/renderer/src/lib/structured-agent-session-launch-admission.ts index d10c8a7c24d8..f67a67491925 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-admission.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-admission.ts @@ -22,6 +22,7 @@ import type { StructuredPromptDeliveryResult } from '@/lib/structured-agent-sess import type { LaunchAgentInNewTabArgs } from '@/lib/launch-agent-in-new-tab' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' +import { StructuredAgentSessionCreateRefusalError } from './structured-agent-session-launch-errors' /** What a host's "no" opens instead: the terminal the launch would have opened had it known. */ export type StructuredLaunchTerminal = { @@ -160,14 +161,11 @@ export function beginHostAdmittedStructuredLaunch(args: { const releaseHold = holdEmptyWorkspaceDefaultSurfaceForLaunch(args.worktreeId) const settlement = (async (): Promise => { try { - // Resuming asks create for the existing owner before fresh-launch prerequisites. - const asked: StructuredLaunchAdmission = plan.resumeFrom - ? { kind: 'admitted' } - : await admitStructuredLaunchOnHost( - args.target, - toRuntimeWorktreeSelector(args.worktreeId), - plan.agent - ) + const asked = await admitStructuredLaunchOnHost( + args.target, + toRuntimeWorktreeSelector(args.worktreeId), + plan.agent + ) if (isCancelled()) { resolveDelivery(NOT_DELIVERED) return { kind: 'cancelled', sessionId: null } @@ -190,6 +188,15 @@ export function beginHostAdmittedStructuredLaunch(args: { } } if (admission.kind === 'declined') { + if (plan.resumeFrom) { + resolveDelivery(NOT_DELIVERED) + return { + kind: 'failed', + error: new StructuredAgentSessionCreateRefusalError( + 'structured_agent_session_unsupported' + ) + } + } // The notice explains a server's refusal; on this machine the terminal opening is the answer. if (paired) { notifyHostDeclined(plan.agent) diff --git a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts index e31be1214987..93bdfdc1a9b3 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-create-call.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-create-call.ts @@ -84,8 +84,7 @@ export async function launchStructuredAgentSession( onHostSeed?: StructuredLaunchHostSeedListener, priorCreateOutcomeUnknown = false ): Promise { - // A resume's owner must answer even when a fresh launch is unavailable. - const hostSeed = intent.params.resumeFrom ? undefined : await requireHostCreateSupport(intent) + const hostSeed = await requireHostCreateSupport(intent) if (intent.target.kind !== 'local') { onHostSeed?.(hostSeed) } diff --git a/src/shared/agent-session-definitive-refusal.ts b/src/shared/agent-session-definitive-refusal.ts index ddbfc33e6d7b..80bf18e6de10 100644 --- a/src/shared/agent-session-definitive-refusal.ts +++ b/src/shared/agent-session-definitive-refusal.ts @@ -24,7 +24,6 @@ export function isAgentSessionCreateAdmissionRefusal( refusal.details?.reason === 'conversationHeldElsewhere') || (refusal.code === 'agent_session_identity_required' && (refusal.details?.reason === 'transcriptNotFound' || - refusal.details?.reason === 'transcriptEmpty' || refusal.details?.reason === 'transcriptUnreadable')) ) } diff --git a/src/shared/agent-session-refusal-details.ts b/src/shared/agent-session-refusal-details.ts index 2301fbddf990..dfa929eeced6 100644 --- a/src/shared/agent-session-refusal-details.ts +++ b/src/shared/agent-session-refusal-details.ts @@ -116,12 +116,7 @@ export const AGENT_SESSION_REFUSAL_REASONS = { ], execution_owner_reconciling: ['hostReconciling', 'recordUnreadable'], agent_session_checkpoint_stale: ['fenceStale', 'leaseMoved', 'recordMissing'], - agent_session_identity_required: [ - 'recordMissing', - 'transcriptNotFound', - 'transcriptEmpty', - 'transcriptUnreadable' - ], + agent_session_identity_required: ['recordMissing', 'transcriptNotFound', 'transcriptUnreadable'], agent_session_operation_conflict: ['fingerprintMismatch', 'operationIdReused', 'handoffInFlight'], agent_session_operation_expired: ['operationExpired'], agent_session_operation_capacity: ['operationCapacity'], diff --git a/src/shared/agent-session-refusal-reason-words.ts b/src/shared/agent-session-refusal-reason-words.ts index 64a50e96157f..6cc7ced2e6e7 100644 --- a/src/shared/agent-session-refusal-reason-words.ts +++ b/src/shared/agent-session-refusal-reason-words.ts @@ -157,7 +157,6 @@ const REASON_WORDS = { agent_session_identity_required: { recordMissing: causeWords('chatNotFound', 'goElsewhere', 'startNewChat'), transcriptNotFound: codeWords('retry'), - transcriptEmpty: codeWords('retry'), transcriptUnreadable: causeWords('historyUnavailable', 'retry', 'tryAgain') }, agent_session_operation_conflict: { From 876c72ce9ab1c563a21cbd2b1b4b6daae8215002 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:34:46 -0700 Subject: [PATCH 16/38] fix(native-chat): retain import read evidence in typed result --- .../native-chat/agent-session-journal/journal-legacy-import.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index 6fb11768c245..c486f68edba9 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -124,7 +124,7 @@ export async function prepareLegacyTranscriptImport(input: { return { ok: false, error: err instanceof Error ? err.message : String(err) } } - let decoded: { messages: NativeChatMessage[]; identities: AgentJournalItemIdentity[] } + let decoded: Awaited> try { decoded = await decodeWithIdentities({ filePath, From 17d63f742eeec398b82547d179d851b7727d5c09 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:35:32 -0700 Subject: [PATCH 17/38] Use the header test fixture record type --- .../terminal-pane/TerminalPaneResumeInChatButton.test.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx index 667645494f14..7a62aaadd400 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneResumeInChatButton.test.tsx @@ -17,7 +17,9 @@ const mocks = vi.hoisted(() => ({ run: vi.fn(), pending: false })) -vi.mock('@/store', () => ({ useAppStore: (selector: (state: object) => unknown) => selector({}) })) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: Record) => unknown) => selector({}) +})) vi.mock('../tab-bar/cli-chat-resume-source', () => ({ resolveCliChatResumeSource: (_state: unknown, args: unknown) => { mocks.resolve(args) From e899665d5a9e1b58fd289df11e037a00054a0d57 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:37:59 -0700 Subject: [PATCH 18/38] Consolidate launch owner imports and correct feedback assertion --- src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts | 2 +- .../src/lib/structured-agent-session-provisional-tab.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index 5ff0e8e4849a..11a53bed656f 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -156,7 +156,7 @@ describe('CLI identity resume through the existing launch owner', () => { expect(tabs()).toEqual([]) expect([...structuredLaunchStates()]).toEqual([]) expect(mocks.toast.mock.calls.at(-1)?.[0]).toMatch( - reason === 'transcriptUnreadable' ? /history.*could not/i : /hasn't saved/ + reason === 'transcriptUnreadable' ? /couldn't open.*history/i : /hasn't saved/ ) } }) diff --git a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts index 6b5f1caa057a..48dedba95966 100644 --- a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts +++ b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts @@ -21,6 +21,7 @@ import { } from '@/lib/structured-agent-session-launch-admission' import { resolveStructuredAgentSessionOwner, + structuredAgentSessionFocusOwner, structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' @@ -30,7 +31,6 @@ import { peekWebSessionFocusIntent, resolveWebSessionVisibleTabId } from '@/runtime/web-session-focus-intent' -import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' import { deleteStructuredLaunchStateIfCurrent, getStructuredLaunchStateBySessionId, From 3bb26b8d2ae695dbb9d273336c09e84bdfc113e8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:42:28 -0700 Subject: [PATCH 19/38] Keep existing resume translation in runtime catalog --- src/renderer/src/i18n/en-runtime-required.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 5a3863f6759b..ca3dcfeae7ff 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2949,6 +2949,9 @@ "sendConfirmBody_one": "You are about to send a message. Do you want to clear the {{count}} message previously queued?", "sendConfirmBody_other": "You are about to send a message. Do you want to clear the {{count}} messages previously queued?" }, + "resumeInNewChat": { + "cannotResume": "This {{agent}} conversation can't be resumed in a native chat." + }, "state": { "empty": { "subtitle": "Ask {{value0}} to inspect code, explain output, or make a change.", From 837aea0dead374ca558c6d38b27ef5ba64eb1d09 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:55:28 -0700 Subject: [PATCH 20/38] fix(native-chat): preserve admitted source and prepared execution home --- .../codex/codex-ai-vault-session-resume.ts | 18 ++++++ .../adopted-transcript-source.ts | 26 ++++---- .../journal-legacy-import.ts | 6 +- .../native-chat/codex-adoption-preparation.ts | 9 +-- ...red-agent-session-source-admission.test.ts | 60 ++++++++++++++++--- .../orca-runtime-preserved-branch-cleanup.ts | 9 +-- src/main/runtime/orca-runtime-state-fields.ts | 9 +-- ...tructured-agent-session-create-adoption.ts | 34 +++++------ .../startup/main-process-runtime-service.ts | 13 ++-- 9 files changed, 118 insertions(+), 66 deletions(-) diff --git a/src/main/codex/codex-ai-vault-session-resume.ts b/src/main/codex/codex-ai-vault-session-resume.ts index 3a4201060dca..908587829943 100644 --- a/src/main/codex/codex-ai-vault-session-resume.ts +++ b/src/main/codex/codex-ai-vault-session-resume.ts @@ -27,6 +27,24 @@ type CodexAiVaultResumeOptions = { preparePinnedLaunchHome: (home: string) => Promise } +export type NativeCodexResumePreparation = ( + args: AiVaultPrepareSessionResumeArgs, + nativeSystemHomePath?: string +) => Promise + +/** Native adoption supplies its execution target; History keeps its configured storage target. */ +export function codexAiVaultSessionResumePreparation( + getOptions: () => CodexAiVaultResumeOptions +): NativeCodexResumePreparation { + return (args, nativeSystemHomePath) => { + const options = getOptions() + return prepareCodexAiVaultSessionResume(args, { + ...options, + systemCodexHomePath: nativeSystemHomePath ?? options.systemCodexHomePath + }) + } +} + /** Keeps window and serve AI Vault resumes behind the same refusing account-home gate. */ export async function prepareCodexAiVaultSessionResume( args: AiVaultPrepareSessionResumeArgs, diff --git a/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts index bf0aa5cb8598..7cdedc6c12e1 100644 --- a/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts +++ b/src/main/native-chat/agent-session-journal/adopted-transcript-source.ts @@ -29,7 +29,7 @@ export function assertAdoptedSourceIdentity( } /** Metadata is observed from the same lines that become the imported journal. */ -export async function adoptedTranscriptSourceObserver(input: { +export function adoptedTranscriptSourceObserver(input: { agent: AgentType filePath: string source: AdoptedTranscriptSource @@ -39,18 +39,6 @@ export async function adoptedTranscriptSourceObserver(input: { input.agent === 'claude' || input.agent === 'codex' ? sessionIdFromFileName(input.filePath) : null let cwd: string | null = null let sawCodexMetadata = false - if (input.agent === 'grok') { - const summaryPath = join(dirname(input.filePath), 'summary.json') - if (!(await admitTranscriptPath(dirname(input.filePath), summaryPath))) { - throw new Error('The conversation summary is outside its storage directory.') - } - const { buffer } = await readNodeFileWithinLimit(summaryPath, input.maxSourceBytes, { - regularFileOnly: true - }) - const summary = asRecord(asRecord(JSON.parse(buffer.toString('utf8')))?.info) - sessionId = extractString(summary?.id) ?? sessionIdFromFileName(dirname(input.filePath)) - cwd = extractString(summary?.cwd) - } return { observe(line: string) { const record = parseJsonObject(line) @@ -70,6 +58,18 @@ export async function adoptedTranscriptSourceObserver(input: { } }, async validate() { + if (input.agent === 'grok') { + const summaryPath = join(dirname(input.filePath), 'summary.json') + if (!(await admitTranscriptPath(dirname(input.filePath), summaryPath))) { + throw new Error('The conversation summary is outside its storage directory.') + } + const { buffer } = await readNodeFileWithinLimit(summaryPath, input.maxSourceBytes, { + regularFileOnly: true + }) + const summary = asRecord(asRecord(JSON.parse(buffer.toString('utf8')))?.info) + sessionId = extractString(summary?.id) ?? sessionIdFromFileName(dirname(input.filePath)) + cwd = extractString(summary?.cwd) + } if (input.agent === 'pi' && sessionIdFromFileName(input.filePath) !== sessionId) { throw new Error('The saved conversation header does not match its file identity.') } diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index f2f4966e3b31..7732eda9f75c 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -226,7 +226,7 @@ async function decodeWithIdentities(input: { identities: AgentJournalItemIdentity[] consumedBytes: number }> { - const source = input.source ? await adoptedTranscriptSourceObserver({ + const source = input.source ? adoptedTranscriptSourceObserver({ agent: input.agent, filePath: input.filePath, source: input.source, maxSourceBytes: MAX_LEGACY_IMPORT_SOURCE_BYTES }) : null @@ -272,7 +272,9 @@ async function decodeWithIdentities(input: { true, MAX_LEGACY_IMPORT_SOURCE_BYTES ) - await source?.validate() + if (consumedBytes > 0) { + await source?.validate() + } if (pi) { return { ...pi.project(), consumedBytes } } diff --git a/src/main/native-chat/codex-adoption-preparation.ts b/src/main/native-chat/codex-adoption-preparation.ts index 0d903129e86d..0e86904abdd9 100644 --- a/src/main/native-chat/codex-adoption-preparation.ts +++ b/src/main/native-chat/codex-adoption-preparation.ts @@ -4,7 +4,7 @@ import { isLegacyAgentSessionAccountHome, type AgentSessionAccountHome } from '../../shared/agent-session-account-home' -import type { AiVaultSessionResumePreparation } from '../../shared/ai-vault-resume-preparation' +import type { NativeCodexResumePreparation } from '../codex/codex-ai-vault-session-resume' import { getSystemCodexHomePath } from '../codex/codex-home-paths' import type { StructuredAgentSessionAdoption } from './structured-agent-session-history-adoption' import { admitTranscriptPath } from './transcript-path-admission' @@ -14,20 +14,21 @@ import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-p export async function prepareCodexAdoption( source: StructuredAgentSessionAdoption, providerSessionId: string, - prepare: AiVaultSessionResumePreparation | undefined, + prepare: NativeCodexResumePreparation | undefined, recognizedHomes: readonly AgentSessionAccountHome[] ): Promise { if (!prepare || !isLegacyAgentSessionAccountHome(source.accountHome)) { return source } + const nativeSystemHomePath = getSystemCodexHomePath() const result = await prepare({ agent: 'codex', sessionId: providerSessionId, filePath: source.transcriptPath, codexHome: source.accountHome.path, executionHostId: 'local' - }) - const home = result.useRealCodexHome ? getSystemCodexHomePath() : result.substituteCodexHome + }, nativeSystemHomePath) + const home = result.useRealCodexHome ? nativeSystemHomePath : result.substituteCodexHome if ( !home || normalizeRuntimePathForComparison(home) === diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index 0a485875f5a2..6402cbc4b03a 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -10,7 +10,7 @@ import type { AgentSessionAttachParams } from './agent-session-wire/structured-a import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' import { prepareLegacyTranscriptImport } from './agent-session-journal/journal-legacy-import' import { prepareCodexAdoption } from './codex-adoption-preparation' -import { prepareLegacySharedCodexSessionResume } from '../codex/codex-legacy-session-resume' +import { codexAiVaultSessionResumePreparation } from '../codex/codex-ai-vault-session-resume' import * as codexHomes from '../codex/codex-home-paths' let root: string @@ -52,6 +52,17 @@ it('creates from the host hook path when Claude filename differs, then checks ac providerSession: { key: 'session_id', id, transcriptPath } }] }) const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! + const selectedAccountHome = { variable: 'CLAUDE_CONFIG_DIR', path: root } + vi.spyOn(importer, 'accountHomeCandidates').mockReturnValue([ + selectedAccountHome, { ...selectedAccountHome, path: join(root, 'locked-account') } + ]) + const admit = importer.admitTranscriptPath.bind(importer) + const admission = vi.spyOn(importer, 'admitTranscriptPath').mockImplementation((args) => { + if (!('path' in args.accountHome) || args.accountHome.path !== root) { + throw Object.assign(new Error('Account inaccessible'), { code: 'EACCES' }) + } + return admit(args) + }) const find = vi.spyOn(importer, 'findTranscript') const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, @@ -59,6 +70,7 @@ it('creates from the host hook path when Claude filename differs, then checks ac launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: sourcePath }) expect(adoption.transcriptPath).toBe(transcriptPath) + expect(admission).toHaveBeenCalledOnce() expect(find).not.toHaveBeenCalled() expect(await prepareAdoptedTranscript(params('claude', adoption.transcriptPath))).toMatchObject({ ok: true }) const wrongDirectory = params('claude', adoption.transcriptPath) @@ -78,11 +90,28 @@ it('creates from the host hook path when Claude filename differs, then checks ac selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: () => escaped })).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) + admission.mockRejectedValueOnce(Object.assign(new Error('Selected account inaccessible'), { code: 'EACCES' })) + await expect(resolveStructuredAgentSessionAdoptionForCreate({ + settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selectedAccountHome, launchEnv: {}, workspaceCwd: root, resolveTranscriptPath: sourcePath + })).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) expect(find).not.toHaveBeenCalled() }) +it.each(['claude', 'codex', 'grok', 'omp', 'pi'] as const)('retains empty versus unreadable source facts for %s', async (agent) => { + const transcript = join(root, `${id}.jsonl`) + await writeFile(transcript, '') + expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: false, + refusal: { details: { reason: 'transcriptNotFound' } } }) + for (const content of ['{broken json}\n', '{"type":"future_record"}\n']) { + await writeFile(transcript, content) + expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: false, + refusal: { details: { reason: 'transcriptUnreadable' } } }) + } +}) + it('checks canonical provider metadata during the existing import, including Codex copied parent metadata', async () => { - const codex = await file(join(root, 'rollout.jsonl'), [ + const codex = await file(join(root, `${id}.jsonl`), [ { type: 'session_meta', payload: { id } }, { type: 'session_meta', payload: { id: 'copied-parent' } }, { type: 'response_item', payload: { type: 'message', role: 'user', content: 'hello' } } @@ -103,24 +132,37 @@ it('checks canonical provider metadata during the existing import, including Cod await rm(join(root, id, 'summary.json')) expect(await prepareAdoptedTranscript(params('grok', grok))).toMatchObject({ ok: false, refusal: { details: { reason: 'transcriptUnreadable' } } }) - await writeFile(codex, '{malformed json') + await file(codex, [{ type: 'session_meta', payload: { id } }]) expect(await prepareLegacyTranscriptImport({ agent: 'codex', sessionId: id, - options: { filePath: codex, source: { providerSessionId: id, workspaceCwd: root } } })).toMatchObject({ ok: false }) + options: { filePath: codex } })).toMatchObject({ ok: true, items: [], sourceEmpty: false }) + expect(await prepareAdoptedTranscript(params('codex', codex))).toMatchObject({ ok: false, + refusal: { details: { reason: 'transcriptUnreadable' } } }) }) it('materializes legacy Codex into the system home and pins a verified selected account alias', async () => { - const legacy = join(root, 'legacy') + const legacy = codexHomes.getOrcaManagedCodexHomePath() const system = join(root, 'system') + const historyOnly = join(root, 'history-only') const selected = join(root, 'codex-accounts', 'selected', 'home') const suffix = join('sessions', '2026', '10', '15', `rollout-stamp-${id}.jsonl`) const transcriptPath = await file(join(legacy, suffix), [{ type: 'session_meta', payload: { id } }]) vi.spyOn(codexHomes, 'getSystemCodexHomePath').mockReturnValue(system) const source = { accountHome: { variable: 'CODEX_HOME' as const, path: legacy }, transcriptPath } - const migrated = await prepareCodexAdoption(source, id, - (args) => prepareLegacySharedCodexSessionResume(args, { - legacyCodexHomePath: legacy, systemCodexHomePath: system, isHostSystemDefaultRealHomeSelected: () => true - }), [source.accountHome]) + const prepare = codexAiVaultSessionResumePreparation(() => ({ + runtimeHome: { + isHostSystemDefaultRealHomeSelected: () => true, + resolveSelectedHostAccountCodexHomePathForResume: () => null, + getHostCodexHomePathsForSessionDiscovery: () => [legacy] + }, + systemCodexHomePath: historyOnly, preparePinnedLaunchHome: async () => {} + })) + const migrated = await prepareCodexAdoption(source, id, prepare, [source.accountHome]) expect(migrated).toEqual({ accountHome: { variable: 'CODEX_HOME', path: system }, transcriptPath: join(system, suffix) }) + await expect(prepareLegacyTranscriptImport({ agent: 'codex', sessionId: id, + options: { filePath: join(historyOnly, suffix) } })).resolves.toMatchObject({ ok: false }) + await prepare({ agent: 'codex', sessionId: id, filePath: transcriptPath, codexHome: legacy, executionHostId: 'local' }) + expect(await prepareLegacyTranscriptImport({ agent: 'codex', sessionId: id, + options: { filePath: join(historyOnly, suffix) } })).toMatchObject({ ok: true }) await file(join(selected, suffix), [{ type: 'session_meta', payload: { id } }]) expect(await prepareCodexAdoption(migrated, id, async () => ({ useRealCodexHome: false, substituteCodexHome: selected }), [{ variable: 'CODEX_HOME', path: selected }])).toEqual({ accountHome: { variable: 'CODEX_HOME', path: selected }, transcriptPath: join(selected, suffix) }) diff --git a/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts b/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts index 95e0dc289b22..9deaee049aed 100644 --- a/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts +++ b/src/main/runtime/orca-runtime-preserved-branch-cleanup.ts @@ -19,10 +19,7 @@ import type { StructuredAgentSessionStatusSink } from '../native-chat/agent-sess import type { ObservedAgentStatusPaneIdentity } from '../ipc/agent-status-ipc-boundary' import type { AgentHookAuthorityAttestation } from '../agent-hooks/server' import type { RuntimeDesktopWindowStatus } from '../../shared/runtime-types' -import type { - AiVaultPrepareSessionResumeArgs, - AiVaultPrepareSessionResumeResult -} from '../../shared/ai-vault-resume-preparation' +import type { NativeCodexResumePreparation } from '../codex/codex-ai-vault-session-resume' import type { AgentSessionClaimSigner } from './agent-session-claim-identity' import type { AgentStatus } from '../../shared/agent-detection' import { RuntimeLegacyWorkerTerminalRecoveryPersistence } from './runtime-legacy-worker-terminal-recovery-persistence' @@ -156,9 +153,7 @@ export abstract class OrcaRuntimeWithPreservedBranchCleanup extends OrcaRuntimeW protected readonly getDesktopWindowStatusFn: () => RuntimeDesktopWindowStatus - protected readonly prepareAiVaultSessionResumeFn: - | ((args: AiVaultPrepareSessionResumeArgs) => Promise) - | null + protected readonly prepareAiVaultSessionResumeFn: NativeCodexResumePreparation | null protected readonly prepareCodexStructuredLaunchFn: | ((input: { launchEnv: NodeJS.ProcessEnv }) => string | null | Promise) diff --git a/src/main/runtime/orca-runtime-state-fields.ts b/src/main/runtime/orca-runtime-state-fields.ts index 39b9869ba54f..bac23f69d390 100644 --- a/src/main/runtime/orca-runtime-state-fields.ts +++ b/src/main/runtime/orca-runtime-state-fields.ts @@ -12,10 +12,7 @@ import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' import type { StructuredAgentSessionStatusSink } from '../native-chat/agent-session-wire/structured-agent-session-status-feed' import type { ObservedAgentStatusPaneIdentity } from '../ipc/agent-status-ipc-boundary' import type { AgentHookAuthorityAttestation } from '../agent-hooks/server' -import type { - AiVaultPrepareSessionResumeArgs, - AiVaultPrepareSessionResumeResult -} from '../../shared/ai-vault-resume-preparation' +import type { NativeCodexResumePreparation } from '../codex/codex-ai-vault-session-resume' import type { RuntimeDesktopWindowStatus } from '../../shared/runtime-types' import type { AgentSessionClaimSigner } from './agent-session-claim-identity' import type { OrchestrationEnvironmentTransport } from './orchestration/environment-transport' @@ -103,9 +100,7 @@ export class OrcaRuntimeWithStateFields extends OrcaRuntimeWithLinearCommands { // runs under `orca serve`, so remote/SSH hosts would silently drop // managed-Codex sessions. The runtime ctor runs in BOTH window and serve. getAdditionalAiVaultCodexHomePaths?: () => readonly string[] - prepareAiVaultSessionResume?: ( - args: AiVaultPrepareSessionResumeArgs - ) => Promise + prepareAiVaultSessionResume?: NativeCodexResumePreparation prepareCodexStructuredLaunch?: (input: { launchEnv: NodeJS.ProcessEnv }) => string | null | Promise diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index 1346ad094001..0afcb50cd6cc 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -1,7 +1,7 @@ import { stat } from 'node:fs/promises' import { agentSessionRefusalError, isAgentSessionRefusalError } from '../../shared/agent-session-wire-refusals' import { prepareCodexAdoption } from '../native-chat/codex-adoption-preparation' -import type { AiVaultSessionResumePreparation } from '../../shared/ai-vault-resume-preparation' +import type { NativeCodexResumePreparation } from '../codex/codex-ai-vault-session-resume' import type { AgentSessionAccountHome } from '../../shared/agent-session-account-home' import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' @@ -91,31 +91,31 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { launchEnv: NodeJS.ProcessEnv workspaceCwd: string resolveTranscriptPath?: () => string | undefined - prepareCodexResume?: AiVaultSessionResumePreparation + prepareCodexResume?: NativeCodexResumePreparation }) { try { const transcriptPath = input.resolveTranscriptPath?.() const candidates = input.transcriptImport.accountHomeCandidates(input) - const admitted = transcriptPath - ? await Promise.all(candidates.map(async (accountHome) => ({ - accountHome, - path: await input.transcriptImport.admitTranscriptPath({ - accountHome, transcriptPath, launchEnv: input.launchEnv - }) - }))) - : null - if (admitted && !admitted.some((candidate) => candidate.path)) { + let admitted: { accountHome: AgentSessionAccountHome; path: string } | null = null + if (transcriptPath) { + for (const accountHome of candidates) { + const path = await input.transcriptImport.admitTranscriptPath({ + accountHome, transcriptPath, launchEnv: input.launchEnv + }) + if (path) { + admitted = { accountHome, path } + break + } + } + } + if (transcriptPath && !admitted) { throw new Error('The conversation account is not available on this host.') } const adoption = await resolveStructuredAgentSessionAdoption({ providerSessionId: input.providerSessionId, - candidateAccountHomes: admitted - ? admitted.filter((candidate) => candidate.path).map((candidate) => candidate.accountHome) - : candidates, + candidateAccountHomes: admitted ? [admitted.accountHome] : candidates, resolveTranscript: async (args) => { - const exact = transcriptPath && await input.transcriptImport.admitTranscriptPath({ - ...args, transcriptPath - }) + const exact = admitted?.path if (exact) { try { if ((await stat(exact)).isFile()) { diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 6fa6ddb109ea..2c9e9453cc0d 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -13,7 +13,7 @@ import { agentHookServer } from '../agent-hooks/server' import { browserManager } from '../browser/browser-manager' import { loadAgentSessionClaimSigner } from '../runtime/agent-session-claim-identity' import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' -import { prepareCodexAiVaultSessionResume } from '../codex/codex-ai-vault-session-resume' +import { codexAiVaultSessionResumePreparation } from '../codex/codex-ai-vault-session-resume' import { prepareCodexPinnedLaunchHome } from './codex-session-resume-launch' import { resolveHostCodexSessionSourceHome } from '../codex/codex-session-source-home' import { agentHookRuntimeDeps } from '../agent-hooks/agent-hook-runtime-deps' @@ -114,12 +114,11 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { // Why: source codex-home here (runs in window AND serve) so aiVault.listSessions includes managed-Codex sessions; registerCoreHandlers is window-only. getAdditionalAiVaultCodexHomePaths: () => state.codexRuntimeHome?.getHostCodexHomePathsForSessionDiscovery() ?? [], - prepareAiVaultSessionResume: (args) => - prepareCodexAiVaultSessionResume(args, { - runtimeHome: state.codexRuntimeHome, - systemCodexHomePath: resolveHostCodexSessionSourceHome(store.getSettings()), - preparePinnedLaunchHome: (home) => prepareCodexPinnedLaunchHome(home) - }), + prepareAiVaultSessionResume: codexAiVaultSessionResumePreparation(() => ({ + runtimeHome: state.codexRuntimeHome, + systemCodexHomePath: resolveHostCodexSessionSourceHome(store.getSettings()), + preparePinnedLaunchHome: (home) => prepareCodexPinnedLaunchHome(home) + })), ...codexStructuredLaunchHomeResolvers, prepareCodexCatalogProbeHome: (homePath) => state.codexRuntimeHome?.prepareHostCodexHomeForReadOnlyAppServer( From 3ee200d98d6e00b8007559cd842295110d062046 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:25:54 -0700 Subject: [PATCH 21/38] fix(chat): retain source evidence for dispatched adoption --- .../structured-agent-cli-source.ts | 24 +++++++ src/main/runtime/rpc/core.ts | 2 + .../runtime/rpc/dispatcher-stream-options.ts | 5 ++ ...ured-agent-session-adoption-replay.test.ts | 63 ++++++++++++++++--- ...structured-agent-session-create-handler.ts | 1 + .../structured-agent-session-create.ts | 10 +++ .../structured-session-create-support.ts | 31 +++++++-- 7 files changed, 123 insertions(+), 13 deletions(-) diff --git a/src/main/native-chat/structured-agent-cli-source.ts b/src/main/native-chat/structured-agent-cli-source.ts index 0601327368ad..b5d255cad80e 100644 --- a/src/main/native-chat/structured-agent-cli-source.ts +++ b/src/main/native-chat/structured-agent-cli-source.ts @@ -10,6 +10,30 @@ import { isWslUncPath } from '../../shared/wsl-paths' import { needsWslHostResolution } from './host-readable-transcript-path' import { parseSshTranscriptPath } from './ssh-transcript-path' +export type StructuredAgentCliSourceEvidence = + | { readonly rows: readonly Readonly[] } + | { readonly error: unknown } + +export function captureStructuredAgentCliSource( + readRows: () => readonly AgentStatusIpcPayload[] +): StructuredAgentCliSourceEvidence { + try { + return Object.freeze({ + rows: Object.freeze( + readRows().map((row) => Object.freeze({ + ...row, + ...(row.providerSession + ? { providerSession: Object.freeze({ ...row.providerSession }) } + : {}) + })) + ) + }) + } catch (error) { + // Capture cannot override an existing owner or committed replay. + return Object.freeze({ error }) + } +} + /** A client names a pane; only this host supplies its provider path. */ export function structuredAgentCliSourcePath(input: { agent: StructuredAgentId diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 4f12fe7a82ba..43ed51de7fe1 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -2,6 +2,7 @@ import { ZodError, type ZodType } from 'zod' import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol' import type { OrcaRuntimeService, OrchestrationCompatibilityCallerAuthority } from '../orca-runtime' +import type { StructuredAgentCliSourceEvidence } from '../../native-chat/structured-agent-cli-source' import type { DeviceCredentialInstalled, PairingGetEndpointsParams, @@ -93,6 +94,7 @@ export type RpcContext = { connectionId?: string // An unsubscribe cannot retire a registration created after its dispatch began. subscriptionRegistrationVersion?: number + structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence // Why: shared-control multiplexes many logical streams over one socket; the frame id lets handlers register cleanup per logical stream. requestId?: string // Why: paired mobile device token; state-owning handlers use it to clean up when that device disconnects. diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatcher-stream-options.ts index df94afa7af95..b79d87f95123 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatcher-stream-options.ts @@ -1,4 +1,5 @@ import type { OrcaRuntimeService } from '../orca-runtime' +import { captureStructuredAgentCliSource } from '../../native-chat/structured-agent-cli-source' import type { OrchestrationSessionCaller } from '../orchestration/orchestration-caller-identity' import { isRegistrationFencedUnsubscribe, type RpcContext, type RpcRequest } from './core' import { resolveRpcCallerIdentity } from './rpc-caller-identity' @@ -44,6 +45,10 @@ export function rpcContextFromTransport( subscriptionRegistrationVersion: isRegistrationFencedUnsubscribe(request.method) ? runtime.getSubscriptionRegistrationVersion() : undefined, + structuredAgentCliSourceEvidence: + request.method === 'agentSession.create' + ? captureStructuredAgentCliSource(() => runtime.getAgentProviderSessionRows()) + : undefined, clientId: options?.clientId, pairedDeviceId: options?.pairedDeviceId, pairedDeviceParentId: options?.pairedDeviceParentId, diff --git a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts index 4a82cb904752..20377249a02d 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status-types' import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' import { openTestAgentSessionRecordStore } from '../../agent-session-record-store-test-harness' import type { StructuredAgentSessionAdapter } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter' @@ -59,20 +60,21 @@ function adapter(): StructuredAgentSessionAdapter { } } -function createParams(operationId = OPERATION) { +function createParams(operationId = OPERATION, sessionId = SESSION) { const fields = { worktree: `id:${WORKSPACE}`, agent: 'codex' as const, - resumeFrom: { providerSessionId: THREAD } + resumeFrom: { providerSessionId: THREAD, + cliSource: { workspaceId: WORKSPACE, paneKey: 'source-pane' } } } return { envelope: { - sessionId: SESSION, + sessionId, clientOperationId: operationId, expectedRuntimeFence: null, payloadFingerprint: computeAgentSessionPayloadFingerprint({ method: 'agentSession.create', - sessionId: SESSION, + sessionId, fields }) }, @@ -80,7 +82,7 @@ function createParams(operationId = OPERATION) { } } -async function call(dispatcher: RpcDispatcher, params: unknown, client = CLIENT) { +async function call(dispatcher: RpcDispatcher, params: unknown, client = CLIENT, unary = false) { const replies: RpcResponse[] = [] const request: RpcRequest = { id: `request-${replies.length + 1}`, @@ -88,6 +90,7 @@ async function call(dispatcher: RpcDispatcher, params: unknown, client = CLIENT) method: 'agentSession.create', params } + if (unary) return dispatcher.dispatch(request, client) await dispatcher.dispatchStreaming( request, (raw) => replies.push(JSON.parse(raw) as RpcResponse), @@ -114,7 +117,7 @@ afterEach(async () => { }) describe('committed adopting create RPC replay', () => { - it('republishes from durable identity after the source disappears and account selection drifts', async () => { + it.each([true, false])('captures source before routing (unary=%s)', async (unary) => { const originalHome = join(root, 'account-original') const driftedHome = join(root, 'account-drifted') const transcriptPath = join( @@ -150,6 +153,13 @@ describe('committed adopting create RPC replay', () => { undefined, { prepareCodexStructuredLaunch: selectAccountHome } ) + const sourceRow = { + paneKey: 'source-pane', worktreeId: WORKSPACE, agentType: 'codex', + connectionId: null, receivedAt: 1, stateStartedAt: 1, state: 'waiting' as const, prompt: '', + providerSession: { key: 'session_id' as const, id: THREAD, transcriptPath } + } + let rows: AgentStatusIpcPayload[] = [sourceRow] + const sourceRows = vi.spyOn(runtime, 'getAgentProviderSessionRows').mockImplementation(() => rows) // The structured surface is settings-gated for every caller, not just mobile; this test // probes durable-identity replay, which only runs once the gate admits the call. // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The RPC gate reads only this setting from the test double. @@ -202,16 +212,49 @@ describe('committed adopting create RPC replay', () => { }) const params = createParams() - expect(await call(dispatcher, params)).toMatchObject({ + rows = unary ? [] : [{ ...sourceRow, providerSession: { ...sourceRow.providerSession, id: 'replaced' } }] + const route = vi.spyOn(runtime, 'routeClientHostedBrowserRpc').mockImplementationOnce(async () => { + rows = [sourceRow] + return { handled: false } + }) + expect(await call(dispatcher, params, CLIENT, unary)).toMatchObject({ + ok: true, + result: { ok: false, refusal: { details: { reason: 'transcriptUnreadable' } } } + }) + expect(sessionAdapter.acquire).not.toHaveBeenCalled() + expect(internal.publishStructuredAgentSessionTab).not.toHaveBeenCalled() + selectAccountHome.mockClear() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + route.mockImplementationOnce(async () => { + entered.resolve() + await release.promise + return { handled: false } + }) + const pending = call(dispatcher, params, CLIENT, unary) + await entered.promise + if (unary) rows = [] + else { + sourceRow.worktreeId = 'replacement-workspace' + sourceRow.providerSession.id = 'replacement-thread' + sourceRow.providerSession.transcriptPath = join(root, 'replacement.jsonl') + } + release.resolve() + expect(await pending).toMatchObject({ ok: true, result: { ok: false, refusal: { code: 'agent_session_operation_unknown' } } }) + expect(store.getRecord(SESSION)?.accountHome).toMatchObject({ path: originalHome }) await rm(transcriptPath) selectedHome = driftedHome setStructuredAgentSessionHost(null) internal.ensureStructuredAgentSessionHost = vi.fn(async () => { setStructuredAgentSessionHost(host) }) + sourceRows.mockImplementation(() => { + if (!unary) throw new Error('source snapshot unavailable') + return [] + }) expect(await call(dispatcher, params)).toMatchObject({ ok: true, @@ -236,6 +279,12 @@ describe('committed adopting create RPC replay', () => { expect(sessionAdapter.acquire).toHaveBeenCalledTimes(1) expect(internal.publishStructuredAgentSessionTab).toHaveBeenCalledTimes(2) expect(selectAccountHome).toHaveBeenCalledTimes(1) + expect(await call(dispatcher, createParams(OPERATION, 'another-chat'))).toMatchObject({ + ok: true, + result: { ok: false, refusal: { details: { + reason: 'conversationHeldElsewhere', owner: { sessionId: SESSION, workspaceId: WORKSPACE } + } } } + }) const otherOperation = createParams(`${Date.now()}-00000000000000000000000000000002`) expect(await call(dispatcher, otherOperation)).toMatchObject({ diff --git a/src/main/runtime/rpc/methods/structured-agent-session-create-handler.ts b/src/main/runtime/rpc/methods/structured-agent-session-create-handler.ts index 335648ecd87d..944d3d5bc8ee 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-create-handler.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-create-handler.ts @@ -85,6 +85,7 @@ export async function handleStructuredAgentSessionCreate( worktree: params.worktree, agent: params.agent, caller: callerFor(ctx), + structuredAgentCliSourceEvidence: ctx.structuredAgentCliSourceEvidence, ...(params.resumeFrom ? { resumeFrom: params.resumeFrom } : {}), ...(params.tabId ? { tabId: params.tabId } : {}), ...(params.options ? { options: params.options } : {}), diff --git a/src/main/runtime/rpc/methods/structured-agent-session-create.ts b/src/main/runtime/rpc/methods/structured-agent-session-create.ts index 8fd8c2245192..04f69f7a1035 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-create.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-create.ts @@ -20,6 +20,10 @@ import type { } from '../../../../shared/structured-agent-session-create' import { structuredAgentSessionOptionOverridesRefusal } from '../../../native-chat/agent-session-wire/structured-agent-session-options-read' import type { OrcaRuntimeService } from '../../orca-runtime' +import { + captureStructuredAgentCliSource, + type StructuredAgentCliSourceEvidence +} from '../../../native-chat/structured-agent-cli-source' import type { StructuredAgentId } from '../../../../shared/agent-session-provider-handle' import { resolveUncommittedStructuredCreate, @@ -71,6 +75,7 @@ export async function prepareStructuredAgentSessionCreateForWorktree(args: { agent: StructuredAgentId caller: StructuredAgentSessionCaller resumeFrom?: StructuredAgentSessionResumeSource + structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence /** Explicit picks override seed keys at rest; acquired in-process launches replace the seed. */ options?: Readonly> /** The tab id the caller reserved for this chat, taken when its tab is published; absent, the tab @@ -79,6 +84,10 @@ export async function prepareStructuredAgentSessionCreateForWorktree(args: { firstMessage?: StructuredAgentSessionFirstMessage atRest?: boolean }): Promise { + const structuredAgentCliSourceEvidence = args.structuredAgentCliSourceEvidence ?? + (args.resumeFrom?.cliSource + ? captureStructuredAgentCliSource(() => args.runtime.getAgentProviderSessionRows()) + : undefined) // Adoption replay may need the record loaded from disk before source discovery can be skipped. let host = args.resumeFrom ? await args.ensureHost() : null const resolved = await args.runtime.resolveStructuredAgentSessionCreateIntent({ @@ -86,6 +95,7 @@ export async function prepareStructuredAgentSessionCreateForWorktree(args: { worktree: args.worktree, agent: args.agent, callerKey: args.caller.callerKey, + structuredAgentCliSourceEvidence, ...(args.resumeFrom ? { resumeFrom: args.resumeFrom } : {}) }) const attachFingerprint = computeAgentSessionPayloadFingerprint({ diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index 1cb1788e78ab..a5940a5f47a8 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -1,5 +1,9 @@ import type { StructuredAgentSessionResumeSource } from '../../../shared/structured-agent-session-create' -import { structuredAgentCliSourcePath } from '../../native-chat/structured-agent-cli-source' +import { + captureStructuredAgentCliSource, + structuredAgentCliSourcePath, + type StructuredAgentCliSourceEvidence +} from '../../native-chat/structured-agent-cli-source' import type { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce as RestoreStructuredAgentSessionTabsOnceMethods } from './structured-session-tab-restoration' import { agentSessionRefusalError } from '../../../shared/agent-session-wire-refusals' import { OrcaRuntimeWithGetWorktreePs } from '../workspaces/workspace-process-listing' @@ -152,6 +156,7 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte agent: StructuredAgentId callerKey?: string resumeFrom?: StructuredAgentSessionResumeSource + structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence }): Promise { if (input.resumeFrom) { requireUnownedStructuredAgentSessionAdoption({ @@ -161,6 +166,10 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte selfSessionId: input.envelope.sessionId }) } + const structuredAgentCliSourceEvidence = input.structuredAgentCliSourceEvidence ?? + (input.resumeFrom?.cliSource + ? captureStructuredAgentCliSource(() => this.getAgentProviderSessionRows()) + : undefined) const hostLaunchDirectory = isFloatingWorkspaceSelector(input.worktree) ? (await this.resolveRuntimeFileTarget(input.worktree)).worktree.path : undefined @@ -175,7 +184,10 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte reason: 'hostUnsupported' }) } - const resolved = await this.resolveStructuredAgentSessionIntent(input, resolveAccountHome) + const resolved = await this.resolveStructuredAgentSessionIntent( + { ...input, structuredAgentCliSourceEvidence }, + resolveAccountHome + ) return hostLaunchDirectory ? { ...resolved, hostLaunchDirectory } : resolved } @@ -204,6 +216,7 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte agent: StructuredAgentId callerKey?: string resumeFrom?: StructuredAgentSessionResumeSource + structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence }, resolveAccountHome: (context: { launchEnv: NodeJS.ProcessEnv @@ -253,10 +266,16 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte agent: input.agent, transcriptImport, providerSessionId: resumeFrom.providerSessionId, - resolveTranscriptPath: () => structuredAgentCliSourcePath({ - agent: input.agent, resumeFrom, workspaceId: location.workspaceId, - rows: this.getAgentProviderSessionRows() - }), + resolveTranscriptPath: () => { + const evidence = input.structuredAgentCliSourceEvidence + if (resumeFrom.cliSource && evidence && 'error' in evidence) { + throw evidence.error + } + return structuredAgentCliSourcePath({ + agent: input.agent, resumeFrom, workspaceId: location.workspaceId, + rows: evidence && 'rows' in evidence ? evidence.rows : [] + }) + }, prepareCodexResume: this.prepareAiVaultSessionResumeFn ?? undefined, selectedAccountHome, launchEnv: await resolveHostStructuredAgentLaunchEnvironment(input.agent, settings), From 8cd662b72e6e90e1969ee99d37b3089d97e06d28 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:30:42 -0700 Subject: [PATCH 22/38] fix(chat): keep source capture within module limits --- .../structured-agent-cli-source.ts | 16 ++++++++ ...ured-agent-session-adoption-replay.test.ts | 13 ++++-- .../structured-session-create-support.ts | 41 +++++-------------- ...tructured-agent-session-create-adoption.ts | 11 +++++ 4 files changed, 47 insertions(+), 34 deletions(-) diff --git a/src/main/native-chat/structured-agent-cli-source.ts b/src/main/native-chat/structured-agent-cli-source.ts index b5d255cad80e..244a84dd3157 100644 --- a/src/main/native-chat/structured-agent-cli-source.ts +++ b/src/main/native-chat/structured-agent-cli-source.ts @@ -34,6 +34,22 @@ export function captureStructuredAgentCliSource( } } +export function structuredAgentCliSourcePathFromEvidence(input: { + agent: StructuredAgentId + resumeFrom: StructuredAgentSessionResumeSource + workspaceId: string + evidence?: StructuredAgentCliSourceEvidence +}): string | undefined { + const evidence = input.evidence + if (input.resumeFrom.cliSource && evidence && 'error' in evidence) { + throw evidence.error + } + return structuredAgentCliSourcePath({ + ...input, + rows: evidence && 'rows' in evidence ? evidence.rows : [] + }) +} + /** A client names a pane; only this host supplies its provider path. */ export function structuredAgentCliSourcePath(input: { agent: StructuredAgentId diff --git a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts index 20377249a02d..ecbb599de7ff 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-adoption-replay.test.ts @@ -90,7 +90,9 @@ async function call(dispatcher: RpcDispatcher, params: unknown, client = CLIENT, method: 'agentSession.create', params } - if (unary) return dispatcher.dispatch(request, client) + if (unary) { + return dispatcher.dispatch(request, client) + } await dispatcher.dispatchStreaming( request, (raw) => replies.push(JSON.parse(raw) as RpcResponse), @@ -233,8 +235,9 @@ describe('committed adopting create RPC replay', () => { }) const pending = call(dispatcher, params, CLIENT, unary) await entered.promise - if (unary) rows = [] - else { + if (unary) { + rows = [] + } else { sourceRow.worktreeId = 'replacement-workspace' sourceRow.providerSession.id = 'replacement-thread' sourceRow.providerSession.transcriptPath = join(root, 'replacement.jsonl') @@ -252,7 +255,9 @@ describe('committed adopting create RPC replay', () => { setStructuredAgentSessionHost(host) }) sourceRows.mockImplementation(() => { - if (!unary) throw new Error('source snapshot unavailable') + if (!unary) { + throw new Error('source snapshot unavailable') + } return [] }) diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index a5940a5f47a8..e9318ed1ca16 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -1,8 +1,6 @@ -import type { StructuredAgentSessionResumeSource } from '../../../shared/structured-agent-session-create' import { captureStructuredAgentCliSource, - structuredAgentCliSourcePath, - type StructuredAgentCliSourceEvidence + structuredAgentCliSourcePathFromEvidence } from '../../native-chat/structured-agent-cli-source' import type { OrcaRuntimeWithRestoreStructuredAgentSessionTabsOnce as RestoreStructuredAgentSessionTabsOnceMethods } from './structured-session-tab-restoration' import { agentSessionRefusalError } from '../../../shared/agent-session-wire-refusals' @@ -11,7 +9,8 @@ import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-w import { resolveCommittedStructuredAgentSessionAdoptionIntent, requireUnownedStructuredAgentSessionAdoption, - resolveStructuredAgentSessionAdoptionForCreate + resolveStructuredAgentSessionAdoptionForCreate, + type StructuredAgentSessionCreateIntentInput } from '../structured-agent-session-create-adoption' import { isNativeLocalLocation, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { getLocalProjectWorktreeGitOptions } from '../../project-runtime-git-options' @@ -150,14 +149,9 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte return (await this.resolveRuntimeFileTarget(worktreeSelector)).worktree.path } - async resolveStructuredAgentSessionCreateIntent(input: { - envelope: { sessionId: string; clientOperationId: string } - worktree: string - agent: StructuredAgentId - callerKey?: string - resumeFrom?: StructuredAgentSessionResumeSource - structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence - }): Promise { + async resolveStructuredAgentSessionCreateIntent( + input: StructuredAgentSessionCreateIntentInput + ): Promise { if (input.resumeFrom) { requireUnownedStructuredAgentSessionAdoption({ host: getStructuredAgentSessionHost(), @@ -210,14 +204,7 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte } protected async resolveStructuredAgentSessionIntent( - input: { - envelope: { sessionId: string; clientOperationId: string } - worktree: string - agent: StructuredAgentId - callerKey?: string - resumeFrom?: StructuredAgentSessionResumeSource - structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence - }, + input: StructuredAgentSessionCreateIntentInput, resolveAccountHome: (context: { launchEnv: NodeJS.ProcessEnv location: { @@ -266,16 +253,10 @@ export abstract class OrcaRuntimeWithGetStructuredAgentSessionCreateSupport exte agent: input.agent, transcriptImport, providerSessionId: resumeFrom.providerSessionId, - resolveTranscriptPath: () => { - const evidence = input.structuredAgentCliSourceEvidence - if (resumeFrom.cliSource && evidence && 'error' in evidence) { - throw evidence.error - } - return structuredAgentCliSourcePath({ - agent: input.agent, resumeFrom, workspaceId: location.workspaceId, - rows: evidence && 'rows' in evidence ? evidence.rows : [] - }) - }, + resolveTranscriptPath: () => structuredAgentCliSourcePathFromEvidence({ + agent: input.agent, resumeFrom, workspaceId: location.workspaceId, + evidence: input.structuredAgentCliSourceEvidence + }), prepareCodexResume: this.prepareAiVaultSessionResumeFn ?? undefined, selectedAccountHome, launchEnv: await resolveHostStructuredAgentLaunchEnvironment(input.agent, settings), diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index 0afcb50cd6cc..a98e8e588446 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -2,6 +2,8 @@ import { stat } from 'node:fs/promises' import { agentSessionRefusalError, isAgentSessionRefusalError } from '../../shared/agent-session-wire-refusals' import { prepareCodexAdoption } from '../native-chat/codex-adoption-preparation' import type { NativeCodexResumePreparation } from '../codex/codex-ai-vault-session-resume' +import type { StructuredAgentSessionResumeSource } from '../../shared/structured-agent-session-create' +import type { StructuredAgentCliSourceEvidence } from '../native-chat/structured-agent-cli-source' import type { AgentSessionAccountHome } from '../../shared/agent-session-account-home' import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' import type { StructuredAgentId } from '../../shared/agent-session-provider-handle' @@ -21,6 +23,15 @@ import type { StructuredAgentTranscriptImportSettings } from '../native-chat/structured-agent-cli-conversations' +export type StructuredAgentSessionCreateIntentInput = { + envelope: { sessionId: string; clientOperationId: string } + worktree: string + agent: StructuredAgentId + callerKey?: string + resumeFrom?: StructuredAgentSessionResumeSource + structuredAgentCliSourceEvidence?: StructuredAgentCliSourceEvidence +} + export function resolveCommittedStructuredAgentSessionAdoptionIntent(input: { host: StructuredAgentSessionHost | null envelope: { sessionId: string; clientOperationId: string } From 4440b5b07f7cdacdb7f4e9314ba4b61273c56368 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:45:55 -0700 Subject: [PATCH 23/38] Keep deferred chat publication in the shared launch owner --- .../app-shell/use-app-startup-hydration.ts | 2 + .../tab-bar/cli-chat-resume-run.test.ts | 200 ++++++++++++-- .../src/lib/agent-session-launch-plan.ts | 3 + .../lib/launch-structured-agent-session.ts | 2 + ...structured-agent-session-launch-callers.ts | 2 + ...d-agent-session-launch-outcome-tracking.ts | 25 ++ ...d-agent-session-launch-persistence.test.ts | 12 + ...ctured-agent-session-launch-persistence.ts | 26 +- .../structured-agent-session-launch-record.ts | 31 +++ ...tructured-agent-session-launch-registry.ts | 2 + .../structured-agent-session-launch-reload.ts | 5 +- ...structured-agent-session-launch-surface.ts | 252 ++++++++++++++++++ .../lib/structured-agent-session-launch.ts | 6 + ...tructured-agent-session-provisional-tab.ts | 104 ++------ .../lib/workspace-session-hydration-keys.ts | 5 + .../src/lib/workspace-session-unified-tabs.ts | 20 +- .../web-session-client-owned-tab-placement.ts | 21 +- .../terminal-surfaces.ts | 14 +- .../src/store/slices/tab-group-state.ts | 7 +- .../src/store/slices/tabs-hydration.ts | 11 +- .../store/slices/tabs/tabs-close-actions.ts | 7 +- .../store/slices/tabs/tabs-create-actions.ts | 20 +- .../store/slices/tabs/tabs-drop-actions.ts | 7 +- .../store/slices/tabs/tabs-group-actions.ts | 3 +- .../store/slices/tabs/tabs-move-actions.ts | 7 +- .../store/slices/tabs/tabs-reconciliation.ts | 9 +- .../teardown/worktree-purge-state.ts | 18 ++ 27 files changed, 682 insertions(+), 139 deletions(-) create mode 100644 src/renderer/src/lib/structured-agent-session-launch-surface.ts diff --git a/src/renderer/src/app-shell/use-app-startup-hydration.ts b/src/renderer/src/app-shell/use-app-startup-hydration.ts index 0c0ab0dd5436..b5bb87b1e67f 100644 --- a/src/renderer/src/app-shell/use-app-startup-hydration.ts +++ b/src/renderer/src/app-shell/use-app-startup-hydration.ts @@ -1,3 +1,4 @@ +import { restoreStructuredLaunchSurfaces } from '@/lib/structured-agent-session-launch-surface' import { useEffect, useRef } from 'react' import { restoreLocalStructuredChatsAtStartup } from '@/runtime/local-structured-chats' import { syncZoomCSSVar } from '@/lib/ui-zoom' @@ -214,6 +215,7 @@ export function useAppStartupHydration(onOnboardingLoaded: (state: OnboardingSta useAppStore.getState().reconcileWorktreeTabModels ) }) + restoreStructuredLaunchSurfaces() await timeRendererStartupStep('prepare-terminal-startup-restoration', () => window.api.app.prepareTerminalStartupRestoration() ) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index 11a53bed656f..bc42b4253c30 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -34,6 +34,30 @@ vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ activateAiVaultStructuredSession: mocks.activate })) +import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session-launch-plan' +import { newAgentLaunchRequestId } from '@/lib/agent-launch-request-id' +import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/structured-agent-session-provisional-tab' +import { + getStructuredAgentSessionLaunchLifecycle, + retryStructuredAgentSessionLaunch +} from '@/lib/structured-agent-session-launch' +import { + readStructuredAgentLaunchRecord, + writeStructuredAgentLaunchRecord, + resetStructuredAgentLaunchPersistenceForTests +} from '@/lib/structured-agent-session-launch-persistence' +import { + reserveStructuredLaunchSlot, + restoreStructuredLaunchSurfaces, + resetStructuredLaunchSurfaceForTests +} from '@/lib/structured-agent-session-launch-surface' +import { applyStructuredSessionTabSnapshots } from '@/runtime/local-structured-session-tabs-sync/snapshot-apply' +import { resetLocalStructuredSessionVersionForTests } from '@/runtime/local-structured-session-tabs-sync/inventory-generation-fence' +import { resetWebSessionTabsSnapshotFreshnessForTests } from '@/runtime/web-session-tabs-sync/tracking-lifecycle' +import { buildWorkspaceSessionPayload } from '@/lib/workspace-session' +import { buildHydratedTabState } from '@/store/slices/tabs-hydration' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types' import { useAppStore } from '@/store' import { runCliChatResume } from './cli-chat-resume-run' import { @@ -41,7 +65,6 @@ import { structuredLaunchStates } from '@/lib/structured-agent-session-launch-registry' import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims' -import { openStructuredAgentSessionProvisionalTab } from '@/lib/structured-agent-session-provisional-tab' import { clearWebSessionFocusIntent, resetWebSessionFocusIntentForTests @@ -77,7 +100,11 @@ function refuse( beforeEach(() => { vi.clearAllMocks() + resetLocalStructuredSessionVersionForTests() + resetWebSessionTabsSnapshotFreshnessForTests() + resetStructuredLaunchSurfaceForTests() localStorage.clear() + resetStructuredAgentLaunchPersistenceForTests() resetStructuredAgentLaunchRegistryForTests() resetWebSessionFocusIntentForTests() useAppStore.setState(useAppStore.getInitialState(), true) @@ -93,6 +120,35 @@ beforeEach(() => { ) }) +function snapshot(sessionId?: string): RuntimeMobileSessionTabsResult { + return { + worktree: 'wt-1', + publicationEpoch: 'publication-test', + snapshotVersion: Date.now(), + activeGroupId: null, + activeTabId: null, + activeTabType: null, + tabs: sessionId + ? [ + { + type: 'agent-session', + id: `agent-session:${sessionId}`, + sessionId, + agent: 'claude', + title: 'Chat', + isActive: false + } + ] + : [] + } +} + +function seedTabs() { + return ['E', 'S', 'B'].map((id) => + useAppStore.getState().createUnifiedTab('wt-1', 'editor', { id, entityId: id }) + ) +} + describe('CLI identity resume through the existing launch owner', () => { it('shares pending, sends only an advertised source, and survives source closure after dispatch', async () => { const reply = deferred() @@ -182,28 +238,136 @@ describe('CLI identity resume through the existing launch owner', () => { expect(tabs()).toEqual([]) }) - it('does not re-activate a published destination over a later selection', async () => { + it('keeps the eager History joiner failed and retryable after the hidden starter is refused', async () => { const reply = deferred() mocks.call.mockReturnValue(reply.promise) const running = runCliChatResume(SOURCE) await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) const sessionId: string = mocks.call.mock.calls[0][2].envelope.sessionId - openStructuredAgentSessionProvisionalTab({ - worktreeId: 'wt-1', - executionHostId: 'local', - sessionId, - agent: 'claude' + const eager = beginStructuredAgentSessionProvisionalLaunch({ + hooks: {}, + plan: adoptAgentSessionLaunchVerdict({ + route: 'structured-native-chat', + requestId: newAgentLaunchRequestId(), + agent: 'claude', + worktreeId: 'wt-1', + executionHostId: 'local', + resumeFrom: { providerSessionId: 'provider-1' } + }) }) - clearWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1') - const later = useAppStore - .getState() - .createUnifiedTab('wt-1', 'editor', { entityId: 'later-file', label: 'Later' }) - reply.resolve({ ok: true, value: { sessionId, fence: 1 } }) - await running - const state = useAppStore.getState() - expect(tabs().filter((tab) => tab.entityId === sessionId)).toHaveLength(1) - expect( - state.groupsByWorktree['wt-1'].find((group) => group.id === later.groupId)?.activeTabId - ).toBe(later.id) + await vi.waitFor(() => expect(tabs()).toHaveLength(1)) + reply.resolve({ ok: false, refusal: refuse('transcriptUnreadable') }) + await Promise.all([running, eager?.settlement]) + expect(mocks.call).toHaveBeenCalledOnce() + expect(getStructuredAgentSessionLaunchLifecycle('wt-1', sessionId)).toBe('failed') + expect(readStructuredAgentLaunchRecord(sessionId)?.lifecycle).toBe('failed') + mocks.call.mockResolvedValue({ ok: true, value: { sessionId, fence: 1 } }) + expect(retryStructuredAgentSessionLaunch('wt-1', sessionId)).toBe(true) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2)) + expect(mocks.call.mock.calls[1][2].envelope.sessionId).toBe(sessionId) + await vi.waitFor(() => + expect(getStructuredAgentSessionLaunchLifecycle('wt-1', sessionId)).toBeNull() + ) + expect(tabs()).toHaveLength(1) + }) + + it.each(['reply', 'inventory'] as const)( + 'fills the original slot after sibling drag, append and later selection (%s first)', + async (first) => { + const [e, source, browser] = seedTabs() + const reply = deferred() + mocks.call.mockReturnValue(reply.promise) + const running = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledOnce()) + const sessionId: string = mocks.call.mock.calls[0][2].envelope.sessionId + const slotId = `structured-agent-session-${sessionId}` + const store = useAppStore.getState() + const order = store.groupsByWorktree['wt-1'][0].tabOrder + expect(order).toEqual([e.id, source.id, browser.id, slotId]) + store.reorderUnifiedTabs(e.groupId, [browser.id, e.id, source.id, slotId]) + const later = useAppStore + .getState() + .createUnifiedTab('wt-1', 'editor', { id: 'R', entityId: 'R' }) + const other = useAppStore.getState().createUnifiedTab('wt-1', 'editor', { + entityId: 'other', + split: { splitDirection: 'right', sourceGroupId: e.groupId } + }) + clearWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1') + if (first === 'inventory') applyStructuredSessionTabSnapshots([snapshot(sessionId)]) + reply.resolve({ ok: true, value: { sessionId, fence: 1 } }) + await running + expect( + useAppStore.getState().groupsByWorktree['wt-1'].find((group) => group.id === e.groupId) + ?.tabOrder + ).toEqual([browser.id, e.id, source.id, slotId, later.id]) + expect(useAppStore.getState().activeGroupIdByWorktree['wt-1']).toBe(other.groupId) + useAppStore.getState().moveUnifiedTabToGroup(slotId, other.groupId) + applyStructuredSessionTabSnapshots([ + { ...snapshot(sessionId), snapshotVersion: Date.now() + 1 } + ]) + expect(tabs().find((tab) => tab.entityId === sessionId)?.groupId).toBe(other.groupId) + } + ) + + it.each([false, true])( + 'keeps overlapping requests in their canonical order (second finishes first: %s)', + async (reverse) => { + const initial = seedTabs() + const replies = [deferred(), deferred()] + mocks.call + .mockImplementationOnce(() => replies[0].promise) + .mockImplementationOnce(() => replies[1].promise) + const first = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(1)) + const secondSource = { ...SOURCE, providerSessionId: 'provider-2' } + mocks.source = secondSource + const second = runCliChatResume(secondSource) + await vi.waitFor(() => expect(mocks.call).toHaveBeenCalledTimes(2)) + const ids: string[] = mocks.call.mock.calls.map((call) => call[2].envelope.sessionId) + for (const index of reverse ? [1, 0] : [0, 1]) { + replies[index].resolve({ ok: true, value: { sessionId: ids[index], fence: 1 } }) + await (index === 0 ? first : second) + } + expect(useAppStore.getState().groupsByWorktree['wt-1'][0].tabOrder).toEqual([ + ...initial.map((tab) => tab.id), + ...ids.map((id) => `structured-agent-session-${id}`) + ]) + } + ) + + it('restores a pending-only group as unknown without sending create or restoring focus', () => { + const record = { + sessionId: 'reload-pending', + executionHostId: 'local' as const, + agent: 'claude' as const, + lifecycle: 'pending' as const, + clientOperationId: 'original-operation', + payloadFingerprint: 'fingerprint', + expectedRuntimeFence: null, + surfaceAddress: { worktreeId: 'wt-1', precedingTabIds: [] } + } + writeStructuredAgentLaunchRecord(record) + reserveStructuredLaunchSlot(record) + const session = buildWorkspaceSessionPayload(useAppStore.getState()) + resetStructuredLaunchSurfaceForTests() + resetStructuredAgentLaunchPersistenceForTests() + resetStructuredAgentLaunchRegistryForTests() + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + ...buildHydratedTabState(session, new Set(['wt-1'])), + worktreesByRepo: { repo: [makeWorktree({ id: 'wt-1', repoId: 'repo', hostId: 'local' })] } + }) + restoreStructuredLaunchSurfaces() + restoreStructuredLaunchSurfaces() + applyStructuredSessionTabSnapshots([snapshot()]) + expect(mocks.call).not.toHaveBeenCalled() + expect(tabs()).toHaveLength(1) + expect(getStructuredAgentSessionLaunchLifecycle('wt-1', 'reload-pending')).toBe( + 'visibility-unknown' + ) + expect(readStructuredAgentLaunchRecord('reload-pending')?.clientOperationId).toBe( + 'original-operation' + ) + expect(useAppStore.getState().groupsByWorktree['wt-1'][0].recentTabIds ?? []).toEqual([]) }) }) diff --git a/src/renderer/src/lib/agent-session-launch-plan.ts b/src/renderer/src/lib/agent-session-launch-plan.ts index fb8956a7fae1..81b27beafa77 100644 --- a/src/renderer/src/lib/agent-session-launch-plan.ts +++ b/src/renderer/src/lib/agent-session-launch-plan.ts @@ -1,3 +1,4 @@ +import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' import type { StructuredAgentSessionResumeSource } from '../../../shared/structured-agent-session-create' import type { TuiAgent } from '../../../shared/tui-agent' import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' @@ -65,6 +66,7 @@ export type AgentSessionStructuredFeasibilityRequest = AgentLaunchRouteArgs & { } export type AgentSessionLaunchTarget = { + surfaceAddress?: StructuredLaunchSurfaceAddress /** Overrides the verdict's workspace when it was created after planning. */ worktreeId?: string /** The host that admitted the chat, when one was asked first; it is the host the chat is made on. */ @@ -118,6 +120,7 @@ function beginStructuredPlanLaunch( verdict.agent, { ...structuredLaunchOptions(verdict), + ...(target?.surfaceAddress ? { surfaceAddress: target.surfaceAddress } : {}), ...(executionHostId ? { executionHostId } : {}), ...(target?.seedOptions ? { hostSeedOptions: target.seedOptions } : {}) }, diff --git a/src/renderer/src/lib/launch-structured-agent-session.ts b/src/renderer/src/lib/launch-structured-agent-session.ts index d7bc79d13b2c..da3809b559a2 100644 --- a/src/renderer/src/lib/launch-structured-agent-session.ts +++ b/src/renderer/src/lib/launch-structured-agent-session.ts @@ -1,3 +1,4 @@ +import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' import type { TuiAgent } from '../../../shared/tui-agent' import { createStructuredAgentSessionId, @@ -48,6 +49,7 @@ export type StructuredAgentSessionLaunchIntent = { createPrepared?: true prepareCreate?: () => void beforeCreate?: () => boolean + surfaceAddress?: StructuredLaunchSurfaceAddress /** The saved selection create seeds, read when the intent is built. */ seedOptions?: Readonly> } diff --git a/src/renderer/src/lib/structured-agent-session-launch-callers.ts b/src/renderer/src/lib/structured-agent-session-launch-callers.ts index 8e3258429643..ba21ae8df316 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-callers.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-callers.ts @@ -1,3 +1,4 @@ +import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' import { settleStructuredAgentLaunchPrompt } from '@/lib/structured-agent-session-launch-prompt' import type { StagedStructuredLaunchPrompt, @@ -26,6 +27,7 @@ export type StructuredAgentLaunchOptions = { hostSeedOptions?: Readonly> /** Final admission of a source-bound action, immediately before its first create is sent. */ beforeCreate?: () => boolean + surfaceAddress?: StructuredLaunchSurfaceAddress } export type StructuredLaunchCaller = { diff --git a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts index 02fd06166181..ad825bc0c924 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts @@ -1,3 +1,9 @@ +import { + materializeStructuredLaunchSurface, + removeStructuredLaunchSlot +} from './structured-agent-session-launch-surface' +import { findStructuredAgentSessionTab } from './structured-agent-session-tab-activation' +import { useAppStore } from '@/store' import { StructuredAgentSessionCreateRefusalError } from '@/lib/launch-structured-agent-session' import { settleStructuredLaunchCallers, @@ -31,6 +37,20 @@ export function maybeCleanupLaunchState(state: StructuredLaunchState): void { cleanupLaunchState(state) } +function cleanupUnmaterializedLaunch(state: StructuredLaunchState): void { + if ( + state.intent.surfaceAddress && + !findStructuredAgentSessionTab(useAppStore.getState().unifiedTabsByWorktree, { + workspaceId: state.intent.worktreeId, + sessionId: state.intent.sessionId, + target: state.intent.target + }) + ) { + removeStructuredLaunchSlot(state.intent.worktreeId, state.intent.sessionId) + cleanupLaunchState(state) + } +} + function settleStructuredLaunchRefusal(state: StructuredLaunchState): void { if (state.callers.outcome !== 'pending' && state.callers.outcome !== 'unknown') { return @@ -40,6 +60,7 @@ function settleStructuredLaunchRefusal(state: StructuredLaunchState): void { state.intent.sessionId ) settleStructuredLaunchCallers(state.callers, 'failed') + cleanupUnmaterializedLaunch(state) notifyStructuredLaunchListeners() } @@ -52,6 +73,8 @@ export function trackLaunchSettlement( if (state.promise !== promise) { return } + if (state.cancelled) return + materializeStructuredLaunchSurface(state.intent) settleStructuredLaunchCallers(state.callers, 'published') notifyStructuredLaunchListeners() }, @@ -80,9 +103,11 @@ export function trackLaunchSettlement( settleStructuredLaunchRefusal(state) } else if (!state.visibilityUnknown) { settleStructuredLaunchCallers(state.callers, 'failed') + cleanupUnmaterializedLaunch(state) notifyStructuredLaunchListeners() } else { state.callers.outcome = 'unknown' + materializeStructuredLaunchSurface(state.intent) notifyStructuredLaunchListeners() } } diff --git a/src/renderer/src/lib/structured-agent-session-launch-persistence.test.ts b/src/renderer/src/lib/structured-agent-session-launch-persistence.test.ts index c9c56377fbd9..9872e63785e8 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-persistence.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-persistence.test.ts @@ -33,6 +33,11 @@ describe('structured agent launch persistence', () => { JSON.stringify([ { sessionId: 'codex_session', + surfaceAddress: { + worktreeId: 'repo::/workspace', + targetGroupId: 'original', + precedingTabIds: ['source'] + }, agent: 'codex', lifecycle: 'pending', clientOperationId: 'operation-1', @@ -43,6 +48,11 @@ describe('structured agent launch persistence', () => { ) expect(readStructuredAgentLaunchRecord('codex_session')).toMatchObject({ + surfaceAddress: { + worktreeId: 'repo::/workspace', + targetGroupId: 'original', + precedingTabIds: ['source'] + }, lifecycle: 'visibility-unknown', clientOperationId: 'operation-1', // Written before a paired host could hold a chat, so it was launched on this machine. @@ -61,6 +71,7 @@ describe('structured agent launch persistence', () => { sessionId, agent, lifecycle: 'pending', + surfaceAddress: { worktreeId: 'workspace', precedingTabIds: [false] }, clientOperationId: `${sessionId}-op`, payloadFingerprint: 'fingerprint', expectedRuntimeFence: null @@ -69,6 +80,7 @@ describe('structured agent launch persistence', () => { ) expect(readStructuredAgentLaunchRecord('grok_session')?.agent).toBe('grok') + expect(readStructuredAgentLaunchRecord('grok_session')?.surfaceAddress).toBeUndefined() expect(readStructuredAgentLaunchRecord('bogus_session')).toBeUndefined() }) diff --git a/src/renderer/src/lib/structured-agent-session-launch-persistence.ts b/src/renderer/src/lib/structured-agent-session-launch-persistence.ts index ccd9298f380c..52a73c68f16e 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-persistence.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-persistence.ts @@ -1,5 +1,7 @@ +import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' import { validRecord, + parseStructuredLaunchSurfaceAddress, type StructuredAgentLaunchPersistedRecord } from './structured-agent-session-launch-record' export { @@ -40,9 +42,13 @@ function load(): void { const seedOptions = parseStructuredLaunchSeedOptions( 'seedOptions' in value ? value.seedOptions : undefined ) - const { seedOptions: _stored, ...rest } = value + const surfaceAddress = parseStructuredLaunchSurfaceAddress( + 'surfaceAddress' in value ? value.surfaceAddress : undefined + ) + const { seedOptions: _stored, surfaceAddress: _address, ...rest } = value records.set(value.sessionId, { ...rest, + ...(surfaceAddress ? { surfaceAddress } : {}), ...(seedOptions ? { seedOptions } : {}), executionHostId: parseExecutionHostId(value.executionHostId)?.id ?? LOCAL_EXECUTION_HOST_ID, @@ -144,6 +150,24 @@ function writeTombstones(): void { } } +export function readStructuredAgentLaunchRecords(): readonly StructuredAgentLaunchPersistedRecord[] { + load() + return [...records.values()] +} + +export function structuredLaunchSlotIds(worktreeId: string, groupId?: string): Set { + return new Set( + readStructuredAgentLaunchRecords().flatMap((record) => + record.executionHostId === 'local' && + record.lifecycle !== 'failed' && + record.surfaceAddress?.worktreeId === worktreeId && + (!groupId || record.surfaceAddress.targetGroupId === groupId) + ? [structuredAgentSessionTabId(record.sessionId)] + : [] + ) + ) +} + export function readStructuredAgentLaunchRecord( sessionId: string ): StructuredAgentLaunchPersistedRecord | undefined { diff --git a/src/renderer/src/lib/structured-agent-session-launch-record.ts b/src/renderer/src/lib/structured-agent-session-launch-record.ts index 0f631ef58116..b9af8c6fa41c 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-record.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-record.ts @@ -11,7 +11,37 @@ import type { StructuredAgentSessionLaunchIntent } from './launch-structured-age export type StructuredAgentLaunchPersistedLifecycle = 'pending' | 'visibility-unknown' | 'failed' +export type StructuredLaunchSurfaceAddress = { + worktreeId: string + targetGroupId?: string + precedingTabIds: readonly string[] +} + +export function parseStructuredLaunchSurfaceAddress( + value: unknown +): StructuredLaunchSurfaceAddress | undefined { + if ( + !value || + typeof value !== 'object' || + !('worktreeId' in value) || + typeof value.worktreeId !== 'string' || + !value.worktreeId || + !('precedingTabIds' in value) || + !Array.isArray(value.precedingTabIds) || + !value.precedingTabIds.every((id: unknown) => typeof id === 'string') || + ('targetGroupId' in value && typeof value.targetGroupId !== 'string') + ) { + return undefined + } + return { + worktreeId: value.worktreeId, + precedingTabIds: value.precedingTabIds, + ...('targetGroupId' in value ? { targetGroupId: value.targetGroupId } : {}) + } +} + export type StructuredAgentLaunchPersistedRecord = { + surfaceAddress?: StructuredLaunchSurfaceAddress sessionId: string /** The host the chat was created on. Records written before paired hosts could hold a chat lack * it and load as local, the only host a chat could then be launched on. */ @@ -40,6 +70,7 @@ export function structuredAgentLaunchRecordFor( // A local launch re-reads this machine's settings on reload; only a paired server's seed is kept. const pairedSeed = intent.target.kind === 'local' ? undefined : intent.seedOptions return { + ...(intent.surfaceAddress ? { surfaceAddress: intent.surfaceAddress } : {}), sessionId: intent.sessionId, executionHostId: intent.executionHostId, agent: intent.agent, diff --git a/src/renderer/src/lib/structured-agent-session-launch-registry.ts b/src/renderer/src/lib/structured-agent-session-launch-registry.ts index 076ecf184862..964844ad1bb6 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-registry.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-registry.ts @@ -1,3 +1,4 @@ +import { removeStructuredLaunchSlot } from './structured-agent-session-launch-surface' import { useSyncExternalStore } from 'react' import type { TuiAgent } from '../../../shared/tui-agent' import type { StructuredLaunchFailure } from './structured-agent-session-launch-failure' @@ -241,6 +242,7 @@ function markStructuredAgentSessionLaunchCancelledInternal( } else if (!alreadyCancelled) { markStructuredAgentLaunchCancellation(sessionId, executionHostId, alreadyCancelled) } + if (notify) removeStructuredLaunchSlot(worktreeId, sessionId) if (!alreadyCancelled && notify) { notifyStructuredLaunchListeners() } diff --git a/src/renderer/src/lib/structured-agent-session-launch-reload.ts b/src/renderer/src/lib/structured-agent-session-launch-reload.ts index 8a511ff876f0..870dbfe05a1f 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-reload.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-reload.ts @@ -51,7 +51,10 @@ export function restorePersistedStructuredLaunchState( const callers: StructuredLaunchCallerGroup = createStructuredLaunchCallerGroup({ kind: 'retry' }) const state: StructuredLaunchState = { identity: structuredLaunchIdentity(worktreeId, record.agent, record.resumeFrom), - intent, + intent: { + ...intent, + ...(record.surfaceAddress ? { surfaceAddress: record.surfaceAddress } : {}) + }, promptDelivery: 'draft', promise: Promise.resolve({ sessionId: record.sessionId, fence: 0 }), visibilityUnknown: record.lifecycle === 'visibility-unknown', diff --git a/src/renderer/src/lib/structured-agent-session-launch-surface.ts b/src/renderer/src/lib/structured-agent-session-launch-surface.ts new file mode 100644 index 000000000000..45d4704665d0 --- /dev/null +++ b/src/renderer/src/lib/structured-agent-session-launch-surface.ts @@ -0,0 +1,252 @@ +import { getExecutionHostIdForWorktree } from './worktree-runtime-owner' +import { folderWorkspaceToWorktree } from '../../../shared/folder-workspace-worktree' +import type { Tab } from '../../../shared/tab-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { TuiAgent } from '../../../shared/tui-agent' +import { defaultAgentChatLabel } from '../../../shared/agent-session-chat-label' +import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' +import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-order' +import { useAppStore } from '@/store' +import { ensureGroup } from '@/store/slices/tab-group-state' +import { resolveUnifiedTabCreatePlacement } from '@/store/slices/tabs/tabs-create-placement' +import { findStructuredAgentSessionTab } from './structured-agent-session-tab-activation' +import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' +import { + readStructuredAgentLaunchRecord, + readStructuredAgentLaunchRecords, + writeStructuredAgentLaunchRecord +} from './structured-agent-session-launch-persistence' +import { getStructuredLaunchStateBySessionId } from './structured-agent-session-launch-registry' +import { + structuredAgentSessionFocusOwner, + structuredAgentSessionTargetForHost +} from '@/runtime/structured-agent-session-owner' +import { + clearWebSessionFocusIntentIfMatches, + peekWebSessionFocusIntent, + resolveWebSessionVisibleTabId +} from '@/runtime/web-session-focus-intent' + +type LaunchSurface = { + sessionId: string + executionHostId: ExecutionHostId + agent: TuiAgent + surfaceAddress?: StructuredLaunchSurfaceAddress +} + +export function captureStructuredLaunchSurfaceAddress( + worktreeId: string, + targetGroupId?: string +): StructuredLaunchSurfaceAddress { + const state = useAppStore.getState() + const groups = state.groupsByWorktree[worktreeId] ?? [] + const placement = resolveUnifiedTabCreatePlacement({ + groups, + tabs: state.unifiedTabsByWorktree[worktreeId] ?? [], + activeGroupId: state.activeGroupIdByWorktree[worktreeId], + targetGroupId, + lookupWorktrees: () => [] + }) + return { + worktreeId, + targetGroupId: placement.groupId, + precedingTabIds: groups.find((group) => group.id === placement.groupId)?.tabOrder ?? [] + } +} + +let stopTrackingSlots: (() => void) | undefined + +export function resetStructuredLaunchSurfaceForTests(): void { + stopTrackingSlots?.() + stopTrackingSlots = undefined +} + +function trackSlotAddresses(): void { + stopTrackingSlots ??= useAppStore.subscribe((state, previous) => { + if (state.groupsByWorktree === previous.groupsByWorktree) return + const records = readStructuredAgentLaunchRecords().filter( + (record) => + record.surfaceAddress && + record.executionHostId === 'local' && + !state.unifiedTabsByWorktree[record.surfaceAddress.worktreeId]?.some( + (tab) => tab.id === structuredAgentSessionTabId(record.sessionId) + ) + ) + if (records.length === 0) resetStructuredLaunchSurfaceForTests() + for (const record of records) { + const address = record.surfaceAddress + if (!address || record.executionHostId !== 'local') continue + const tabId = structuredAgentSessionTabId(record.sessionId) + if (state.unifiedTabsByWorktree[address.worktreeId]?.some((tab) => tab.id === tabId)) continue + if ( + state.groupsByWorktree[address.worktreeId] === previous.groupsByWorktree[address.worktreeId] + ) + continue + const group = state.groupsByWorktree[address.worktreeId]?.find((entry) => + entry.tabOrder.includes(tabId) + ) + const surfaceAddress = { + worktreeId: address.worktreeId, + targetGroupId: group?.id, + precedingTabIds: group ? group.tabOrder.slice(0, group.tabOrder.indexOf(tabId)) : [] + } + const launch = getStructuredLaunchStateBySessionId(record.sessionId) + if (launch) launch.intent.surfaceAddress = surfaceAddress + writeStructuredAgentLaunchRecord({ ...record, surfaceAddress }) + } + }) +} + +export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { + const address = launch.surfaceAddress + if (!address || launch.executionHostId !== 'local') return + const state = useAppStore.getState() + const tabId = structuredAgentSessionTabId(launch.sessionId) + const groups = state.groupsByWorktree[address.worktreeId] ?? [] + if (groups.some((group) => group.tabOrder.includes(tabId))) return + const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( + state.groupsByWorktree, + state.activeGroupIdByWorktree, + address.worktreeId, + groups.some((entry) => entry.id === address.targetGroupId) + ? address.targetGroupId + : state.activeGroupIdByWorktree[address.worktreeId] + ) + // Only reload reconstructs a missing slot; live sibling mutations use canonical order. + const preceding = new Set(address.precedingTabIds) + const anchor = group.tabOrder.findLast((id) => preceding.has(id)) + const order = insertTabIdIntoOrder( + group.tabOrder, + state.unifiedTabsByWorktree[address.worktreeId] ?? [], + tabId, + false, + anchor + ) + if (!anchor && address.precedingTabIds.length === 0) { + order.splice(order.indexOf(tabId), 1) + const firstUnpinned = order.findIndex( + (id) => + !state.unifiedTabsByWorktree[address.worktreeId]?.find((tab) => tab.id === id)?.isPinned + ) + order.splice(firstUnpinned < 0 ? order.length : firstUnpinned, 0, tabId) + } + trackSlotAddresses() + useAppStore.setState({ + groupsByWorktree: { + ...groupsByWorktree, + [address.worktreeId]: groupsByWorktree[address.worktreeId].map((entry) => + entry.id === group.id ? { ...entry, tabOrder: order } : entry + ) + }, + activeGroupIdByWorktree, + layoutByWorktree: { + ...state.layoutByWorktree, + [address.worktreeId]: state.layoutByWorktree[address.worktreeId] ?? { + type: 'leaf', + groupId: group.id + } + } + }) +} + +export function removeStructuredLaunchSlot(worktreeId: string, sessionId: string): void { + const state = useAppStore.getState() + const tabId = structuredAgentSessionTabId(sessionId) + if (state.unifiedTabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)) return + const groups = state.groupsByWorktree[worktreeId] ?? [] + if (!groups.some((group) => group.tabOrder.includes(tabId))) return + useAppStore.setState({ + groupsByWorktree: { + ...state.groupsByWorktree, + [worktreeId]: groups.map((group) => ({ + ...group, + tabOrder: group.tabOrder.filter((id) => id !== tabId) + })) + } + }) +} + +export function openStructuredAgentSessionProvisionalTab(args: { + worktreeId: string + executionHostId: ExecutionHostId + sessionId: string + agent: TuiAgent + targetGroupId?: string + activate?: boolean +}): Tab { + const state = useAppStore.getState() + const target = structuredAgentSessionTargetForHost(args.executionHostId) + const existing = findStructuredAgentSessionTab(state.unifiedTabsByWorktree, { + workspaceId: args.worktreeId, + sessionId: args.sessionId, + ...(target ? { target } : {}) + }) + if (existing) { + if (args.activate !== false) { + state.focusGroup(args.worktreeId, existing.groupId) + state.activateTab(existing.id, { worktreeId: args.worktreeId }) + state.setActiveTabType('agent-session', args.worktreeId) + } + return existing + } + const tabId = structuredAgentSessionTabId(args.sessionId) + const record = readStructuredAgentLaunchRecord(args.sessionId) + const address = + record?.executionHostId === args.executionHostId ? record.surfaceAddress : undefined + const group = state.groupsByWorktree?.[args.worktreeId]?.find((entry) => + entry.tabOrder.includes(tabId) + ) + const tab = state.createUnifiedTab(args.worktreeId, 'agent-session', { + id: tabId, + entityId: args.sessionId, + executionHostId: args.executionHostId, + agentSessionAgent: args.agent, + label: defaultAgentChatLabel(args.agent), + targetGroupId: + group?.id ?? + (address?.worktreeId === args.worktreeId ? address.targetGroupId : args.targetGroupId), + activate: args.activate !== false + }) + if (args.activate !== false) state.setActiveTabType('agent-session', args.worktreeId) + return tab +} + +export function materializeStructuredLaunchSurface(launch: LaunchSurface, activate?: false): void { + const address = launch.surfaceAddress + if (!address || launch.executionHostId !== 'local') return + const state = useAppStore.getState() + const owner = structuredAgentSessionFocusOwner({ kind: 'local' }) + const hostTabId = `agent-session:${launch.sessionId}` + const focus = peekWebSessionFocusIntent(owner, address.worktreeId) + openStructuredAgentSessionProvisionalTab({ + ...launch, + worktreeId: address.worktreeId, + activate: + activate !== false && + focus?.hostTabId === hostTabId && + (focus.expectedCurrentLocalTabId === undefined || + focus.expectedCurrentLocalTabId === + resolveWebSessionVisibleTabId(state, address.worktreeId)) + }) + if (activate !== false) clearWebSessionFocusIntentIfMatches(owner, address.worktreeId, hostTabId) +} + +export function restoreStructuredLaunchSurfaces(): void { + const state = useAppStore.getState() + const validWorkspaces = new Set([ + ...state.allWorktrees().map((worktree) => worktree.id), + ...state.folderWorkspaces.map((workspace) => folderWorkspaceToWorktree(workspace).id) + ]) + for (const record of readStructuredAgentLaunchRecords()) { + if ( + record.executionHostId !== 'local' || + record.lifecycle !== 'visibility-unknown' || + !record.surfaceAddress || + !validWorkspaces.has(record.surfaceAddress.worktreeId) || + getExecutionHostIdForWorktree(state, record.surfaceAddress.worktreeId) !== 'local' + ) + continue + reserveStructuredLaunchSlot(record) + materializeStructuredLaunchSurface(record, false) + } +} diff --git a/src/renderer/src/lib/structured-agent-session-launch.ts b/src/renderer/src/lib/structured-agent-session-launch.ts index ae5848f11db8..b0ccbf2316c8 100644 --- a/src/renderer/src/lib/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/structured-agent-session-launch.ts @@ -1,3 +1,4 @@ +import { reserveStructuredLaunchSlot } from './structured-agent-session-launch-surface' import type { TuiAgent } from '../../../shared/tui-agent' import type { ExecutionHostId } from '../../../shared/execution-host' import { @@ -131,7 +132,9 @@ function resetStructuredLaunchCallers(state: StructuredLaunchState): void { function restartStructuredLaunchState(state: StructuredLaunchState): void { const wasVisibilityUnknown = state.visibilityUnknown if (!wasVisibilityUnknown) { + const surfaceAddress = state.intent.surfaceAddress state.intent = retryStructuredAgentSessionLaunchIntent(state.intent) + state.intent.surfaceAddress = surfaceAddress } resetStructuredLaunchCallers(state) delete state.failure @@ -207,6 +210,7 @@ function structuredAgentLaunchState( options.hostSeedOptions ) intent.beforeCreate = options.beforeCreate + intent.surfaceAddress = options.surfaceAddress const text = launchPromptText(options) const stagedPrompt = text ? stageStructuredLaunchPrompt(intent.sessionId, text, promptOwner(options)) @@ -230,6 +234,8 @@ function structuredAgentLaunchState( } state.onHostSeed = (seedOptions) => adoptPairedHostSeed(state, seedOptions) callers.onSettled = () => maybeCleanupLaunchState(state) + setStructuredLaunchState(state) + reserveStructuredLaunchSlot(state.intent) state.promise = publishWithHeldOptions(state, launchAndReconcile(state)) const caller = addStructuredLaunchCaller({ group: state.callers, diff --git a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts index 48dedba95966..dfbe39d9fbc3 100644 --- a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts +++ b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts @@ -1,6 +1,4 @@ import type { Tab } from '../../../shared/tab-types' -import { defaultAgentChatLabel } from '../../../shared/agent-session-chat-label' -import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' import type { AgentSessionLaunchPlan, AgentSessionLaunchTarget @@ -27,15 +25,10 @@ import { import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' import { holdEmptyWorkspaceDefaultSurfaceForLaunch } from './empty-workspace-default-surface-claims' import { - clearWebSessionFocusIntentIfMatches, - peekWebSessionFocusIntent, - resolveWebSessionVisibleTabId -} from '@/runtime/web-session-focus-intent' -import { - deleteStructuredLaunchStateIfCurrent, - getStructuredLaunchStateBySessionId, - notifyStructuredLaunchListeners -} from './structured-agent-session-launch-registry' + captureStructuredLaunchSurfaceAddress, + openStructuredAgentSessionProvisionalTab +} from './structured-agent-session-launch-surface' +export { openStructuredAgentSessionProvisionalTab } from './structured-agent-session-launch-surface' type LocalProvisionalLaunch = StructuredAgentLaunchHandle & { tab: Tab } @@ -45,46 +38,6 @@ export type StructuredAgentSessionProvisionalLaunch = | HostAdmittedStructuredLaunch | (StructuredAgentLaunchHandle & { tab: null }) -export function openStructuredAgentSessionProvisionalTab(args: { - worktreeId: string - /** The host the chat is created on; every later operation on the tab reads it. */ - executionHostId: ExecutionHostId - sessionId: string - agent: TuiAgent - targetGroupId?: string - activate?: boolean -}): Tab { - const state = useAppStore.getState() - const tabId = structuredAgentSessionTabId(args.sessionId) - const existing = (state.unifiedTabsByWorktree[args.worktreeId] ?? []).find( - (candidate) => - candidate.contentType === 'agent-session' && - candidate.entityId === args.sessionId && - (!candidate.executionHostId || candidate.executionHostId === args.executionHostId) - ) - if (existing) { - if (args.activate !== false) { - state.focusGroup(args.worktreeId, existing.groupId) - state.activateTab(existing.id, { worktreeId: args.worktreeId }) - state.setActiveTabType('agent-session', args.worktreeId) - } - return existing - } - const tab = state.createUnifiedTab(args.worktreeId, 'agent-session', { - id: tabId, - entityId: args.sessionId, - executionHostId: args.executionHostId, - agentSessionAgent: args.agent, - label: defaultAgentChatLabel(args.agent), - ...(args.targetGroupId ? { targetGroupId: args.targetGroupId } : {}), - activate: args.activate !== false - }) - if (args.activate !== false) { - state.setActiveTabType('agent-session', args.worktreeId) - } - return tab -} - /** The host a structured launch would run on, which admits the chat before it exists. */ export function structuredLaunchOwner( plan: Pick, @@ -134,6 +87,15 @@ export function beginStructuredAgentSessionProvisionalLaunch( if (!args.deferPublication && args.beforeOpen?.() === false) { return null } + if (args.deferPublication && !args.target?.surfaceAddress) { + args = { + ...args, + target: { + ...args.target, + surfaceAddress: captureStructuredLaunchSurfaceAddress(worktreeId, args.targetGroupId) + } + } + } return beginHostAdmittedStructuredLaunch({ plan: args.plan, hooks: args.hooks, @@ -217,39 +179,9 @@ function beginDeferredPublication( releaseHold() return null } - const launch = handle - const target = structuredAgentSessionTargetForHost(launch.executionHostId) - const settlement = launch.settlement - .then((result) => { - if (result.kind === 'structured' || result.kind === 'visibility-unknown') { - const state = useAppStore.getState() - const owner = target && structuredAgentSessionFocusOwner(target) - const focus = owner && peekWebSessionFocusIntent(owner, worktreeId) - const hostTabId = `agent-session:${launch.sessionId}` - const activate = - args.activate !== false && - focus?.hostTabId === hostTabId && - (focus.expectedCurrentLocalTabId === undefined || - focus.expectedCurrentLocalTabId === resolveWebSessionVisibleTabId(state, worktreeId)) - openStructuredAgentSessionProvisionalTab({ - worktreeId, - executionHostId: launch.executionHostId, - sessionId: launch.sessionId, - agent: args.plan.agent, - ...(args.targetGroupId ? { targetGroupId: args.targetGroupId } : {}), - activate - }) - if (owner) { - clearWebSessionFocusIntentIfMatches(owner, worktreeId, hostTabId) - } - } else if (!launch.joined && (result.kind === 'failed' || result.kind === 'cancelled')) { - const failed = getStructuredLaunchStateBySessionId(launch.sessionId) - if (failed?.callers.outcome === 'failed' && deleteStructuredLaunchStateIfCurrent(failed)) { - notifyStructuredLaunchListeners() - } - } - return result - }) - .finally(releaseHold) - return { ...launch, tab: null, settlement } + return { + ...handle, + tab: null, + settlement: handle.settlement.finally(releaseHold) + } } diff --git a/src/renderer/src/lib/workspace-session-hydration-keys.ts b/src/renderer/src/lib/workspace-session-hydration-keys.ts index bcfce2c9eae0..4a550c5372c8 100644 --- a/src/renderer/src/lib/workspace-session-hydration-keys.ts +++ b/src/renderer/src/lib/workspace-session-hydration-keys.ts @@ -1,3 +1,4 @@ +import { readStructuredAgentLaunchRecords } from './structured-agent-session-launch-persistence' import type { ExecutionHostId } from '../../../shared/execution-host' import { parseExecutionHostId } from '../../../shared/execution-host' import type { WorkspaceKey } from '../../../shared/folder-workspace-types' @@ -157,6 +158,10 @@ export function collectWorktreeHydrationRepoIdsFromSession( // Why: a repo referenced only by activeRepoId (no active worktree, no tabs) still needs // enumeration so hydrateWorkspaceSession can restore its main worktree from worktreesByRepo. addWorktreeRepoId(session.activeRepoId) + for (const record of readStructuredAgentLaunchRecords()) { + if (record.executionHostId === 'local' && record.surfaceAddress) + addWorktreeRepoId(record.surfaceAddress.worktreeId) + } return [...repoIds].filter(Boolean).sort() } diff --git a/src/renderer/src/lib/workspace-session-unified-tabs.ts b/src/renderer/src/lib/workspace-session-unified-tabs.ts index f75ca4499192..bc51c96ac45e 100644 --- a/src/renderer/src/lib/workspace-session-unified-tabs.ts +++ b/src/renderer/src/lib/workspace-session-unified-tabs.ts @@ -1,3 +1,4 @@ +import { structuredLaunchSlotIds } from './structured-agent-session-launch-persistence' import type { Tab, TabGroup, TabGroupLayoutNode } from '../../../shared/tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' import type { WorkspaceSessionSnapshot } from './workspace-session' @@ -28,7 +29,11 @@ function prunePersistedLayoutForGroups( return { ...root, first, second } } -function buildPersistedGroupsForWorktree(tabs: Tab[], groups: TabGroup[]): TabGroup[] { +function buildPersistedGroupsForWorktree( + tabs: Tab[], + groups: TabGroup[], + worktreeId: string +): TabGroup[] { const validTabIds = new Set(tabs.map((tab) => tab.id)) const tabIdsByGroup = new Map() for (const tab of tabs) { @@ -39,18 +44,19 @@ function buildPersistedGroupsForWorktree(tabs: Tab[], groups: TabGroup[]): TabGr return groups .map((group) => { + const slots = structuredLaunchSlotIds(worktreeId, group.id) const orderedTabIds = new Set([ - ...group.tabOrder.filter((tabId) => validTabIds.has(tabId)), + ...group.tabOrder.filter((tabId) => validTabIds.has(tabId) || slots.has(tabId)), ...(tabIdsByGroup.get(group.id) ?? []) ]) const tabOrder = Array.from(orderedTabIds) const activeTabId = - group.activeTabId && orderedTabIds.has(group.activeTabId) ? group.activeTabId : null + group.activeTabId && validTabIds.has(group.activeTabId) ? group.activeTabId : null return { ...group, activeTabId, tabOrder, - recentTabIds: group.recentTabIds?.filter((tabId) => orderedTabIds.has(tabId)) + recentTabIds: group.recentTabIds?.filter((tabId) => validTabIds.has(tabId)) } }) .filter((group) => group.tabOrder.length > 0) @@ -78,18 +84,18 @@ export function buildPersistedUnifiedTabSessionData( for (const worktreeId of worktreeIds) { const tabs = sourceTabs[worktreeId] ?? [] - if (tabs.length === 0) { + if (tabs.length === 0 && structuredLaunchSlotIds(worktreeId).size === 0) { continue } - const groups = buildPersistedGroupsForWorktree(tabs, sourceGroups[worktreeId] ?? []) + const groups = buildPersistedGroupsForWorktree(tabs, sourceGroups[worktreeId] ?? [], worktreeId) if (groups.length === 0) { continue } const groupIds = new Set(groups.map((group) => group.id)) const persistedTabs = tabs.filter((tab) => groupIds.has(tab.groupId)) - if (persistedTabs.length === 0) { + if (persistedTabs.length === 0 && structuredLaunchSlotIds(worktreeId).size === 0) { continue } diff --git a/src/renderer/src/runtime/web-session-client-owned-tab-placement.ts b/src/renderer/src/runtime/web-session-client-owned-tab-placement.ts index 564348a105d5..96fea7c8668d 100644 --- a/src/renderer/src/runtime/web-session-client-owned-tab-placement.ts +++ b/src/renderer/src/runtime/web-session-client-owned-tab-placement.ts @@ -1,3 +1,4 @@ +import { structuredLaunchSlotIds } from '@/lib/structured-agent-session-launch-persistence' import type { TabGroup, TabGroupLayoutNode } from '../../../shared/tab-types' import { pickNextActiveTab, @@ -109,9 +110,12 @@ export function reconcileClientOwnedTabPlacement( activeTabId: group.activeTabId ? rekeyTabId(group.activeTabId) : group.activeTabId, recentTabIds: (group.recentTabIds ?? []).map(rekeyTabId) } + const slots = structuredLaunchSlotIds(input.worktreeId, group.id) working.set(group.id, { group: rekeyed, - tabOrder: rekeyed.tabOrder.filter((tabId) => input.validUnifiedTabIds.has(tabId)) + tabOrder: rekeyed.tabOrder.filter( + (tabId) => input.validUnifiedTabIds.has(tabId) || slots.has(tabId) + ) }) groupOrder.push(group.id) } @@ -195,25 +199,26 @@ export function reconcileClientOwnedTabPlacement( continue } const { group, tabOrder } = entry + const realOrder = tabOrder.filter((id) => input.validUnifiedTabIds.has(id)) const intentActive = - input.intentTabId && tabOrder.includes(input.intentTabId) ? input.intentTabId : null + input.intentTabId && realOrder.includes(input.intentTabId) ? input.intentTabId : null const displacedActive = - group.activeTabId && !tabOrder.includes(group.activeTabId) ? group.activeTabId : null + group.activeTabId && !realOrder.includes(group.activeTabId) ? group.activeTabId : null // Why: a host-side close (or a placement move away) must land the user where a local // close would (MRU, then neighbor), picking only among tabs surviving this snapshot. const repairOrder = displacedActive - ? group.tabOrder.filter((tabId) => tabOrder.includes(tabId) || tabId === displacedActive) + ? group.tabOrder.filter((tabId) => realOrder.includes(tabId) || tabId === displacedActive) : null const activeTabId = intentActive ?? (displacedActive && repairOrder ? (pickNextActiveTab(repairOrder, group.recentTabIds, displacedActive) ?? - tabOrder[0] ?? + realOrder[0] ?? null) - : (group.activeTabId ?? tabOrder[0] ?? null)) + : (group.activeTabId ?? realOrder[0] ?? null)) const validActiveTabId = - activeTabId && tabOrder.includes(activeTabId) ? activeTabId : (tabOrder[0] ?? null) - const sanitizedRecent = sanitizeRecentTabIds(group.recentTabIds, tabOrder) + activeTabId && realOrder.includes(activeTabId) ? activeTabId : (realOrder[0] ?? null) + const sanitizedRecent = sanitizeRecentTabIds(group.recentTabIds, realOrder) // Why: only explicit intent or a close/move successor is a visit; retaining the active tab or // structurally filling an empty group must not reorder MRU. const recordsVisit = validActiveTabId === intentActive || displacedActive !== null diff --git a/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts b/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts index 445950ce97b2..ddf348a0c4c8 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/terminal-surfaces.ts @@ -1,3 +1,4 @@ +import { readStructuredAgentLaunchRecord } from '@/lib/structured-agent-session-launch-persistence' import type { RuntimeMobileSessionTabsResult, RuntimeMobileSessionAgentTab @@ -104,6 +105,13 @@ export function buildMirroredAgentTabs( candidate.contentType === 'agent-session' && candidate.entityId === tab.sessionId ) + const launch = readStructuredAgentLaunchRecord(tab.sessionId) + const address = + executionHostId === 'local' && + launch?.executionHostId === executionHostId && + launch.surfaceAddress?.worktreeId === snapshot.worktree + ? launch.surfaceAddress + : undefined const baseId = structuredAgentSessionTabId(tab.sessionId) let localId = existing?.id ?? baseId if (!existing || assignedIds.has(localId)) { @@ -121,7 +129,11 @@ export function buildMirroredAgentTabs( entityId: tab.sessionId, // Keep the local group while a provisional tab is promoted; host placement can lag the // user's split choice and must not move the mounted pane during adoption. - groupId: existing?.groupId ?? hostGroupIdByTabId.get(tab.id) ?? fallbackGroupId, + groupId: + existing?.groupId ?? + address?.targetGroupId ?? + hostGroupIdByTabId.get(tab.id) ?? + fallbackGroupId, worktreeId: snapshot.worktree, executionHostId, contentType: 'agent-session', diff --git a/src/renderer/src/store/slices/tab-group-state.ts b/src/renderer/src/store/slices/tab-group-state.ts index 85fe8c5da228..8ee88c9d2fb1 100644 --- a/src/renderer/src/store/slices/tab-group-state.ts +++ b/src/renderer/src/store/slices/tab-group-state.ts @@ -136,8 +136,13 @@ export function pushRecentTabId(recent: string[] | undefined, tabId: string): st export function pickNextActiveTab( tabOrder: string[], recentTabIds: string[] | undefined, - closingTabId: string + closingTabId: string, + tabs?: readonly Pick[] ): string | null { + if (tabs) { + const realIds = new Set(tabs.map((tab) => tab.id)) + tabOrder = tabOrder.filter((id) => realIds.has(id)) + } const sanitized = sanitizeRecentTabIds(recentTabIds, tabOrder) // The closing tab is typically at the tail (it's the active tab). Walk back // from the tail looking for the most-recent *other* tab still present. diff --git a/src/renderer/src/store/slices/tabs-hydration.ts b/src/renderer/src/store/slices/tabs-hydration.ts index 39c49047e5a3..9419d4d715e1 100644 --- a/src/renderer/src/store/slices/tabs-hydration.ts +++ b/src/renderer/src/store/slices/tabs-hydration.ts @@ -1,3 +1,4 @@ +import { structuredLaunchSlotIds } from '@/lib/structured-agent-session-launch-persistence' import type { Tab, TabGroup, TabGroupLayoutNode } from '../../../../shared/tab-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' import { isValidTerminalTabId } from '../../../../shared/terminal-tab-id' @@ -160,13 +161,16 @@ export function buildHydratedTabState( const tabIdAliasesByGroup = tabIdAliasesByWorktree[worktreeId] const tabOwners = resolveTabGroupOwners(hydratedTabsForWorktree, groups, tabIdAliasesByGroup) const validatedGroups = appendOwnedTabIdsToGroups(groups, tabOwners).map((g) => { + const slots = structuredLaunchSlotIds(worktreeId, g.id) const tabIdAliases = tabIdAliasesByGroup?.get(g.id) const canonicalTabId = (tabId: string): string => tabIdAliases?.get(tabId) ?? tabId // Why: persisted tabOrder can contain duplicates from older buggy // writes. Deduping during hydration restores the store invariant before // later group operations branch on tab counts or neighbors. const tabOrder = dedupeTabOrder( - g.tabOrder.map(canonicalTabId).filter((tid) => tabOwners.get(tid) === g.id) + g.tabOrder + .map(canonicalTabId) + .filter((tid) => tabOwners.get(tid) === g.id || slots.has(tid)) ) const canonicalActiveTabId = g.activeTabId ? canonicalTabId(g.activeTabId) : null const activeTabId = @@ -177,7 +181,10 @@ export function buildHydratedTabState( // against the live tabOrder, then ensure the current active tab sits at // the tail so the first close after restore jumps back to the previous // tab rather than falling through to neighbor selection. - const sanitizedRecent = sanitizeRecentTabIds(g.recentTabIds?.map(canonicalTabId), tabOrder) + const sanitizedRecent = sanitizeRecentTabIds( + g.recentTabIds?.map(canonicalTabId), + tabOrder.filter((id) => tabOwners.get(id) === g.id) + ) const recentTabIds = activeTabId && sanitizedRecent.at(-1) !== activeTabId ? [...sanitizedRecent.filter((id) => id !== activeTabId), activeTabId] diff --git a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts index 7eb871fc868f..2b6a5097a9f2 100644 --- a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts @@ -84,7 +84,12 @@ export function createTabsCloseActions( group?.activeTabId === tabId ? wasLastTab ? null - : pickNextActiveTab(dedupedGroupOrder, group.recentTabIds, tabId) + : pickNextActiveTab( + dedupedGroupOrder, + group.recentTabIds, + tabId, + state.unifiedTabsByWorktree[worktreeId] + ) : (group?.activeTabId ?? null) const nextRecentTabIds = sanitizeRecentTabIds( (group?.recentTabIds ?? []).filter((id) => id !== tabId), diff --git a/src/renderer/src/store/slices/tabs/tabs-create-actions.ts b/src/renderer/src/store/slices/tabs/tabs-create-actions.ts index 5cda1b606a3f..c2b991c0034d 100644 --- a/src/renderer/src/store/slices/tabs/tabs-create-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-create-actions.ts @@ -1,3 +1,4 @@ +import { structuredLaunchSlotIds } from '@/lib/structured-agent-session-launch-persistence' import { createBrowserUuid } from '@/lib/browser-uuid' import { getActiveExecutionHostIdForWorktree } from '@/lib/unified-tab-host-ownership' import type { Tab, TabGroup } from '../../../../../shared/tab-types' @@ -84,13 +85,18 @@ export function createTabsCreateActions( const executionHostId = init?.executionHostId ?? getActiveExecutionHostIdForWorktree(state, worktreeId) // Why: preview replacement may have removed the anchor; the order then appends in-partition. - nextOrder = insertTabIdIntoOrder( - nextOrder, - nextTabs, - id, - init?.isPinned === true, - placement.anchorTabId - ) + nextOrder = + contentType === 'agent-session' && + nextOrder.includes(id) && + structuredLaunchSlotIds(worktreeId, group.id).has(id) + ? nextOrder + : insertTabIdIntoOrder( + nextOrder, + nextTabs, + id, + init?.isPinned === true, + placement.anchorTabId + ) const insertedIndex = nextOrder.indexOf(id) // Why always: preview replacement can leave a gap, so an append alone would reuse a sibling's sortOrder. nextTabs = applyTabOrderSortValues(nextTabs, nextOrder) diff --git a/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts b/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts index 19d067fac5d3..8d0bb2f82468 100644 --- a/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-drop-actions.ts @@ -119,7 +119,12 @@ export function createTabsDropActions( activeTabId: group.activeTabId === tabId ? // Why: same MRU-aware fallback as moveUnifiedTabToGroup — the drag keeps the user on their previously-active tab. - pickNextActiveTab(dedupedSourceGroupOrder, sourceGroup.recentTabIds, tabId) + pickNextActiveTab( + dedupedSourceGroupOrder, + sourceGroup.recentTabIds, + tabId, + state.unifiedTabsByWorktree[worktreeId] + ) : group.activeTabId, tabOrder: sourceOrder, recentTabIds: sourceRecentTabIds diff --git a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts index a779ce3b2fd7..50bdafaf0090 100644 --- a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts @@ -128,7 +128,8 @@ export function createTabsGroupActions( const group = (state.groupsByWorktree[worktreeId] ?? []).find( (candidate) => candidate.id === groupId ) - if (!group || group.tabOrder.length > 0) { + const realIds = new Set((state.unifiedTabsByWorktree[worktreeId] ?? []).map((tab) => tab.id)) + if (!group || group.tabOrder.some((id) => realIds.has(id))) { return false } set((current) => { diff --git a/src/renderer/src/store/slices/tabs/tabs-move-actions.ts b/src/renderer/src/store/slices/tabs/tabs-move-actions.ts index fa28767fac45..68e600becfd8 100644 --- a/src/renderer/src/store/slices/tabs/tabs-move-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-move-actions.ts @@ -59,7 +59,12 @@ export function createTabsMoveActions( activeTabId: group.activeTabId === tabId ? // Why: keep MRU-aware selection so the user lands on their previously-focused tab, not a visual neighbor. - pickNextActiveTab(dedupedSourceGroupOrder, sourceGroup.recentTabIds, tabId) + pickNextActiveTab( + dedupedSourceGroupOrder, + sourceGroup.recentTabIds, + tabId, + state.unifiedTabsByWorktree[worktreeId] + ) : group.activeTabId, tabOrder: sourceOrder, recentTabIds: sourceRecentTabIds diff --git a/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts b/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts index 7cd446f76a33..561a14837059 100644 --- a/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts +++ b/src/renderer/src/store/slices/tabs/tabs-reconciliation.ts @@ -1,3 +1,4 @@ +import { structuredLaunchSlotIds } from '@/lib/structured-agent-session-launch-persistence' import type { AppState } from '../../types' import type { Tab } from '../../../../../shared/tab-types' import { dedupeTabOrder } from '../../../../../shared/workspace-layout/tab-order' @@ -136,15 +137,17 @@ export function projectWorktreeTabModelReconciliation( renderableTabs.length === reconciledUnifiedTabs.length ? reconciledUnifiedTabs : renderableTabs const validTabIds = new Set(validTabs.map((tab) => tab.id)) const nextGroupsWithEmpty = reconciledGroups.map((group) => { - const tabOrder = group.tabOrder.filter((tabId) => validTabIds.has(tabId)) + const slots = structuredLaunchSlotIds(worktreeId, group.id) + const tabOrder = group.tabOrder.filter((tabId) => validTabIds.has(tabId) || slots.has(tabId)) + const realOrder = tabOrder.filter((id) => validTabIds.has(id)) const activeTabId = group.activeTabId && validTabIds.has(group.activeTabId) ? group.activeTabId - : (tabOrder[0] ?? null) + : (realOrder[0] ?? null) const tabOrderUnchanged = tabOrder.length === group.tabOrder.length && tabOrder.every((tabId, index) => tabId === group.tabOrder[index]) - const recentTabIds = sanitizeRecentTabIds(group.recentTabIds, tabOrder) + const recentTabIds = sanitizeRecentTabIds(group.recentTabIds, realOrder) const recentUnchanged = recentTabIds.length === (group.recentTabIds ?? []).length && recentTabIds.every((id, index) => id === (group.recentTabIds ?? [])[index]) diff --git a/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts b/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts index 6470ffcb5509..9293bf4e026c 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts @@ -1,3 +1,4 @@ +import { readStructuredAgentLaunchRecords } from '@/lib/structured-agent-session-launch-persistence' import type { AppState } from '../../../types' import type { WorktreePurgeTarget, WorktreePurgeTargets } from '../../worktree-helpers' import { forgetHugeRepoWarningDismissalsForWorktrees } from '@/lib/source-control-huge-repo-warning-dismissals' @@ -59,6 +60,23 @@ export function buildWorktreePurgeState( cancelledSessionIds.add(launch.intent.sessionId) } } + for (const record of readStructuredAgentLaunchRecords()) { + const worktreeId = record.surfaceAddress?.worktreeId + if ( + record.executionHostId === 'local' && + worktreeId && + worktreeIdSet.has(worktreeId) && + !cancelledSessionIds.has(record.sessionId) + ) { + markStructuredAgentSessionLaunchCancelledSilently( + worktreeId, + record.sessionId, + record.executionHostId + ) + discardStructuredAgentSessionChatSends(record.sessionId) + cancelledSessionIds.add(record.sessionId) + } + } for (const worktreeId of worktreeIdSet) { // A launch tab that never spawned has no spawn left to answer its prompt's wait. for (const tab of s.tabsByWorktree[worktreeId] ?? []) { From a836a6c77b1b81db7af7120d0afd466576735304 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:47:18 -0700 Subject: [PATCH 24/38] test(chat): allow host evidence in create routing --- .../methods/structured-agent-session.test.ts | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/main/runtime/rpc/methods/structured-agent-session.test.ts b/src/main/runtime/rpc/methods/structured-agent-session.test.ts index f67dd8ed74fb..da6461b57a3c 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session.test.ts @@ -383,10 +383,12 @@ describe('method routing', () => { } const created = await call('agentSession.create', params, STRUCTURED_CLIENT) expect(created).toMatchObject({ ok: true, result: { ok: true } }) - expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith({ - ...params, - callerKey: 'trusted-local:runtime' - }) + expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ + ...params, + callerKey: 'trusted-local:runtime' + }) + ) expect(hostCalls.attach).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ @@ -536,10 +538,12 @@ describe('method routing', () => { ok: true, result: { ok: true } }) - expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith({ - ...params, - callerKey: 'trusted-local:runtime' - }) + expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ + ...params, + callerKey: 'trusted-local:runtime' + }) + ) } ) @@ -570,10 +574,12 @@ describe('method routing', () => { } const created = await call('agentSession.create', params, STRUCTURED_CLIENT) expect(created).toMatchObject({ ok: true, result: { ok: true } }) - expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith({ - ...params, - callerKey: 'trusted-local:runtime' - }) + expect(runtimeCalls.resolveStructuredAgentSessionCreateIntent).toHaveBeenCalledWith( + expect.objectContaining({ + ...params, + callerKey: 'trusted-local:runtime' + }) + ) expect(hostCalls.attach).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ From 09b29bc8cdbdef8899a8d3b31c152793dc3be0c9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:51:33 -0700 Subject: [PATCH 25/38] Satisfy launch publication checks and scope slot cleanup --- .../app-shell/use-app-startup-hydration.ts | 6 +- .../tab-bar/cli-chat-resume-run.test.ts | 14 ++-- ...d-agent-session-launch-outcome-tracking.ts | 4 +- ...tructured-agent-session-launch-registry.ts | 7 +- ...structured-agent-session-launch-surface.ts | 70 ++++++++++++------- ...tructured-agent-session-provisional-tab.ts | 2 - .../lib/workspace-session-hydration-keys.ts | 3 +- 7 files changed, 69 insertions(+), 37 deletions(-) diff --git a/src/renderer/src/app-shell/use-app-startup-hydration.ts b/src/renderer/src/app-shell/use-app-startup-hydration.ts index b5bb87b1e67f..f31f4f5d6338 100644 --- a/src/renderer/src/app-shell/use-app-startup-hydration.ts +++ b/src/renderer/src/app-shell/use-app-startup-hydration.ts @@ -273,11 +273,11 @@ export function useAppStartupHydration(onOnboardingLoaded: (state: OnboardingSta await timeRendererStartupStep('recover-legacy-worker-terminals-pre-reconnect', () => window.api.app.recoverLegacyWorkerTerminalsForRendererStartup() ) - await timeRendererStartupStep('terminal-provider-snapshot-capabilities', () => { - return refreshTerminalProviderSnapshotCapabilities( + await timeRendererStartupStep('terminal-provider-snapshot-capabilities', () => + refreshTerminalProviderSnapshotCapabilities( collectTerminalProviderSnapshotPtyIds(useAppStore.getState()) ) - }) + ) reconnectStarted = true await timeRendererStartupStep('reconnect-terminals', () => actions.reconnectPersistedTerminals(abortController.signal) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index bc42b4253c30..03bb04c48e17 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -49,7 +49,7 @@ import { import { reserveStructuredLaunchSlot, restoreStructuredLaunchSurfaces, - resetStructuredLaunchSurfaceForTests + stopStructuredLaunchSlotTracking } from '@/lib/structured-agent-session-launch-surface' import { applyStructuredSessionTabSnapshots } from '@/runtime/local-structured-session-tabs-sync/snapshot-apply' import { resetLocalStructuredSessionVersionForTests } from '@/runtime/local-structured-session-tabs-sync/inventory-generation-fence' @@ -67,6 +67,7 @@ import { import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims' import { clearWebSessionFocusIntent, + peekWebSessionFocusIntent, resetWebSessionFocusIntentForTests } from '@/runtime/web-session-focus-intent' import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' @@ -102,7 +103,7 @@ beforeEach(() => { vi.clearAllMocks() resetLocalStructuredSessionVersionForTests() resetWebSessionTabsSnapshotFreshnessForTests() - resetStructuredLaunchSurfaceForTests() + stopStructuredLaunchSlotTracking() localStorage.clear() resetStructuredAgentLaunchPersistenceForTests() resetStructuredAgentLaunchRegistryForTests() @@ -293,7 +294,9 @@ describe('CLI identity resume through the existing launch owner', () => { split: { splitDirection: 'right', sourceGroupId: e.groupId } }) clearWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1') - if (first === 'inventory') applyStructuredSessionTabSnapshots([snapshot(sessionId)]) + if (first === 'inventory') { + applyStructuredSessionTabSnapshots([snapshot(sessionId)]) + } reply.resolve({ ok: true, value: { sessionId, fence: 1 } }) await running expect( @@ -349,7 +352,7 @@ describe('CLI identity resume through the existing launch owner', () => { writeStructuredAgentLaunchRecord(record) reserveStructuredLaunchSlot(record) const session = buildWorkspaceSessionPayload(useAppStore.getState()) - resetStructuredLaunchSurfaceForTests() + stopStructuredLaunchSlotTracking() resetStructuredAgentLaunchPersistenceForTests() resetStructuredAgentLaunchRegistryForTests() useAppStore.setState(useAppStore.getInitialState(), true) @@ -361,6 +364,9 @@ describe('CLI identity resume through the existing launch owner', () => { restoreStructuredLaunchSurfaces() applyStructuredSessionTabSnapshots([snapshot()]) expect(mocks.call).not.toHaveBeenCalled() + expect( + peekWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), 'wt-1') + ).toBeNull() expect(tabs()).toHaveLength(1) expect(getStructuredAgentSessionLaunchLifecycle('wt-1', 'reload-pending')).toBe( 'visibility-unknown' diff --git a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts index ad825bc0c924..548b1c4c93b3 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts @@ -73,7 +73,9 @@ export function trackLaunchSettlement( if (state.promise !== promise) { return } - if (state.cancelled) return + if (state.cancelled) { + return + } materializeStructuredLaunchSurface(state.intent) settleStructuredLaunchCallers(state.callers, 'published') notifyStructuredLaunchListeners() diff --git a/src/renderer/src/lib/structured-agent-session-launch-registry.ts b/src/renderer/src/lib/structured-agent-session-launch-registry.ts index 964844ad1bb6..ae6788f26f7c 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-registry.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-registry.ts @@ -226,6 +226,9 @@ function markStructuredAgentSessionLaunchCancelledInternal( ): boolean { const alreadyCancelled = hasStructuredAgentLaunchCancellationTombstonePersisted(sessionId) const state = getStructuredLaunchStateBySessionId(sessionId) + const surfaceAddress = + state?.intent.surfaceAddress ?? + getPersistedStructuredAgentLaunchRecord(sessionId)?.surfaceAddress if (matchesLaunchWorktree(state, worktreeId) && state) { // The launch's own owner outranks the caller's: it is the host the create was sent to. markStructuredAgentLaunchCancellation( @@ -242,7 +245,9 @@ function markStructuredAgentSessionLaunchCancelledInternal( } else if (!alreadyCancelled) { markStructuredAgentLaunchCancellation(sessionId, executionHostId, alreadyCancelled) } - if (notify) removeStructuredLaunchSlot(worktreeId, sessionId) + if (notify && surfaceAddress) { + removeStructuredLaunchSlot(worktreeId, sessionId) + } if (!alreadyCancelled && notify) { notifyStructuredLaunchListeners() } diff --git a/src/renderer/src/lib/structured-agent-session-launch-surface.ts b/src/renderer/src/lib/structured-agent-session-launch-surface.ts index 45d4704665d0..fd1f09cb9480 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-surface.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-surface.ts @@ -56,32 +56,32 @@ export function captureStructuredLaunchSurfaceAddress( let stopTrackingSlots: (() => void) | undefined -export function resetStructuredLaunchSurfaceForTests(): void { +export function stopStructuredLaunchSlotTracking(): void { stopTrackingSlots?.() stopTrackingSlots = undefined } function trackSlotAddresses(): void { stopTrackingSlots ??= useAppStore.subscribe((state, previous) => { - if (state.groupsByWorktree === previous.groupsByWorktree) return - const records = readStructuredAgentLaunchRecords().filter( - (record) => - record.surfaceAddress && - record.executionHostId === 'local' && - !state.unifiedTabsByWorktree[record.surfaceAddress.worktreeId]?.some( - (tab) => tab.id === structuredAgentSessionTabId(record.sessionId) - ) - ) - if (records.length === 0) resetStructuredLaunchSurfaceForTests() - for (const record of records) { + if (state.groupsByWorktree === previous.groupsByWorktree) { + return + } + let hasHiddenSlot = false + for (const record of readStructuredAgentLaunchRecords()) { const address = record.surfaceAddress - if (!address || record.executionHostId !== 'local') continue + if (!address || record.executionHostId !== 'local') { + continue + } const tabId = structuredAgentSessionTabId(record.sessionId) - if (state.unifiedTabsByWorktree[address.worktreeId]?.some((tab) => tab.id === tabId)) continue + if (state.unifiedTabsByWorktree[address.worktreeId]?.some((tab) => tab.id === tabId)) { + continue + } + hasHiddenSlot = true if ( state.groupsByWorktree[address.worktreeId] === previous.groupsByWorktree[address.worktreeId] - ) + ) { continue + } const group = state.groupsByWorktree[address.worktreeId]?.find((entry) => entry.tabOrder.includes(tabId) ) @@ -91,19 +91,28 @@ function trackSlotAddresses(): void { precedingTabIds: group ? group.tabOrder.slice(0, group.tabOrder.indexOf(tabId)) : [] } const launch = getStructuredLaunchStateBySessionId(record.sessionId) - if (launch) launch.intent.surfaceAddress = surfaceAddress + if (launch) { + launch.intent.surfaceAddress = surfaceAddress + } writeStructuredAgentLaunchRecord({ ...record, surfaceAddress }) } + if (!hasHiddenSlot) { + stopStructuredLaunchSlotTracking() + } }) } export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { const address = launch.surfaceAddress - if (!address || launch.executionHostId !== 'local') return + if (!address || launch.executionHostId !== 'local') { + return + } const state = useAppStore.getState() const tabId = structuredAgentSessionTabId(launch.sessionId) const groups = state.groupsByWorktree[address.worktreeId] ?? [] - if (groups.some((group) => group.tabOrder.includes(tabId))) return + if (groups.some((group) => group.tabOrder.includes(tabId))) { + return + } const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( state.groupsByWorktree, state.activeGroupIdByWorktree, @@ -128,7 +137,7 @@ export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { (id) => !state.unifiedTabsByWorktree[address.worktreeId]?.find((tab) => tab.id === id)?.isPinned ) - order.splice(firstUnpinned < 0 ? order.length : firstUnpinned, 0, tabId) + order.splice(firstUnpinned === -1 ? order.length : firstUnpinned, 0, tabId) } trackSlotAddresses() useAppStore.setState({ @@ -152,9 +161,13 @@ export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { export function removeStructuredLaunchSlot(worktreeId: string, sessionId: string): void { const state = useAppStore.getState() const tabId = structuredAgentSessionTabId(sessionId) - if (state.unifiedTabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)) return + if (state.unifiedTabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)) { + return + } const groups = state.groupsByWorktree[worktreeId] ?? [] - if (!groups.some((group) => group.tabOrder.includes(tabId))) return + if (!groups.some((group) => group.tabOrder.includes(tabId))) { + return + } useAppStore.setState({ groupsByWorktree: { ...state.groupsByWorktree, @@ -207,13 +220,17 @@ export function openStructuredAgentSessionProvisionalTab(args: { (address?.worktreeId === args.worktreeId ? address.targetGroupId : args.targetGroupId), activate: args.activate !== false }) - if (args.activate !== false) state.setActiveTabType('agent-session', args.worktreeId) + if (args.activate !== false) { + state.setActiveTabType('agent-session', args.worktreeId) + } return tab } export function materializeStructuredLaunchSurface(launch: LaunchSurface, activate?: false): void { const address = launch.surfaceAddress - if (!address || launch.executionHostId !== 'local') return + if (!address || launch.executionHostId !== 'local') { + return + } const state = useAppStore.getState() const owner = structuredAgentSessionFocusOwner({ kind: 'local' }) const hostTabId = `agent-session:${launch.sessionId}` @@ -228,7 +245,9 @@ export function materializeStructuredLaunchSurface(launch: LaunchSurface, activa focus.expectedCurrentLocalTabId === resolveWebSessionVisibleTabId(state, address.worktreeId)) }) - if (activate !== false) clearWebSessionFocusIntentIfMatches(owner, address.worktreeId, hostTabId) + if (activate !== false) { + clearWebSessionFocusIntentIfMatches(owner, address.worktreeId, hostTabId) + } } export function restoreStructuredLaunchSurfaces(): void { @@ -244,8 +263,9 @@ export function restoreStructuredLaunchSurfaces(): void { !record.surfaceAddress || !validWorkspaces.has(record.surfaceAddress.worktreeId) || getExecutionHostIdForWorktree(state, record.surfaceAddress.worktreeId) !== 'local' - ) + ) { continue + } reserveStructuredLaunchSlot(record) materializeStructuredLaunchSurface(record, false) } diff --git a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts index dfbe39d9fbc3..e393e1a5b5cc 100644 --- a/src/renderer/src/lib/structured-agent-session-provisional-tab.ts +++ b/src/renderer/src/lib/structured-agent-session-provisional-tab.ts @@ -9,7 +9,6 @@ import type { } from '@/lib/structured-agent-launch-settlement' import { useAppStore } from '@/store' import type { ExecutionHostId } from '../../../shared/execution-host' -import type { TuiAgent } from '../../../shared/tui-agent' import { beginHostAdmittedStructuredLaunch, openDeclinedStructuredLaunchTerminal, @@ -19,7 +18,6 @@ import { } from '@/lib/structured-agent-session-launch-admission' import { resolveStructuredAgentSessionOwner, - structuredAgentSessionFocusOwner, structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' diff --git a/src/renderer/src/lib/workspace-session-hydration-keys.ts b/src/renderer/src/lib/workspace-session-hydration-keys.ts index 4a550c5372c8..50b2b630019e 100644 --- a/src/renderer/src/lib/workspace-session-hydration-keys.ts +++ b/src/renderer/src/lib/workspace-session-hydration-keys.ts @@ -159,8 +159,9 @@ export function collectWorktreeHydrationRepoIdsFromSession( // enumeration so hydrateWorkspaceSession can restore its main worktree from worktreesByRepo. addWorktreeRepoId(session.activeRepoId) for (const record of readStructuredAgentLaunchRecords()) { - if (record.executionHostId === 'local' && record.surfaceAddress) + if (record.executionHostId === 'local' && record.surfaceAddress) { addWorktreeRepoId(record.surfaceAddress.worktreeId) + } } return [...repoIds].filter(Boolean).sort() From 2da98ed9897fc2399f0b68fc3a4022a533ec379c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:20:57 -0700 Subject: [PATCH 26/38] Preserve canonical tab membership on projected reorders --- .../app-shell/use-app-startup-hydration.ts | 6 +- .../tab-bar/cli-chat-resume-run.test.ts | 55 +++++++++++++++++-- .../ipc-events/session-tab-ipc-bridge.ts | 6 +- .../store/slices/tabs/tabs-label-actions.ts | 12 +++- .../store/slices/tabs/tabs-slice-contract.ts | 2 +- src/shared/workspace-layout/tab-order.ts | 47 ++++++++++++++++ 6 files changed, 113 insertions(+), 15 deletions(-) diff --git a/src/renderer/src/app-shell/use-app-startup-hydration.ts b/src/renderer/src/app-shell/use-app-startup-hydration.ts index f31f4f5d6338..b6189e3809a8 100644 --- a/src/renderer/src/app-shell/use-app-startup-hydration.ts +++ b/src/renderer/src/app-shell/use-app-startup-hydration.ts @@ -95,10 +95,8 @@ export function useAppStartupHydration(onOnboardingLoaded: (state: OnboardingSta actions.fetchSettings({ deferOwnerWorktreeVisibilityDefaults: true }) ) // Why: hidden-at-launch PTYs can query before any pane mounts; publish view attributes as soon as settings exist so every PTY owner answers from the composed theme. - publishTerminalViewAttributesAtAppStart( - useAppStore.getState().settings, - getSystemPrefersDark() - ) + const settings = useAppStore.getState().settings + publishTerminalViewAttributesAtAppStart(settings, getSystemPrefersDark()) // Why: start keybindings + onboarding now so their IPC overlaps the local catalog scans; await them at their original spots. The .catch marks rejections handled if an earlier await throws first. // Why: browser session profiles are NOT started early — on a remote runtime the RPC may be unconnected and a failed fetch clears the list. const keybindingsPromise = timeRendererStartupStep('fetch-keybindings', () => diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index 03bb04c48e17..c9ec3938889a 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { CliChatResumeSource } from './cli-chat-resume-source' import type { AgentSessionWireRefusal } from '../../../../shared/agent-session-wire' import type { StructuredAgentSessionCreateParams } from '../../../../shared/structured-agent-session-create' @@ -71,6 +71,7 @@ import { resetWebSessionFocusIntentForTests } from '@/runtime/web-session-focus-intent' import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' +import { registerSessionTabIpcBridge } from '@/hooks/ipc-events/session-tab-ipc-bridge' const SOURCE: CliChatResumeSource = { tabId: 'tab-1', @@ -81,6 +82,7 @@ const SOURCE: CliChatResumeSource = { executionHostId: 'local' } const tabs = () => useAppStore.getState().unifiedTabsByWorktree['wt-1'] ?? [] +afterEach(() => vi.unstubAllGlobals()) function deferred() { let resolve: (value: T) => void = () => {} const promise = new Promise((done) => { @@ -272,10 +274,29 @@ describe('CLI identity resume through the existing launch owner', () => { expect(tabs()).toHaveLength(1) }) - it.each(['reply', 'inventory'] as const)( - 'fills the original slot after sibling drag, append and later selection (%s first)', - async (first) => { + it.each([ + ['reply', 'B', 'B E S R', 'B E S D R'], + ['inventory', 'E', 'S B R E', 'S B D R E'], + ['reply', 'E', 'S B E R', 'S B D E R'], + ['inventory', 'B', 'R S E B', 'R S E D B'] + ])( + 'keeps canonical membership through registered IPC (%s first, move %s to %s)', + async (first, mover, requested, expected) => { const [e, source, browser] = seedTabs() + let move: Parameters[0] = () => {} + vi.stubGlobal('api', { + ...window.api, + ui: { + ...window.api?.ui, + onCloseSessionTab: () => () => {}, + onSessionTabCloseRequest: () => () => {}, + onMoveSessionTab: (callback: typeof move) => { + move = callback + return () => {} + } + } + }) + registerSessionTabIpcBridge([]) const reply = deferred() mocks.call.mockReturnValue(reply.promise) const running = runCliChatResume(SOURCE) @@ -285,10 +306,32 @@ describe('CLI identity resume through the existing launch owner', () => { const store = useAppStore.getState() const order = store.groupsByWorktree['wt-1'][0].tabOrder expect(order).toEqual([e.id, source.id, browser.id, slotId]) - store.reorderUnifiedTabs(e.groupId, [browser.id, e.id, source.id, slotId]) const later = useAppStore .getState() .createUnifiedTab('wt-1', 'editor', { id: 'R', entityId: 'R' }) + const beforeNoop = useAppStore.getState() + move({ + kind: 'reorder', + worktreeId: 'wt-1', + targetGroupId: e.groupId, + tabId: browser.id, + tabOrder: [e.id, source.id, browser.id, later.id] + }) + expect(useAppStore.getState()).toBe(beforeNoop) + move({ + kind: 'reorder', + worktreeId: 'wt-1', + targetGroupId: e.groupId, + tabId: mover, + tabOrder: requested.split(' ') + }) + const expectedOrder = expected.split(' ').map((id) => (id === 'D' ? slotId : id)) + expect(useAppStore.getState().groupsByWorktree['wt-1'][0].tabOrder).toEqual(expectedOrder) + expect(readStructuredAgentLaunchRecord(sessionId)?.surfaceAddress).toEqual({ + worktreeId: 'wt-1', + targetGroupId: e.groupId, + precedingTabIds: expectedOrder.slice(0, expectedOrder.indexOf(slotId)) + }) const other = useAppStore.getState().createUnifiedTab('wt-1', 'editor', { entityId: 'other', split: { splitDirection: 'right', sourceGroupId: e.groupId } @@ -302,7 +345,7 @@ describe('CLI identity resume through the existing launch owner', () => { expect( useAppStore.getState().groupsByWorktree['wt-1'].find((group) => group.id === e.groupId) ?.tabOrder - ).toEqual([browser.id, e.id, source.id, slotId, later.id]) + ).toEqual(expectedOrder) expect(useAppStore.getState().activeGroupIdByWorktree['wt-1']).toBe(other.groupId) useAppStore.getState().moveUnifiedTabToGroup(slotId, other.groupId) applyStructuredSessionTabSnapshots([ diff --git a/src/renderer/src/hooks/ipc-events/session-tab-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/session-tab-ipc-bridge.ts index 7cd2b65efb9b..bfda5742ae48 100644 --- a/src/renderer/src/hooks/ipc-events/session-tab-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/session-tab-ipc-bridge.ts @@ -114,7 +114,11 @@ export function registerSessionTabIpcBridge(unsubs: (() => void)[]): void { const { tabId, targetGroupId } = move const store = useAppStore.getState() if (move.kind === 'reorder') { - store.reorderUnifiedTabs(targetGroupId, move.tabOrder) + store.reorderUnifiedTabs( + targetGroupId, + move.tabOrder.map((id) => resolveWindowTabIdForHostTab(move.worktreeId, id)), + { projectedMoveTabId: resolveWindowTabIdForHostTab(move.worktreeId, tabId) } + ) return } store.dropUnifiedTab(tabId, { diff --git a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts index df3bb17f322a..2d122e1d44b6 100644 --- a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts @@ -5,7 +5,8 @@ import { findTabAndWorktree, patchTab, updateGroup } from '../tab-group-state' import { applyTabOrderSortValues, dedupeTabOrder, - partitionPinnedTabOrder + partitionPinnedTabOrder, + reorderProjectedTabOrder } from '../../../../../shared/workspace-layout/tab-order' import { mirrorTabPinnedToHost, @@ -36,8 +37,13 @@ export function createTabsLabelActions( if (!group) { continue } - // Why: dedupe at the store boundary so each tab keeps one canonical position and later group ops don't branch on duplicate ids. - const nextTabOrder = dedupeTabOrder(tabIds) + // Projected orders own placement; only complete local orders own membership. + const nextTabOrder = opts?.projectedMoveTabId + ? reorderProjectedTabOrder(group.tabOrder, tabIds, opts.projectedMoveTabId) + : dedupeTabOrder(tabIds) + if (nextTabOrder === group.tabOrder) { + return state + } reordered = true const orderMap = new Map(nextTabOrder.map((id, index) => [id, index])) return { diff --git a/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts b/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts index 825408fda764..da53d6354e0d 100644 --- a/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts +++ b/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts @@ -108,7 +108,7 @@ export type TabsSlice = { reorderUnifiedTabs: ( groupId: string, tabIds: string[], - opts?: { recordInteraction?: boolean } + opts?: { recordInteraction?: boolean; projectedMoveTabId?: string } ) => void setTabLabel: (tabId: string, label: string) => void /** Set a tab's view mode (terminal vs native chat). Patches only that tab. */ diff --git a/src/shared/workspace-layout/tab-order.ts b/src/shared/workspace-layout/tab-order.ts index 315965c4293e..edccac5001c0 100644 --- a/src/shared/workspace-layout/tab-order.ts +++ b/src/shared/workspace-layout/tab-order.ts @@ -15,6 +15,53 @@ export function dedupeTabOrder(tabIds: string[]): string[] { return deduped } +/** A projected reorder changes current placement without replacing omitted canonical members. */ +export function reorderProjectedTabOrder( + order: string[], + requestedOrder: readonly string[], + movingTabId: string +): string[] { + const currentIds = new Set(order) + const requested = requestedOrder.filter((id) => currentIds.has(id)) + const positions = new Map(requested.map((id, index) => [id, index])) + const visible = order.filter((id) => positions.has(id)) + if (visible.every((id, index) => id === requested[index])) { + return order + } + const candidates = visible.flatMap((id) => { + const position = positions.get(id) + return id === movingTabId || position === undefined ? [] : [{ id, position }] + }) + const lengths = candidates.map(() => 1) + for (let i = candidates.length - 1; i >= 0; i--) { + for (let j = i + 1; j < candidates.length; j++) { + if (candidates[j].position > candidates[i].position) { + lengths[i] = Math.max(lengths[i], 1 + lengths[j]) + } + } + } + let remaining = Math.max(0, ...lengths) + let previousPosition = -1 + const anchors = new Set() + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i] + if (candidate.position > previousPosition && lengths[i] === remaining) { + anchors.add(candidate.id) + previousPosition = candidate.position + remaining-- + } + } + const result = order.filter((id) => !positions.has(id) || anchors.has(id)) + let successor: string | undefined + for (const id of requested.toReversed()) { + if (!anchors.has(id)) { + result.splice(successor === undefined ? result.length : result.indexOf(successor), 0, id) + } + successor = id + } + return result +} + export function partitionPinnedTabOrder( tabOrder: string[], tabs: readonly PinnedTab[], From 8a8a8a983edd86a18b03bdaad532689999bb8584 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:42:14 -0700 Subject: [PATCH 27/38] Use recorded launch ownership for surface recovery --- .../tab-bar/cli-chat-resume-feedback.ts | 5 +- .../tab-bar/cli-chat-resume-run.test.ts | 10 +-- ...d-agent-session-launch-outcome-tracking.ts | 14 +--- .../structured-agent-session-launch-record.ts | 4 +- ...structured-agent-session-launch-surface.ts | 69 ++++++++++++++----- 5 files changed, 59 insertions(+), 43 deletions(-) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts index 7ca8e68f565c..adab289eee5c 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-feedback.ts @@ -34,10 +34,7 @@ export async function reportCliChatResumeFailure( return } if (refusal?.code === 'agent_session_identity_required') { - if ( - refusal.details?.reason === 'transcriptNotFound' || - refusal.details?.reason === 'transcriptEmpty' - ) { + if (refusal.details?.reason === 'transcriptNotFound') { toast.error( translate( 'components.native-chat.resumeInNewChat.notSavedYet', diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index c9ec3938889a..c7bbc6b2edcc 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -90,9 +90,7 @@ function deferred() { }) return { promise, resolve } } -function refuse( - reason: 'transcriptNotFound' | 'transcriptEmpty' | 'transcriptUnreadable' -): AgentSessionWireRefusal { +function refuse(reason: 'transcriptNotFound' | 'transcriptUnreadable'): AgentSessionWireRefusal { return { code: 'agent_session_identity_required', message: 'private host error', @@ -205,11 +203,7 @@ describe('CLI identity resume through the existing launch owner', () => { }) it('keeps ordinary refusals hidden and distinguishes unsaved from unreadable content', async () => { - for (const reason of [ - 'transcriptNotFound', - 'transcriptEmpty', - 'transcriptUnreadable' - ] as const) { + for (const reason of ['transcriptNotFound', 'transcriptUnreadable'] as const) { mocks.call.mockResolvedValue({ ok: false, refusal: refuse(reason) }) await runCliChatResume(SOURCE) expect(tabs()).toEqual([]) diff --git a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts index 548b1c4c93b3..41ed00c1f3b7 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts @@ -1,9 +1,8 @@ import { materializeStructuredLaunchSurface, - removeStructuredLaunchSlot + removeStructuredLaunchSlot, + findStructuredLaunchTab } from './structured-agent-session-launch-surface' -import { findStructuredAgentSessionTab } from './structured-agent-session-tab-activation' -import { useAppStore } from '@/store' import { StructuredAgentSessionCreateRefusalError } from '@/lib/launch-structured-agent-session' import { settleStructuredLaunchCallers, @@ -38,14 +37,7 @@ export function maybeCleanupLaunchState(state: StructuredLaunchState): void { } function cleanupUnmaterializedLaunch(state: StructuredLaunchState): void { - if ( - state.intent.surfaceAddress && - !findStructuredAgentSessionTab(useAppStore.getState().unifiedTabsByWorktree, { - workspaceId: state.intent.worktreeId, - sessionId: state.intent.sessionId, - target: state.intent.target - }) - ) { + if (state.intent.surfaceAddress && !findStructuredLaunchTab(state.intent)) { removeStructuredLaunchSlot(state.intent.worktreeId, state.intent.sessionId) cleanupLaunchState(state) } diff --git a/src/renderer/src/lib/structured-agent-session-launch-record.ts b/src/renderer/src/lib/structured-agent-session-launch-record.ts index b9af8c6fa41c..caa352ba5b26 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-record.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-record.ts @@ -36,7 +36,9 @@ export function parseStructuredLaunchSurfaceAddress( return { worktreeId: value.worktreeId, precedingTabIds: value.precedingTabIds, - ...('targetGroupId' in value ? { targetGroupId: value.targetGroupId } : {}) + ...('targetGroupId' in value && typeof value.targetGroupId === 'string' + ? { targetGroupId: value.targetGroupId } + : {}) } } diff --git a/src/renderer/src/lib/structured-agent-session-launch-surface.ts b/src/renderer/src/lib/structured-agent-session-launch-surface.ts index fd1f09cb9480..1b086678394c 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-surface.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-surface.ts @@ -1,4 +1,9 @@ -import { getExecutionHostIdForWorktree } from './worktree-runtime-owner' +import { + findIndexedProjectGroupOwner, + findIndexedRepoOwner, + findIndexedWorktreeOwner, + getCatalogOwnerHostId +} from './worktree-runtime-owner-index' import { folderWorkspaceToWorktree } from '../../../shared/folder-workspace-worktree' import type { Tab } from '../../../shared/tab-types' import type { ExecutionHostId } from '../../../shared/execution-host' @@ -9,18 +14,17 @@ import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-order import { useAppStore } from '@/store' import { ensureGroup } from '@/store/slices/tab-group-state' import { resolveUnifiedTabCreatePlacement } from '@/store/slices/tabs/tabs-create-placement' -import { findStructuredAgentSessionTab } from './structured-agent-session-tab-activation' import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' import { readStructuredAgentLaunchRecord, readStructuredAgentLaunchRecords, writeStructuredAgentLaunchRecord } from './structured-agent-session-launch-persistence' -import { getStructuredLaunchStateBySessionId } from './structured-agent-session-launch-registry' import { - structuredAgentSessionFocusOwner, - structuredAgentSessionTargetForHost -} from '@/runtime/structured-agent-session-owner' + getStructuredAgentSessionLaunchOwner, + getStructuredLaunchStateBySessionId +} from './structured-agent-session-launch-registry' +import { structuredAgentSessionFocusOwner } from '@/runtime/structured-agent-session-owner' import { clearWebSessionFocusIntentIfMatches, peekWebSessionFocusIntent, @@ -34,6 +38,24 @@ type LaunchSurface = { surfaceAddress?: StructuredLaunchSurfaceAddress } +export function findStructuredLaunchTab(args: { + worktreeId: string + sessionId: string + executionHostId: ExecutionHostId +}): Tab | null { + const owner = getStructuredAgentSessionLaunchOwner(args.sessionId) + const tabs = useAppStore.getState().unifiedTabsByWorktree[args.worktreeId] + return ( + tabs?.find( + (tab) => + tab.worktreeId === args.worktreeId && + tab.contentType === 'agent-session' && + tab.entityId === args.sessionId && + (tab.executionHostId ?? owner) === args.executionHostId + ) ?? null + ) +} + export function captureStructuredLaunchSurfaceAddress( worktreeId: string, targetGroupId?: string @@ -188,12 +210,7 @@ export function openStructuredAgentSessionProvisionalTab(args: { activate?: boolean }): Tab { const state = useAppStore.getState() - const target = structuredAgentSessionTargetForHost(args.executionHostId) - const existing = findStructuredAgentSessionTab(state.unifiedTabsByWorktree, { - workspaceId: args.worktreeId, - sessionId: args.sessionId, - ...(target ? { target } : {}) - }) + const existing = findStructuredLaunchTab(args) if (existing) { if (args.activate !== false) { state.focusGroup(args.worktreeId, existing.groupId) @@ -252,20 +269,34 @@ export function materializeStructuredLaunchSurface(launch: LaunchSurface, activa export function restoreStructuredLaunchSurfaces(): void { const state = useAppStore.getState() - const validWorkspaces = new Set([ - ...state.allWorktrees().map((worktree) => worktree.id), - ...state.folderWorkspaces.map((workspace) => folderWorkspaceToWorktree(workspace).id) - ]) + const catalog = { + workspaces: [ + ...state.allWorktrees(), + ...state.folderWorkspaces.flatMap((workspace) => { + const group = findIndexedProjectGroupOwner(state.projectGroups, workspace.projectGroupId) + const host = workspace.executionHostId || workspace.connectionId ? workspace : group + const owned = host && { ...workspace, executionHostId: getCatalogOwnerHostId(host) } + return owned ? [folderWorkspaceToWorktree(owned)] : [] + }) + ] + } for (const record of readStructuredAgentLaunchRecords()) { if ( record.executionHostId !== 'local' || record.lifecycle !== 'visibility-unknown' || - !record.surfaceAddress || - !validWorkspaces.has(record.surfaceAddress.worktreeId) || - getExecutionHostIdForWorktree(state, record.surfaceAddress.worktreeId) !== 'local' + !record.surfaceAddress ) { continue } + const workspace = findIndexedWorktreeOwner(catalog, record.surfaceAddress.worktreeId) + if (!workspace || workspace.runtimeOwnerEnvironmentId?.trim()) { + continue + } + const repo = findIndexedRepoOwner(state.repos, workspace.repoId) + const host = workspace.hostId ?? (repo ? getCatalogOwnerHostId(repo) : undefined) + if (host !== getStructuredAgentSessionLaunchOwner(record.sessionId)) { + continue + } reserveStructuredLaunchSlot(record) materializeStructuredLaunchSurface(record, false) } From 02ebb2ee3ae03102f304befc4bfea8522b14d4b7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:04:44 -0700 Subject: [PATCH 28/38] Reserve deferred chat order through existing group actions --- .../tab-bar/cli-chat-resume-run.test.ts | 15 ++++ ...structured-agent-session-launch-surface.ts | 67 ++-------------- .../store/slices/tabs/tabs-group-actions.ts | 80 +++++++++++++++---- .../store/slices/tabs/tabs-slice-contract.ts | 9 ++- 4 files changed, 93 insertions(+), 78 deletions(-) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index c7bbc6b2edcc..ad4d329daf18 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -387,7 +387,22 @@ describe('CLI identity resume through the existing launch owner', () => { surfaceAddress: { worktreeId: 'wt-1', precedingTabIds: [] } } writeStructuredAgentLaunchRecord(record) + const firstGroup = vi.fn() + const unsubscribe = useAppStore.subscribe((state) => { + const group = state.groupsByWorktree['wt-1']?.[0] + if (group) { + firstGroup(group) + } + }) reserveStructuredLaunchSlot(record) + unsubscribe() + expect(firstGroup).toHaveBeenCalledTimes(1) + expect(firstGroup.mock.calls[0][0]).toMatchObject({ + tabOrder: ['structured-agent-session-reload-pending'], + activeTabId: null + }) + expect(firstGroup.mock.calls[0][0].recentTabIds ?? []).toEqual([]) + expect(tabs()).toHaveLength(0) const session = buildWorkspaceSessionPayload(useAppStore.getState()) stopStructuredLaunchSlotTracking() resetStructuredAgentLaunchPersistenceForTests() diff --git a/src/renderer/src/lib/structured-agent-session-launch-surface.ts b/src/renderer/src/lib/structured-agent-session-launch-surface.ts index 1b086678394c..797854b5ade1 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-surface.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-surface.ts @@ -10,9 +10,7 @@ import type { ExecutionHostId } from '../../../shared/execution-host' import type { TuiAgent } from '../../../shared/tui-agent' import { defaultAgentChatLabel } from '../../../shared/agent-session-chat-label' import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' -import { insertTabIdIntoOrder } from '../../../shared/workspace-layout/tab-order' import { useAppStore } from '@/store' -import { ensureGroup } from '@/store/slices/tab-group-state' import { resolveUnifiedTabCreatePlacement } from '@/store/slices/tabs/tabs-create-placement' import type { StructuredLaunchSurfaceAddress } from './structured-agent-session-launch-record' import { @@ -129,54 +127,11 @@ export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { if (!address || launch.executionHostId !== 'local') { return } - const state = useAppStore.getState() - const tabId = structuredAgentSessionTabId(launch.sessionId) - const groups = state.groupsByWorktree[address.worktreeId] ?? [] - if (groups.some((group) => group.tabOrder.includes(tabId))) { - return - } - const { group, groupsByWorktree, activeGroupIdByWorktree } = ensureGroup( - state.groupsByWorktree, - state.activeGroupIdByWorktree, - address.worktreeId, - groups.some((entry) => entry.id === address.targetGroupId) - ? address.targetGroupId - : state.activeGroupIdByWorktree[address.worktreeId] - ) - // Only reload reconstructs a missing slot; live sibling mutations use canonical order. - const preceding = new Set(address.precedingTabIds) - const anchor = group.tabOrder.findLast((id) => preceding.has(id)) - const order = insertTabIdIntoOrder( - group.tabOrder, - state.unifiedTabsByWorktree[address.worktreeId] ?? [], - tabId, - false, - anchor - ) - if (!anchor && address.precedingTabIds.length === 0) { - order.splice(order.indexOf(tabId), 1) - const firstUnpinned = order.findIndex( - (id) => - !state.unifiedTabsByWorktree[address.worktreeId]?.find((tab) => tab.id === id)?.isPinned - ) - order.splice(firstUnpinned === -1 ? order.length : firstUnpinned, 0, tabId) - } trackSlotAddresses() - useAppStore.setState({ - groupsByWorktree: { - ...groupsByWorktree, - [address.worktreeId]: groupsByWorktree[address.worktreeId].map((entry) => - entry.id === group.id ? { ...entry, tabOrder: order } : entry - ) - }, - activeGroupIdByWorktree, - layoutByWorktree: { - ...state.layoutByWorktree, - [address.worktreeId]: state.layoutByWorktree[address.worktreeId] ?? { - type: 'leaf', - groupId: group.id - } - } + useAppStore.getState().ensureWorktreeRootGroup(address.worktreeId, { + tabId: structuredAgentSessionTabId(launch.sessionId), + targetGroupId: address.targetGroupId, + precedingTabIds: address.precedingTabIds }) } @@ -187,18 +142,10 @@ export function removeStructuredLaunchSlot(worktreeId: string, sessionId: string return } const groups = state.groupsByWorktree[worktreeId] ?? [] - if (!groups.some((group) => group.tabOrder.includes(tabId))) { - return + for (const group of groups.filter((entry) => entry.tabOrder.includes(tabId))) { + const order = group.tabOrder.filter((id) => id !== tabId) + state.reorderUnifiedTabs(group.id, order, { recordInteraction: false }) } - useAppStore.setState({ - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: groups.map((group) => ({ - ...group, - tabOrder: group.tabOrder.filter((id) => id !== tabId) - })) - } - }) } export function openStructuredAgentSessionProvisionalTab(args: { diff --git a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts index 50bdafaf0090..79fec1ec0366 100644 --- a/src/renderer/src/store/slices/tabs/tabs-group-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-group-actions.ts @@ -8,6 +8,8 @@ import { replaceLeaf } from '../../../../../shared/workspace-layout/tab-group-layout-tree' import { workspaceRootGroupId } from '../../../../../shared/workspace-layout/workspace-layout-minted-ids' +import { insertTabIdIntoOrder } from '../../../../../shared/workspace-layout/tab-order' +import { resolveUnifiedTabCreatePlacement } from './tabs-create-placement' import { ownsGlobalSelection } from '../../global-selection-owner' type SplitGroupState = Pick< @@ -59,28 +61,72 @@ export function createTabsGroupActions( 'ensureWorktreeRootGroup' | 'focusGroup' | 'closeEmptyGroup' | 'createEmptySplitGroup' > { return { - ensureWorktreeRootGroup: (worktreeId) => { + ensureWorktreeRootGroup: (worktreeId, orderSlot) => { const existingGroups = get().groupsByWorktree[worktreeId] ?? [] - if (existingGroups.length > 0) { + if (!orderSlot && existingGroups.length > 0) { return get().activeGroupIdByWorktree[worktreeId] ?? existingGroups[0].id } - const groupId = workspaceRootGroupId(worktreeId) - set((state) => ({ - // Why: a zero-tab worktree still needs a canonical root group so new tabs and splits land in a deterministic place. - groupsByWorktree: { - ...state.groupsByWorktree, - [worktreeId]: [{ id: groupId, worktreeId, activeTabId: null, tabOrder: [] }] - }, - layoutByWorktree: { - ...state.layoutByWorktree, - [worktreeId]: { type: 'leaf', groupId } - }, - activeGroupIdByWorktree: { - ...state.activeGroupIdByWorktree, - [worktreeId]: groupId + let groupId = workspaceRootGroupId(worktreeId) + set((state) => { + const groups = state.groupsByWorktree[worktreeId] ?? [] + const reserved = + orderSlot && groups.find((group) => group.tabOrder.includes(orderSlot.tabId)) + if (reserved) { + groupId = reserved.id + return state + } + const tabs = state.unifiedTabsByWorktree[worktreeId] ?? [] + const placement = resolveUnifiedTabCreatePlacement({ + groups, + tabs, + activeGroupId: state.activeGroupIdByWorktree[worktreeId], + targetGroupId: orderSlot?.targetGroupId, + lookupWorktrees: () => [] + }) + const group = + groups.find((entry) => entry.id === placement.groupId) ?? + groups[0] ?? + emptySplitGroup(worktreeId, groupId) + groupId = group.id + let tabOrder = group.tabOrder + if (orderSlot) { + const { tabId, precedingTabIds } = orderSlot + const preceding = new Set(precedingTabIds) + const anchor = tabOrder.findLast((id) => preceding.has(id)) + tabOrder = insertTabIdIntoOrder(tabOrder, tabs, tabId, false, anchor) + if (!anchor && precedingTabIds.length === 0) { + tabOrder.splice(tabOrder.indexOf(tabId), 1) + const firstUnpinned = tabOrder.findIndex( + (id) => !tabs.find((tab) => tab.id === id)?.isPinned + ) + tabOrder.splice(firstUnpinned === -1 ? tabOrder.length : firstUnpinned, 0, tabId) + } + } + // A new root and its first order member must become observable together. + const nextGroup = { ...group, tabOrder } + return { + groupsByWorktree: { + ...state.groupsByWorktree, + [worktreeId]: groups.length + ? groups.map((entry) => (entry.id === groupId ? nextGroup : entry)) + : [nextGroup] + }, + layoutByWorktree: { + ...state.layoutByWorktree, + [worktreeId]: (orderSlot && state.layoutByWorktree[worktreeId]) || { + type: 'leaf', + groupId + } + }, + activeGroupIdByWorktree: groups.length + ? state.activeGroupIdByWorktree + : { + ...state.activeGroupIdByWorktree, + [worktreeId]: groupId + } } - })) + }) return groupId }, diff --git a/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts b/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts index da53d6354e0d..d8076ec24565 100644 --- a/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts +++ b/src/renderer/src/store/slices/tabs/tabs-slice-contract.ts @@ -126,7 +126,14 @@ export type TabsSlice = { closeOtherTabs: (tabId: string) => string[] closeTabsToRight: (tabId: string) => string[] closeTabsToLeft: (tabId: string) => string[] - ensureWorktreeRootGroup: (worktreeId: string) => string + ensureWorktreeRootGroup: ( + worktreeId: string, + orderSlot?: { + tabId: string + targetGroupId?: string + precedingTabIds: readonly string[] + } + ) => string focusGroup: (worktreeId: string, groupId: string) => void closeEmptyGroup: (worktreeId: string, groupId: string) => boolean createEmptySplitGroup: ( From a6c15818825f85ea6a39aadc34909a16387b7661 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:18:12 -0700 Subject: [PATCH 29/38] Pass the active layout owner into launch cancellation --- ...n-status-bridge-unconfirmed-start.test.tsx | 7 +++++- .../tab-bar/cli-chat-resume-run.test.ts | 5 +++- ...-agent-session-launch-cancellation.test.ts | 13 ++++++++--- ...tured-agent-session-launch-cancellation.ts | 23 +++++++++++++++++++ ...d-agent-session-launch-outcome-tracking.ts | 9 ++++++-- ...tructured-agent-session-launch-registry.ts | 18 ++++++++------- ...structured-agent-session-launch-surface.ts | 13 ----------- .../lib/structured-agent-session-launch.ts | 8 ++++++- ...host-structured-launch-bookkeeping.test.ts | 11 +++++++-- ...tured-agent-session-tab-retirement.test.ts | 21 ++++++++++++++--- ...structured-agent-session-tab-retirement.ts | 5 +++- .../tabs/structured-chat-close-owner.test.ts | 4 +++- .../store/slices/tabs/tabs-close-actions.ts | 3 ++- 13 files changed, 103 insertions(+), 37 deletions(-) diff --git a/src/renderer/src/components/native-chat/structured-agent-session-status-bridge-unconfirmed-start.test.tsx b/src/renderer/src/components/native-chat/structured-agent-session-status-bridge-unconfirmed-start.test.tsx index 06d1dcd6b76f..ef0bc1215cf9 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-status-bridge-unconfirmed-start.test.tsx +++ b/src/renderer/src/components/native-chat/structured-agent-session-status-bridge-unconfirmed-start.test.tsx @@ -340,7 +340,12 @@ describe('a chat whose start was never confirmed', () => { await loseStart(CLAUDE_SESSION, 'claude') await loseStart(CODEX_SESSION, 'codex') act(() => { - markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, CLAUDE_SESSION, 'local') + markStructuredAgentSessionLaunchCancelled( + WORKTREE_ID, + CLAUDE_SESSION, + 'local', + store().getState() + ) }) const creates = createCalls() diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index ad4d329daf18..13952dfa7d3d 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -19,7 +19,10 @@ vi.mock('./cli-chat-resume-source', () => ({ resolveCliChatResumeSource: () => m vi.mock('@/runtime/structured-agent-session-client', () => ({ supportsStructuredAgentSessionCliSource: mocks.sourceCapability, supportsStructuredAgentSessionCreateMessage: mocks.createCapability, - callStructuredAgentSession: mocks.call + callStructuredAgentSession: (...args: unknown[]) => + args[1] === 'agentSession.createSupport' + ? Promise.resolve({ supported: true }) + : mocks.call(...args) })) vi.mock('@/runtime/structured-session-tab-inventory', () => ({ readStructuredSessionTabInventory: async () => { diff --git a/src/renderer/src/lib/structured-agent-session-launch-cancellation.test.ts b/src/renderer/src/lib/structured-agent-session-launch-cancellation.test.ts index 3b1a190ab0c7..425791f156b8 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-cancellation.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-cancellation.test.ts @@ -1,6 +1,7 @@ // @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { StructuredLaunchSlotOwner } from '@/lib/structured-agent-session-launch-cancellation' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import { suppressCancelledStructuredSessionTabs } from '@/runtime/structured-agent-session-tab-retirement' import type { StructuredLaunchState } from './structured-agent-session-launch-registry' @@ -15,6 +16,12 @@ import { beginStructuredAgentSessionAuthoritativeInventory } from './structured- import { resetStructuredAgentLaunchPersistenceForTests } from './structured-agent-session-launch-persistence' import { refreshLocalStructuredSessionTabs } from '@/runtime/local-structured-session-tabs-sync/inventory-refresh' +const layoutOwner: StructuredLaunchSlotOwner = { + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + reorderUnifiedTabs: vi.fn() +} + const WORKTREE_ID = 'repo-1::worktree-1' const SESSION_ID = 'session-close-race' @@ -101,7 +108,7 @@ describe('structured launch cancellation retirement', () => { 'local' ) ).toBe(false) - markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local', layoutOwner) const afterCancel = beginStructuredAgentSessionAuthoritativeInventory() expect( retireAbsentStructuredAgentSessionLaunchCancellationTombstones( @@ -172,7 +179,7 @@ describe('structured launch cancellation retirement', () => { cancelled: false, selection: { held: {} } } satisfies StructuredLaunchState) - markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local', layoutOwner) await new Promise((resolve) => setTimeout(resolve, 0)) const frame = (unverifiable: boolean): RuntimeMobileSessionTabsResult => ({ ...latePublication(), @@ -196,7 +203,7 @@ describe('structured launch cancellation retirement', () => { }) it('drains a restored cancellation before a newer inventory retires it', async () => { - markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE_ID, SESSION_ID, 'local', layoutOwner) resetStructuredAgentLaunchRegistryForTests() resetStructuredAgentLaunchPersistenceForTests() diff --git a/src/renderer/src/lib/structured-agent-session-launch-cancellation.ts b/src/renderer/src/lib/structured-agent-session-launch-cancellation.ts index c56e1af69b8c..885ce8bea787 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-cancellation.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-cancellation.ts @@ -1,3 +1,5 @@ +import type { TabsSlice } from '@/store/slices/tabs/tabs-slice-contract' +import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' import type { ExecutionHostId } from '../../../shared/execution-host' import { hasStructuredAgentLaunchCancellationTombstonePersisted, @@ -7,6 +9,27 @@ import { retireStructuredAgentLaunchCancellationTombstonePersisted } from './structured-agent-session-launch-persistence' +export type StructuredLaunchSlotOwner = Pick< + TabsSlice, + 'unifiedTabsByWorktree' | 'groupsByWorktree' | 'reorderUnifiedTabs' +> + +export function removeStructuredLaunchSlot( + owner: StructuredLaunchSlotOwner, + worktreeId: string, + sessionId: string +): void { + const tabId = structuredAgentSessionTabId(sessionId) + if (owner.unifiedTabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)) { + return + } + const groups = owner.groupsByWorktree[worktreeId] ?? [] + for (const group of groups.filter((entry) => entry.tabOrder.includes(tabId))) { + const order = group.tabOrder.filter((id) => id !== tabId) + owner.reorderUnifiedTabs(group.id, order, { recordInteraction: false }) + } +} + type CancellationRetirement = { retireAfterInventory: number | null cleanupStarted: boolean diff --git a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts index 41ed00c1f3b7..e31475e33785 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-outcome-tracking.ts @@ -1,6 +1,7 @@ +import { useAppStore } from '@/store' +import { removeStructuredLaunchSlot } from './structured-agent-session-launch-cancellation' import { materializeStructuredLaunchSurface, - removeStructuredLaunchSlot, findStructuredLaunchTab } from './structured-agent-session-launch-surface' import { StructuredAgentSessionCreateRefusalError } from '@/lib/launch-structured-agent-session' @@ -38,7 +39,11 @@ export function maybeCleanupLaunchState(state: StructuredLaunchState): void { function cleanupUnmaterializedLaunch(state: StructuredLaunchState): void { if (state.intent.surfaceAddress && !findStructuredLaunchTab(state.intent)) { - removeStructuredLaunchSlot(state.intent.worktreeId, state.intent.sessionId) + removeStructuredLaunchSlot( + useAppStore.getState(), + state.intent.worktreeId, + state.intent.sessionId + ) cleanupLaunchState(state) } } diff --git a/src/renderer/src/lib/structured-agent-session-launch-registry.ts b/src/renderer/src/lib/structured-agent-session-launch-registry.ts index ae6788f26f7c..80adff6f8947 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-registry.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-registry.ts @@ -1,4 +1,3 @@ -import { removeStructuredLaunchSlot } from './structured-agent-session-launch-surface' import { useSyncExternalStore } from 'react' import type { TuiAgent } from '../../../shared/tui-agent' import type { StructuredLaunchFailure } from './structured-agent-session-launch-failure' @@ -20,6 +19,8 @@ import { } from './structured-agent-session-launch-persistence' import { markStructuredAgentLaunchCancellation, + removeStructuredLaunchSlot, + type StructuredLaunchSlotOwner, resetStructuredAgentLaunchCancellationForTests, retireAbsentStructuredAgentLaunchCancellations, retireStructuredAgentLaunchCancellation @@ -222,7 +223,7 @@ function markStructuredAgentSessionLaunchCancelledInternal( worktreeId: string, sessionId: string, executionHostId: ExecutionHostId, - notify: boolean + owner: StructuredLaunchSlotOwner | undefined ): boolean { const alreadyCancelled = hasStructuredAgentLaunchCancellationTombstonePersisted(sessionId) const state = getStructuredLaunchStateBySessionId(sessionId) @@ -245,10 +246,10 @@ function markStructuredAgentSessionLaunchCancelledInternal( } else if (!alreadyCancelled) { markStructuredAgentLaunchCancellation(sessionId, executionHostId, alreadyCancelled) } - if (notify && surfaceAddress) { - removeStructuredLaunchSlot(worktreeId, sessionId) + if (owner && surfaceAddress) { + removeStructuredLaunchSlot(owner, worktreeId, sessionId) } - if (!alreadyCancelled && notify) { + if (!alreadyCancelled && owner) { notifyStructuredLaunchListeners() } return !alreadyCancelled @@ -258,13 +259,14 @@ function markStructuredAgentSessionLaunchCancelledInternal( export function markStructuredAgentSessionLaunchCancelled( worktreeId: string, sessionId: string, - executionHostId: ExecutionHostId + executionHostId: ExecutionHostId, + owner: StructuredLaunchSlotOwner ): boolean { return markStructuredAgentSessionLaunchCancelledInternal( worktreeId, sessionId, executionHostId, - true + owner ) } @@ -278,7 +280,7 @@ export function markStructuredAgentSessionLaunchCancelledSilently( worktreeId, sessionId, executionHostId, - false + undefined ) } diff --git a/src/renderer/src/lib/structured-agent-session-launch-surface.ts b/src/renderer/src/lib/structured-agent-session-launch-surface.ts index 797854b5ade1..338e8216ab75 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-surface.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-surface.ts @@ -135,19 +135,6 @@ export function reserveStructuredLaunchSlot(launch: LaunchSurface): void { }) } -export function removeStructuredLaunchSlot(worktreeId: string, sessionId: string): void { - const state = useAppStore.getState() - const tabId = structuredAgentSessionTabId(sessionId) - if (state.unifiedTabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)) { - return - } - const groups = state.groupsByWorktree[worktreeId] ?? [] - for (const group of groups.filter((entry) => entry.tabOrder.includes(tabId))) { - const order = group.tabOrder.filter((id) => id !== tabId) - state.reorderUnifiedTabs(group.id, order, { recordInteraction: false }) - } -} - export function openStructuredAgentSessionProvisionalTab(args: { worktreeId: string executionHostId: ExecutionHostId diff --git a/src/renderer/src/lib/structured-agent-session-launch.ts b/src/renderer/src/lib/structured-agent-session-launch.ts index b0ccbf2316c8..f0fb8136a4d1 100644 --- a/src/renderer/src/lib/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/structured-agent-session-launch.ts @@ -1,3 +1,4 @@ +import { useAppStore } from '@/store' import { reserveStructuredLaunchSlot } from './structured-agent-session-launch-surface' import type { TuiAgent } from '../../../shared/tui-agent' import type { ExecutionHostId } from '../../../shared/execution-host' @@ -260,7 +261,12 @@ export function cancelStructuredAgentLaunch(worktreeId: string, sessionId: strin if (!state) { return false } - markStructuredAgentSessionLaunchCancelled(worktreeId, sessionId, state.intent.executionHostId) + markStructuredAgentSessionLaunchCancelled( + worktreeId, + sessionId, + state.intent.executionHostId, + useAppStore.getState() + ) discardStructuredAgentSessionChatSends(state.intent.sessionId) launchDraft.clearStructuredAgentLaunchDraft(state.intent.sessionId) abandonStructuredAgentSessionLaunchIntent(state.intent) diff --git a/src/renderer/src/runtime/paired-host-structured-launch-bookkeeping.test.ts b/src/renderer/src/runtime/paired-host-structured-launch-bookkeeping.test.ts index 6ea3a3507021..8ac34de41356 100644 --- a/src/renderer/src/runtime/paired-host-structured-launch-bookkeeping.test.ts +++ b/src/renderer/src/runtime/paired-host-structured-launch-bookkeeping.test.ts @@ -1,6 +1,7 @@ // @vitest-environment happy-dom import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { StructuredLaunchSlotOwner } from '@/lib/structured-agent-session-launch-cancellation' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' @@ -44,6 +45,12 @@ import { } from '@/lib/structured-agent-session-launch-persistence' import { acceptPairedHostStructuredSessions } from './structured-agent-session-tab-retirement' +const layoutOwner: StructuredLaunchSlotOwner = { + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + reorderUnifiedTabs: vi.fn() +} + const SERVER: RuntimeClientTarget = { kind: 'environment', environmentId: 'server-1' } const SERVER_HOST = 'runtime:server-1' const WORKTREE = 'wt-remote' @@ -86,7 +93,7 @@ beforeEach(() => { describe('a chat closed before its create landed on a paired server', () => { it("survives this machine's inventory, so the server's late frame is still suppressed", () => { - markStructuredAgentSessionLaunchCancelled(WORKTREE, 'remote-chat', SERVER_HOST) + markStructuredAgentSessionLaunchCancelled(WORKTREE, 'remote-chat', SERVER_HOST, layoutOwner) // A local chat launch or resubscribe: an authoritative census of this machine only. retireAbsentStructuredAgentSessionLaunchCancellationTombstones( new Set(['some-local-chat']), @@ -102,7 +109,7 @@ describe('a chat closed before its create landed on a paired server', () => { // A tombstone guards a random session id, so it is inert once stale; its 30-day TTL ends it. it('after a reload is closed on the server when the chat appears, never on this machine', () => { - markStructuredAgentSessionLaunchCancelled(WORKTREE, 'remote-chat', SERVER_HOST) + markStructuredAgentSessionLaunchCancelled(WORKTREE, 'remote-chat', SERVER_HOST, layoutOwner) reload() const localCleanup = vi.fn(async () => 'closed') diff --git a/src/renderer/src/runtime/structured-agent-session-tab-retirement.test.ts b/src/renderer/src/runtime/structured-agent-session-tab-retirement.test.ts index 3882bc504c71..f98497c02cb1 100644 --- a/src/renderer/src/runtime/structured-agent-session-tab-retirement.test.ts +++ b/src/renderer/src/runtime/structured-agent-session-tab-retirement.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' +import type { markStructuredAgentSessionLaunchCancelled } from '@/lib/structured-agent-session-launch-registry' +import type { StructuredLaunchSlotOwner } from '@/lib/structured-agent-session-launch-cancellation' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' const mocks = vi.hoisted(() => ({ @@ -10,8 +12,7 @@ const mocks = vi.hoisted(() => ({ discardOutbox: vi.fn<(sessionId: string) => void>(), stopSends: vi.fn<(sessionId: string) => void>(), hasTombstone: vi.fn<(worktreeId: string, sessionId: string) => boolean>(), - markCancelled: - vi.fn<(worktreeId: string, sessionId: string, executionHostId: string) => boolean>(), + markCancelled: vi.fn(), reacceptLocal: vi.fn<(worktreeId: string, options?: { reacceptCurrentVersion?: boolean }) => Promise>(), refreshPaired: @@ -74,6 +75,12 @@ import { LOCAL_STRUCTURED_SESSION_OWNER } from './local-structured-session-owner import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import { replaceRuntimeEnvironmentRevisions } from './runtime-environment-revision' +const layoutOwner: StructuredLaunchSlotOwner = { + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + reorderUnifiedTabs: vi.fn() +} + const target: RuntimeClientTarget = { kind: 'local' } function snapshot(): RuntimeMobileSessionTabsResult { @@ -127,12 +134,13 @@ const closing = (owner: string): boolean => describe('structured agent session tab retirement', () => { it('marks cancellation and clears local launch state before host cleanup', async () => { beginStructuredAgentSessionTabClose({ + layoutOwner, target, worktreeId: 'wt-1', sessionId: 'session-1', provisional: true }) - expect(mocks.markCancelled).toHaveBeenCalledWith('wt-1', 'session-1', 'local') + expect(mocks.markCancelled).toHaveBeenCalledWith('wt-1', 'session-1', 'local', layoutOwner) expect(mocks.discardOutbox).toHaveBeenCalledWith('session-1') expect(mocks.stopSends).not.toHaveBeenCalled() await vi.waitFor(() => expect(mocks.callRuntime).toHaveBeenCalled()) @@ -142,6 +150,7 @@ describe('structured agent session tab retirement', () => { // Withdrawn, as a Stop does: nothing more goes out, and nothing is dropped. it("never drops a published chat's sends when its tab closes", async () => { beginStructuredAgentSessionTabClose({ + layoutOwner, target, worktreeId: 'wt-1', sessionId: 'session-1', @@ -175,6 +184,7 @@ describe('structured agent session tab retirement', () => { }) ) beginStructuredAgentSessionTabClose({ + layoutOwner, target, worktreeId: 'wt-1', sessionId: 'session-1', @@ -208,6 +218,7 @@ describe('structured agent session tab retirement', () => { mocks.callRuntime.mockRejectedValue(new Error('window relay failed')) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) beginStructuredAgentSessionTabClose({ + layoutOwner, target, worktreeId: FLOATING_TERMINAL_WORKTREE_ID, sessionId: 'session-1', @@ -231,6 +242,7 @@ describe('structured agent session tab retirement', () => { mocks.callRuntime.mockRejectedValue(new Error('window relay failed')) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) beginStructuredAgentSessionTabClose({ + layoutOwner, target, worktreeId: 'wt-1', sessionId: 'session-1', @@ -255,6 +267,7 @@ describe('structured agent session tab retirement', () => { ) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) beginStructuredAgentSessionTabClose({ + layoutOwner, target: paired, worktreeId: 'wt-1', sessionId: 'session-1', @@ -279,6 +292,7 @@ describe('structured agent session tab retirement', () => { it('re-reads a paired server after a successful close, since its frames travel apart from its answer', async () => { const paired = { kind: 'environment', environmentId: 'server-1' } as const beginStructuredAgentSessionTabClose({ + layoutOwner, target: paired, worktreeId: 'wt-1', sessionId: 'session-1', @@ -307,6 +321,7 @@ describe('structured agent session tab retirement', () => { ) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) beginStructuredAgentSessionTabClose({ + layoutOwner, target: paired, worktreeId: 'wt-1', sessionId: 'session-1', diff --git a/src/renderer/src/runtime/structured-agent-session-tab-retirement.ts b/src/renderer/src/runtime/structured-agent-session-tab-retirement.ts index 23b7b4cae65c..3a98d712aa6d 100644 --- a/src/renderer/src/runtime/structured-agent-session-tab-retirement.ts +++ b/src/renderer/src/runtime/structured-agent-session-tab-retirement.ts @@ -1,3 +1,4 @@ +import type { StructuredLaunchSlotOwner } from '@/lib/structured-agent-session-launch-cancellation' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import { markStructuredAgentSessionLaunchesPublished, @@ -111,13 +112,15 @@ export function beginStructuredAgentSessionTabClose(args: { worktreeId: string sessionId: string provisional: boolean + layoutOwner: StructuredLaunchSlotOwner onError?: (error: unknown) => void }): void { if (args.provisional) { markStructuredAgentSessionLaunchCancelled( args.worktreeId, args.sessionId, - executionHostIdForStructuredTarget(args.target) + executionHostIdForStructuredTarget(args.target), + args.layoutOwner ) discardStructuredAgentSessionChatSends(args.sessionId) } else { diff --git a/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts b/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts index 0c9e658cac14..6c5045f473a7 100644 --- a/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts +++ b/src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts @@ -64,12 +64,14 @@ describe('closing a structured chat from outside its workspace', () => { it('stops it on the host stamped on its tab, not on whichever host shares its id', () => { const store = storeWith(chatTab('runtime:server-1')) + const layoutOwner = store.getState() store.getState().closeUnifiedTab('agent-session:chat-1') expect(mocks.beginClose).toHaveBeenCalledWith( expect.objectContaining({ target: { kind: 'environment', environmentId: 'server-1' }, - sessionId: 'chat-1' + sessionId: 'chat-1', + layoutOwner }) ) }) diff --git a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts index 2b6a5097a9f2..117e80141567 100644 --- a/src/renderer/src/store/slices/tabs/tabs-close-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-close-actions.ts @@ -70,7 +70,8 @@ export function createTabsCloseActions( target, worktreeId, sessionId: tab.entityId, - provisional + provisional, + layoutOwner: state }) } else { // Closing still removes the tab; no host can be named to stop its chat on. From 9ce2f30364fd726e910abd212daedd390e99e3f2 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:21:59 -0700 Subject: [PATCH 30/38] fix(native-chat): admit an unsaved transcript under a linked account folder A missing transcript stayed unresolved while its account root resolved through symlinks, so containment failed and a not-yet-saved conversation showed a load error instead of the unsaved notice. --- ...red-agent-session-source-admission.test.ts | 12 +++++ .../native-chat/transcript-path-admission.ts | 47 +++++++++++++++++-- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index 6402cbc4b03a..fdf25427bcbb 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -98,6 +98,18 @@ it('creates from the host hook path when Claude filename differs, then checks ac expect(find).not.toHaveBeenCalled() }) +it.skipIf(process.platform === 'win32')('reports a not-yet-saved conversation under a linked account folder as unsaved', async () => { + const linked = join(root, 'linked-account') + await mkdir(join(root, 'projects'), { recursive: true }) + await symlink(root, linked) + await expect(resolveStructuredAgentSessionAdoptionForCreate({ + settings: {}, agent: 'claude', transcriptImport: CLAUDE_CLI_CONVERSATIONS.transcriptImport!, + providerSessionId: id, selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: linked }, + launchEnv: {}, workspaceCwd: root, + resolveTranscriptPath: () => join(linked, 'projects', 'folder', `${id}.jsonl`) + })).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptNotFound' } } }) +}) + it.each(['claude', 'codex', 'grok', 'omp', 'pi'] as const)('retains empty versus unreadable source facts for %s', async (agent) => { const transcript = join(root, `${id}.jsonl`) await writeFile(transcript, '') diff --git a/src/main/native-chat/transcript-path-admission.ts b/src/main/native-chat/transcript-path-admission.ts index 2e7d2b36bf6f..bbf924abca3a 100644 --- a/src/main/native-chat/transcript-path-admission.ts +++ b/src/main/native-chat/transcript-path-admission.ts @@ -1,5 +1,6 @@ -import { isAbsolute, relative, resolve } from 'node:path' -import { isDescendantOrEqual, normalizeExistingPath } from '../ipc/filesystem-path-containment' +import { lstat, realpath } from 'node:fs/promises' +import { basename, dirname, isAbsolute, relative, resolve } from 'node:path' +import { isDescendantOrEqual, isENOENT } from '../ipc/filesystem-path-containment' import { isWslUncPath } from '../../shared/wsl-paths' import { needsWslHostResolution } from './host-readable-transcript-path' @@ -15,10 +16,46 @@ export async function admitTranscriptPath(root: string, candidate: string) { return null } const [canonicalRoot, canonicalCandidate] = await Promise.all([ - normalizeExistingPath(resolve(root)), - normalizeExistingPath(resolve(candidate)) + canonicalPath(resolve(root)), + canonicalPath(resolve(candidate)) ]) - return isDescendantOrEqual(canonicalCandidate, canonicalRoot) + return canonicalRoot && + canonicalCandidate && + isDescendantOrEqual(canonicalCandidate, canonicalRoot) ? { path: canonicalCandidate, relativePath: relative(canonicalRoot, canonicalCandidate) } : null } + +/** A not-yet-written transcript resolves through its deepest existing ancestor, so a linked + * account folder compares equal before the agent's first save. */ +async function canonicalPath(path: string): Promise { + const missing: string[] = [] + let existing = path + for (;;) { + try { + return resolve(await realpath(existing), ...missing) + } catch (error) { + if (!isENOENT(error)) { + throw error + } + const parent = dirname(existing) + // A dangling link gives no evidence of where a later read would land. + if (parent === existing || (await isDanglingLink(existing))) { + return null + } + missing.unshift(basename(existing)) + existing = parent + } + } +} + +async function isDanglingLink(path: string): Promise { + try { + return (await lstat(path)).isSymbolicLink() + } catch (error) { + if (isENOENT(error)) { + return false + } + throw error + } +} From 9baf0ad92fc2b21566d616edb22dec5f3cd6a768 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:33:10 -0700 Subject: [PATCH 31/38] refactor(native-chat): move the newest-item import window into its own module Keeps journal-legacy-import.ts under the line limit after the source identity observer landed on top of the streaming import. --- .../journal-legacy-import.ts | 29 +------------------ .../journal-newest-item-window.ts | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+), 28 deletions(-) create mode 100644 src/main/native-chat/agent-session-journal/journal-newest-item-window.ts diff --git a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts index f7790c8ab7b5..80ad7ab6bfd1 100644 --- a/src/main/native-chat/agent-session-journal/journal-legacy-import.ts +++ b/src/main/native-chat/agent-session-journal/journal-legacy-import.ts @@ -32,6 +32,7 @@ import { readOpenCodeNativeChatTranscriptFull } from '../transcript-opencode' import { boundSubagentEntryId } from '../subagent-entry-id-bounds' import { createLegacyIdentityTracker } from './journal-legacy-identity' import { createPiTranscriptCollector } from './journal-pi-active-branch' +import { createNewestItemWindow } from './journal-newest-item-window' import type { JournalReplacementItem } from './journal-epoch-replacement' import { boundInlineText, @@ -278,34 +279,6 @@ async function decodeReplacementItems(input: { } } -/** The newest complete items that fit `maxBytes`; the latest item is always kept. */ -function createNewestItemWindow(maxBytes: number): { - push(item: JournalReplacementItem): void - items(): JournalReplacementItem[] -} { - let entries: ({ item: JournalReplacementItem; bytes: number } | undefined)[] = [] - let head = 0 - let bytes = 0 - return { - push(item) { - const itemBytes = Buffer.byteLength(JSON.stringify(item), 'utf8') - entries.push({ item, bytes: itemBytes }) - bytes += itemBytes - while (bytes > maxBytes && head < entries.length - 1) { - bytes -= entries[head]?.bytes ?? 0 - entries[head] = undefined - head += 1 - } - // Drop evicted entries in batches so a long source stays linear. - if (head > 1024 && head * 2 > entries.length) { - entries = entries.slice(head) - head = 0 - } - }, - items: () => entries.slice(head).flatMap((entry) => (entry ? [entry.item] : [])) - } -} - /** * A message whose only content is a tool invocation becomes a tool-call item so * the reducer renders it as one. Everything else stays a message item with its diff --git a/src/main/native-chat/agent-session-journal/journal-newest-item-window.ts b/src/main/native-chat/agent-session-journal/journal-newest-item-window.ts new file mode 100644 index 000000000000..39b975de2ee4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-newest-item-window.ts @@ -0,0 +1,29 @@ +import type { JournalReplacementItem } from './journal-epoch-replacement' + +/** The newest complete items that fit `maxBytes`; the latest item is always kept. */ +export function createNewestItemWindow(maxBytes: number): { + push(item: JournalReplacementItem): void + items(): JournalReplacementItem[] +} { + let entries: ({ item: JournalReplacementItem; bytes: number } | undefined)[] = [] + let head = 0 + let bytes = 0 + return { + push(item) { + const itemBytes = Buffer.byteLength(JSON.stringify(item), 'utf8') + entries.push({ item, bytes: itemBytes }) + bytes += itemBytes + while (bytes > maxBytes && head < entries.length - 1) { + bytes -= entries[head]?.bytes ?? 0 + entries[head] = undefined + head += 1 + } + // Drop evicted entries in batches so a long source stays linear. + if (head > 1024 && head * 2 > entries.length) { + entries = entries.slice(head) + head = 0 + } + }, + items: () => entries.slice(head).flatMap((entry) => (entry ? [entry.item] : [])) + } +} From 0aef11d19a358b3a10f55be951b00cb120b06524 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:35:16 -0700 Subject: [PATCH 32/38] fix(native-chat): restore the refusal error import lost in the main merge --- .../src/lib/structured-agent-session-launch-admission.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/renderer/src/lib/structured-agent-session-launch-admission.ts b/src/renderer/src/lib/structured-agent-session-launch-admission.ts index 94a68232e9bd..f767a4313fe1 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-admission.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-admission.ts @@ -13,6 +13,7 @@ import { type StructuredLaunchAdmission } from '@/lib/structured-agent-session-host-admission' import { holdEmptyWorkspaceDefaultSurfaceForLaunch } from '@/lib/empty-workspace-default-surface-claims' +import { StructuredAgentSessionCreateRefusalError } from '@/lib/structured-agent-session-launch-errors' import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' import type { StructuredAgentLaunchHooks, From 92ae7c064424f6240e32a29089b0296629567eba Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:14:12 -0700 Subject: [PATCH 33/38] test(native-chat): pass the layout owner in the layout-owner cancel test main's new test predates launch cancellation taking the active layout owner. --- ...uctured-launch-cancel-layout-owner.test.ts | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/renderer/src/runtime/structured-launch-cancel-layout-owner.test.ts b/src/renderer/src/runtime/structured-launch-cancel-layout-owner.test.ts index afcf5cd8ae84..a647d207fddc 100644 --- a/src/renderer/src/runtime/structured-launch-cancel-layout-owner.test.ts +++ b/src/renderer/src/runtime/structured-launch-cancel-layout-owner.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' import type { ExecutionHostId } from '../../../shared/execution-host' +import type { StructuredLaunchSlotOwner } from '@/lib/structured-agent-session-launch-slot' const mocks = vi.hoisted(() => ({ layoutOwnerIsMain: true, @@ -58,6 +59,11 @@ import { const WORKTREE = 'repo-1::worktree-1' const SESSION = 'chat-1' const LOCAL: RuntimeClientTarget = { kind: 'local' } +const layoutOwner: StructuredLaunchSlotOwner = { + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + reorderUnifiedTabs: vi.fn() +} const SERVER: RuntimeClientTarget = { kind: 'environment', environmentId: 'server-1' } const SERVER_HOST = 'runtime:server-1' @@ -140,7 +146,7 @@ describe('this machine, with main owning the layout', () => { mocks.callRuntime.mockRejectedValueOnce(new Error('tab_not_found')) pendingLaunch('local', LOCAL) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local', layoutOwner) await vi.waitFor(() => expect(mocks.callRuntime).toHaveBeenCalledWith(...hostTabClose)) expect(mocks.closeSession).toHaveBeenCalledWith(LOCAL, SESSION) @@ -153,7 +159,7 @@ describe('this machine, with main owning the layout', () => { it('create before the cancel (an aborted launch): closes the chat and its published tab', async () => { pendingLaunch('local', LOCAL) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local', layoutOwner) await vi.waitFor(() => expect(mocks.callRuntime).toHaveBeenCalledWith(...hostTabClose)) expect(mocks.closeSession).toHaveBeenCalledWith(LOCAL, SESSION) @@ -171,7 +177,7 @@ describe('this machine, with main owning the layout', () => { expectedRuntimeFence: null }) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local', layoutOwner) expect(mocks.closeSession).toHaveBeenCalledWith(LOCAL, SESSION) expect(readStructuredAgentLaunchRecord(SESSION)).toBeUndefined() @@ -184,7 +190,7 @@ describe('this machine, with main owning the layout', () => { const listener = vi.fn() subscribeStructuredAgentLaunchStatus(listener) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local', layoutOwner) await vi.waitFor(() => expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE, SESSION)).toBe(true) ) @@ -197,7 +203,7 @@ describe('this machine, with main owning the layout', () => { mocks.layoutOwnerIsMain = false pendingLaunch('local', LOCAL) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local') + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, 'local', layoutOwner) expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE, SESSION)).toBe(true) expect(mocks.closeSession).not.toHaveBeenCalled() @@ -208,7 +214,7 @@ describe('a paired server, with main owning the layout', () => { it('cancel before the create: keeps the tombstone and hides and closes the late listing', () => { pendingLaunch(SERVER_HOST, SERVER) - markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, SERVER_HOST) + markStructuredAgentSessionLaunchCancelled(WORKTREE, SESSION, SERVER_HOST, layoutOwner) expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE, SESSION)).toBe(true) expect(mocks.closeSession).not.toHaveBeenCalled() @@ -225,7 +231,8 @@ describe('a paired server, with main owning the layout', () => { target: SERVER, worktreeId: WORKTREE, sessionId: SESSION, - provisional: false + provisional: false, + layoutOwner }) expect(hasStructuredAgentSessionLaunchCancellationTombstone(WORKTREE, SESSION)).toBe(false) From 9f3adee9549ae59574c56e416309f71319263e6a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:22:25 -0700 Subject: [PATCH 34/38] fix(native-chat): admit Pi transcripts against the root Session History walks A PI_CODING_AGENT_DIR that already ends in sessions, or any custom folder, made admission expect /sessions while the lookup searched , so a found conversation was refused. --- src/main/pi/pi-transcript-import.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/pi/pi-transcript-import.ts b/src/main/pi/pi-transcript-import.ts index 573d3b78fd9c..15264a50da4e 100644 --- a/src/main/pi/pi-transcript-import.ts +++ b/src/main/pi/pi-transcript-import.ts @@ -7,7 +7,8 @@ import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-c import { readPiSessionHeader } from './rpc-launch-resolution' export const PI_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), + // The same root findTranscript walks, so a custom or sessions-leaf PI_CODING_AGENT_DIR admits. + transcriptRoot: () => piSessionHistorySessionsDir(), // Session History's host source is authoritative, including when the chat chose another home. accountHomeCandidates: () => [ process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), '.pi', 'agent') From 0fdce1355fa28faa156168c43b461e86f98e5e8d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:18:48 -0700 Subject: [PATCH 35/38] refactor(native-chat): admit and look up CLI transcripts in one store per account Each agent's import described where an account keeps its conversations twice, once for the path check and once for the lookup, and the two could disagree (the linked-folder and Pi custom-root refusals). The import now names one conversation store per account; the create path resolves it once and both the hook-path check and the fallback lookup judge that same store. OpenCode's store is its exact database. --- src/main/ai-vault/structured-chat-cli-fork.ts | 10 ++-- src/main/claude/claude-cli-conversations.ts | 9 ++-- src/main/codex/codex-cli-conversations.ts | 9 ++-- src/main/grok/grok-transcript-import.ts | 15 ++---- .../structured-agent-cli-conversations.ts | 54 ++++++++++--------- ...red-agent-session-source-admission.test.ts | 20 ++++++- src/main/omp/omp-session-cwd-lookup.test.ts | 24 +++++---- src/main/omp/omp-transcript-import.ts | 26 ++++----- .../opencode/opencode-transcript-import.ts | 30 +++++------ src/main/pi/pi-transcript-import.ts | 7 ++- ...tructured-agent-session-create-adoption.ts | 32 +++++++++-- 11 files changed, 128 insertions(+), 108 deletions(-) diff --git a/src/main/ai-vault/structured-chat-cli-fork.ts b/src/main/ai-vault/structured-chat-cli-fork.ts index f1282972b4da..1ef1ba3d5ff7 100644 --- a/src/main/ai-vault/structured-chat-cli-fork.ts +++ b/src/main/ai-vault/structured-chat-cli-fork.ts @@ -126,12 +126,10 @@ export async function prepareStructuredChatCliFork( throw new Error('The saved conversation does not match this chat.') } } else { - filePath = await importer.findTranscript({ - providerSessionId, - accountHome: record.accountHome, - launchEnv, - workspaceCwd: cwd - }) + const store = importer.conversationStore({ accountHome: record.accountHome, launchEnv }) + filePath = store + ? await importer.findTranscript({ providerSessionId, store, launchEnv, workspaceCwd: cwd }) + : null } if (!filePath || !isAbsolute(filePath) || isWslUncPath(filePath)) { throw new Error('This chat has no saved conversation to copy.') diff --git a/src/main/claude/claude-cli-conversations.ts b/src/main/claude/claude-cli-conversations.ts index 0a7be1041b82..c3391e69f236 100644 --- a/src/main/claude/claude-cli-conversations.ts +++ b/src/main/claude/claude-cli-conversations.ts @@ -11,17 +11,14 @@ import { } from '../native-chat/structured-agent-cli-conversations' const CLAUDE_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'projects'), + conversationStore: ({ accountHomePath }) => join(accountHomePath, 'projects'), accountHomeCandidates: ({ selectedAccountHomePath }) => [ selectedAccountHomePath, join(homedir(), '.claude'), ...(getClaudeProfileRouter()?.accountHomes() ?? []) ], - findTranscript: ({ providerSessionId, accountHomePath, strictErrors }) => - resolveSessionFilePath('claude', providerSessionId, { - claudeProjectsDir: join(accountHomePath, 'projects'), - strictErrors - }) + findTranscript: ({ providerSessionId, store, strictErrors }) => + resolveSessionFilePath('claude', providerSessionId, { claudeProjectsDir: store, strictErrors }) }) const CLAUDE_SESSION_HISTORY: StructuredAgentSessionHistory = { diff --git a/src/main/codex/codex-cli-conversations.ts b/src/main/codex/codex-cli-conversations.ts index 2b4e971afddf..29316254efa6 100644 --- a/src/main/codex/codex-cli-conversations.ts +++ b/src/main/codex/codex-cli-conversations.ts @@ -10,7 +10,7 @@ import { import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' const CODEX_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), + conversationStore: ({ accountHomePath }) => join(accountHomePath, 'sessions'), accountHomeCandidates: ({ settings, selectedAccountHomePath }) => [ selectedAccountHomePath, ...(settings.codexManagedAccounts ?? []).map((account) => account.managedHomePath), @@ -18,11 +18,8 @@ const CODEX_TRANSCRIPT_IMPORT = directoryTranscriptImport({ getOrcaManagedCodexHomePath(), getSystemCodexHomePath() ], - findTranscript: ({ providerSessionId, accountHomePath, strictErrors }) => - resolveSessionFilePath('codex', providerSessionId, { - codexSessionsDirs: [join(accountHomePath, 'sessions')], - strictErrors - }) + findTranscript: ({ providerSessionId, store, strictErrors }) => + resolveSessionFilePath('codex', providerSessionId, { codexSessionsDirs: [store], strictErrors }) }) const CODEX_SESSION_HISTORY: StructuredAgentSessionHistory = { diff --git a/src/main/grok/grok-transcript-import.ts b/src/main/grok/grok-transcript-import.ts index 8f995210adfb..dab984da73f9 100644 --- a/src/main/grok/grok-transcript-import.ts +++ b/src/main/grok/grok-transcript-import.ts @@ -4,20 +4,13 @@ import { resolveSessionFilePath } from '../native-chat/session-file-resolver' import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-conversations' export const GROK_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - transcriptRoot: ({ accountHomePath }) => join(accountHomePath, 'sessions'), + conversationStore: ({ accountHomePath }) => join(accountHomePath, 'sessions'), // The chat's own home, then the one Session History lists Grok's conversations from. accountHomeCandidates: ({ selectedAccountHomePath }) => [ selectedAccountHomePath, resolveGrokHomeDir() ], - findTranscript: async ({ providerSessionId, accountHomePath, workspaceCwd, strictErrors }) => { - const sessionsDir = join(accountHomePath, 'sessions') - return ( - (await findGrokChatHistoryByCwd({ - sessionId: providerSessionId, - cwd: workspaceCwd, - sessionsDir - })) ?? resolveSessionFilePath('grok', providerSessionId, { grokSessionsDir: sessionsDir, strictErrors }) - ) - } + findTranscript: async ({ providerSessionId, store, workspaceCwd, strictErrors }) => + (await findGrokChatHistoryByCwd({ sessionId: providerSessionId, cwd: workspaceCwd, sessionsDir: store })) ?? + resolveSessionFilePath('grok', providerSessionId, { grokSessionsDir: store, strictErrors }) }) diff --git a/src/main/native-chat/structured-agent-cli-conversations.ts b/src/main/native-chat/structured-agent-cli-conversations.ts index 0c9bb3c67a33..c56e77add999 100644 --- a/src/main/native-chat/structured-agent-cli-conversations.ts +++ b/src/main/native-chat/structured-agent-cli-conversations.ts @@ -1,6 +1,7 @@ // How a structured agent's chats meet the conversations its own CLI records: adopting one into a new // chat, and owning the Session History rows a chat's conversation shows as. +import { isAbsolute } from 'node:path' import { admitTranscriptPath } from './transcript-path-admission' import { isLegacyAgentSessionAccountHome, @@ -23,17 +24,19 @@ export type StructuredAgentTranscriptImport = { settings: StructuredAgentTranscriptImportSettings selectedAccountHome: AgentSessionAccountHome }) => AgentSessionAccountHome[] - /** Admit hook and fallback paths against this account's own storage. */ - admitTranscriptPath: (input: { + /** Where this account keeps its conversations (a directory, or OpenCode's database); null when + * it has none. Admission and lookup both take this one answer, so they cannot disagree. */ + conversationStore: (input: { accountHome: AgentSessionAccountHome - transcriptPath: string + /** The execution host's effective agent environment before account binding. */ launchEnv: NodeJS.ProcessEnv - }) => Promise - /** Where the transcript is (its file, or OpenCode's database); null when the home lacks it. */ + }) => string | null + /** Admit hook and fallback paths against the account's store. */ + admitTranscriptPath: (input: { store: string; transcriptPath: string }) => Promise + /** Where the transcript is (its file, or OpenCode's database); null when the store lacks it. */ findTranscript: (input: { providerSessionId: string - accountHome: AgentSessionAccountHome - /** The execution host's effective agent environment before account binding. */ + store: string launchEnv: NodeJS.ProcessEnv workspaceCwd: string strictErrors?: boolean @@ -43,15 +46,22 @@ export type StructuredAgentTranscriptImport = { } /** The import of an agent whose account is one directory, named by the chat's own variable. */ +/** A store is an absolute path; anything else is none, so lookup and admission agree on it. */ +export function absoluteConversationStore(path: string | null | undefined): string | null { + const trimmed = path?.trim() + return trimmed && isAbsolute(trimmed) ? trimmed : null +} + export function directoryTranscriptImport(directories: { - transcriptRoot: (input: { accountHomePath: string; launchEnv: NodeJS.ProcessEnv }) => string | null + conversationStore: (input: { accountHomePath: string; launchEnv: NodeJS.ProcessEnv }) => string | null accountHomeCandidates: (input: { settings: StructuredAgentTranscriptImportSettings selectedAccountHomePath: string }) => string[] + /** Searches only `store`; it never derives a root of its own. */ findTranscript: (input: { providerSessionId: string - accountHomePath: string + store: string launchEnv: NodeJS.ProcessEnv workspaceCwd: string strictErrors?: boolean @@ -59,13 +69,14 @@ export function directoryTranscriptImport(directories: { handleNamesTranscript?: true }): StructuredAgentTranscriptImport { return { - admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { - if (!isLegacyAgentSessionAccountHome(accountHome)) { - return null - } - const root = directories.transcriptRoot({ accountHomePath: accountHome.path, launchEnv }) - return root ? (await admitTranscriptPath(root, transcriptPath))?.path ?? null : null - }, + conversationStore: ({ accountHome, launchEnv }) => + isLegacyAgentSessionAccountHome(accountHome) + ? absoluteConversationStore( + directories.conversationStore({ accountHomePath: accountHome.path, launchEnv }) + ) + : null, + admitTranscriptPath: async ({ store, transcriptPath }) => + (await admitTranscriptPath(store, transcriptPath))?.path ?? null, ...(directories.handleNamesTranscript ? { handleNamesTranscript: true } : {}), accountHomeCandidates: ({ settings, selectedAccountHome }) => isLegacyAgentSessionAccountHome(selectedAccountHome) @@ -75,16 +86,7 @@ export function directoryTranscriptImport(directories: { .filter((path) => path.length > 0) .map((path) => ({ variable: selectedAccountHome.variable, path })) : [], - findTranscript: async ({ providerSessionId, accountHome, launchEnv, workspaceCwd, strictErrors }) => - isLegacyAgentSessionAccountHome(accountHome) - ? directories.findTranscript({ - providerSessionId, - accountHomePath: accountHome.path, - launchEnv, - workspaceCwd, - strictErrors - }) - : null + findTranscript: (input) => directories.findTranscript(input) } } diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts index fdf25427bcbb..3474e02b1fc4 100644 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ b/src/main/native-chat/structured-agent-session-source-admission.test.ts @@ -58,7 +58,7 @@ it('creates from the host hook path when Claude filename differs, then checks ac ]) const admit = importer.admitTranscriptPath.bind(importer) const admission = vi.spyOn(importer, 'admitTranscriptPath').mockImplementation((args) => { - if (!('path' in args.accountHome) || args.accountHome.path !== root) { + if (args.store !== join(root, 'projects')) { throw Object.assign(new Error('Account inaccessible'), { code: 'EACCES' }) } return admit(args) @@ -98,6 +98,24 @@ it('creates from the host hook path when Claude filename differs, then checks ac expect(find).not.toHaveBeenCalled() }) +it('judges the lookup and its re-admission against one store resolved once per account', async () => { + const transcriptPath = await file(join(root, 'projects', 'folder', `${id}.jsonl`), []) + const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! + const selectedAccountHome = { variable: 'CLAUDE_CONFIG_DIR', path: root } + vi.spyOn(importer, 'accountHomeCandidates').mockReturnValue([selectedAccountHome]) + const store = vi.spyOn(importer, 'conversationStore') + const find = vi.spyOn(importer, 'findTranscript') + const admission = vi.spyOn(importer, 'admitTranscriptPath') + const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ + settings: {}, agent: 'claude', transcriptImport: importer, providerSessionId: id, + selectedAccountHome, launchEnv: {}, workspaceCwd: root + }) + expect(adoption.transcriptPath).toBe(transcriptPath) + expect(store).toHaveBeenCalledOnce() + expect(find.mock.calls[0]?.[0].store).toBe(join(root, 'projects')) + expect(admission.mock.calls[0]?.[0].store).toBe(join(root, 'projects')) +}) + it.skipIf(process.platform === 'win32')('reports a not-yet-saved conversation under a linked account folder as unsaved', async () => { const linked = join(root, 'linked-account') await mkdir(join(root, 'projects'), { recursive: true }) diff --git a/src/main/omp/omp-session-cwd-lookup.test.ts b/src/main/omp/omp-session-cwd-lookup.test.ts index 44a2f72ff396..691275f09fcb 100644 --- a/src/main/omp/omp-session-cwd-lookup.test.ts +++ b/src/main/omp/omp-session-cwd-lookup.test.ts @@ -39,19 +39,21 @@ async function record(bucket: string, file = FILE): Promise { return path } -function lookup(cwd = '/repo/orca', homeDir = join(root, 'home'), temp = join(root, 'temp')) { - return OMP_TRANSCRIPT_IMPORT.findTranscript({ +async function lookup(cwd = '/repo/orca', homeDir = join(root, 'home'), temp = join(root, 'temp')) { + const launchEnv = { + OMP_CODING_AGENT_DIR: sessionsDir, + HOME: homeDir, + USERPROFILE: homeDir, + TMPDIR: temp, + TEMP: temp + } + const store = OMP_TRANSCRIPT_IMPORT.conversationStore({ accountHome: { variable: 'PI_CODING_AGENT_DIR', path: join(root, 'account') }, - providerSessionId: ID, - workspaceCwd: cwd, - launchEnv: { - OMP_CODING_AGENT_DIR: sessionsDir, - HOME: homeDir, - USERPROFILE: homeDir, - TMPDIR: temp, - TEMP: temp - } + launchEnv }) + return store + ? OMP_TRANSCRIPT_IMPORT.findTranscript({ providerSessionId: ID, store, workspaceCwd: cwd, launchEnv }) + : null } describe('OMP known-workspace transcript lookup', () => { diff --git a/src/main/omp/omp-transcript-import.ts b/src/main/omp/omp-transcript-import.ts index 4e250f81d130..4404c9671ef5 100644 --- a/src/main/omp/omp-transcript-import.ts +++ b/src/main/omp/omp-transcript-import.ts @@ -11,22 +11,16 @@ function sessionsRoot(accountHomePath: string, launchEnv: NodeJS.ProcessEnv) { } export const OMP_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - transcriptRoot: ({ accountHomePath, launchEnv }) => sessionsRoot(accountHomePath, launchEnv), + conversationStore: ({ accountHomePath, launchEnv }) => sessionsRoot(accountHomePath, launchEnv), accountHomeCandidates: ({ selectedAccountHomePath }) => [selectedAccountHomePath], // Where OMP itself keeps the account's sessions, which is not always under it (XDG_DATA_HOME). - findTranscript: async ({ providerSessionId, accountHomePath, launchEnv, workspaceCwd, strictErrors }) => { - const homeDir = - (process.platform === 'win32' ? launchEnv.USERPROFILE : launchEnv.HOME) || homedir() - const sessionsDir = sessionsRoot(accountHomePath, launchEnv) - return sessionsDir - ? findOmpSessionByCwd({ - sessionsDir, - sessionId: providerSessionId, - cwd: workspaceCwd, - homeDir, - env: launchEnv, - strictErrors - }) - : null - } + findTranscript: ({ providerSessionId, store, launchEnv, workspaceCwd, strictErrors }) => + findOmpSessionByCwd({ + sessionsDir: store, + sessionId: providerSessionId, + cwd: workspaceCwd, + homeDir: (process.platform === 'win32' ? launchEnv.USERPROFILE : launchEnv.HOME) || homedir(), + env: launchEnv, + strictErrors + }) }) diff --git a/src/main/opencode/opencode-transcript-import.ts b/src/main/opencode/opencode-transcript-import.ts index 2e43b963ce1a..daed142ffe4e 100644 --- a/src/main/opencode/opencode-transcript-import.ts +++ b/src/main/opencode/opencode-transcript-import.ts @@ -4,12 +4,15 @@ import { dirname } from 'node:path' import { homedir } from 'node:os' import { isLegacyAgentSessionAccountHome } from '../../shared/agent-session-account-home' import { getManagedDataAccountService } from '../managed-data-accounts/service' -import type { StructuredAgentTranscriptImport } from '../native-chat/structured-agent-cli-conversations' +import { + absoluteConversationStore, + type StructuredAgentTranscriptImport +} from '../native-chat/structured-agent-cli-conversations' import { resolveOpenCodeDatabasePath } from './opencode-data-directory' import { environmentForStructuredOpenCodeAccountHome } from './opencode-structured-account-home' function accountDatabase( - accountHome: Parameters[0]['accountHome'], + accountHome: Parameters[0]['accountHome'], launchEnv: NodeJS.ProcessEnv ) { if (isLegacyAgentSessionAccountHome(accountHome)) { @@ -19,18 +22,18 @@ function accountDatabase( managedAccounts: getManagedDataAccountService(), baseEnvironment: launchEnv }) - return resolveOpenCodeDatabasePath( - env, - (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir() + return absoluteConversationStore( + resolveOpenCodeDatabasePath( + env, + (process.platform === 'win32' ? env.USERPROFILE : env.HOME) || homedir() + ) ) } export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { - admitTranscriptPath: async ({ accountHome, transcriptPath, launchEnv }) => { - const dbPath = accountDatabase(accountHome, launchEnv) - if (!dbPath) { - return null - } + // The account's store is its exact database, which is the only one its chat can load from. + conversationStore: ({ accountHome, launchEnv }) => accountDatabase(accountHome, launchEnv), + admitTranscriptPath: async ({ store: dbPath, transcriptPath }) => { const [expected, actual] = await Promise.all([ admitTranscriptPath(dirname(dbPath), dbPath), admitTranscriptPath(dirname(dbPath), transcriptPath) @@ -42,12 +45,7 @@ export const OPENCODE_TRANSCRIPT_IMPORT: StructuredAgentTranscriptImport = { selectedAccountHome, { kind: 'opencode', locator: { kind: 'unmanaged' } } ], - // The database the account's OpenCode opens, which is the only one its chat can load from. - findTranscript: async ({ providerSessionId, accountHome, launchEnv }) => { - const dbPath = accountDatabase(accountHome, launchEnv) - if (!dbPath) { - return null - } + findTranscript: async ({ providerSessionId, store: dbPath }) => { try { if (!(await stat(dbPath)).isFile()) { return null diff --git a/src/main/pi/pi-transcript-import.ts b/src/main/pi/pi-transcript-import.ts index 15264a50da4e..0d439f9e34cc 100644 --- a/src/main/pi/pi-transcript-import.ts +++ b/src/main/pi/pi-transcript-import.ts @@ -7,15 +7,14 @@ import { directoryTranscriptImport } from '../native-chat/structured-agent-cli-c import { readPiSessionHeader } from './rpc-launch-resolution' export const PI_TRANSCRIPT_IMPORT = directoryTranscriptImport({ - // The same root findTranscript walks, so a custom or sessions-leaf PI_CODING_AGENT_DIR admits. - transcriptRoot: () => piSessionHistorySessionsDir(), + conversationStore: () => piSessionHistorySessionsDir(), // Session History's host source is authoritative, including when the chat chose another home. accountHomeCandidates: () => [ process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), '.pi', 'agent') ], // The file Session History lists under this id. - findTranscript: async ({ providerSessionId, strictErrors }) => { - const files = await walkSessionFiles(piSessionHistorySessionsDir(), 'pi', [], { + findTranscript: async ({ providerSessionId, store, strictErrors }) => { + const files = await walkSessionFiles(store, 'pi', [], { extensions: new Set(['.jsonl']), strictErrors, filePredicate: (path) => sessionIdFromFileName(path) === providerSessionId diff --git a/src/main/runtime/structured-agent-session-create-adoption.ts b/src/main/runtime/structured-agent-session-create-adoption.ts index bd2b7d3ccbdb..0288fdeb8d52 100644 --- a/src/main/runtime/structured-agent-session-create-adoption.ts +++ b/src/main/runtime/structured-agent-session-create-adoption.ts @@ -107,12 +107,24 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { try { const transcriptPath = input.resolveTranscriptPath?.() const candidates = input.transcriptImport.accountHomeCandidates(input) + // Each account's store is resolved once, so the hook path, the lookup and its re-admission + // all judge the same place even if the environment changes mid-create. + const stores = new Map() + const storeOf = (accountHome: AgentSessionAccountHome): string | null => { + if (!stores.has(accountHome)) { + stores.set(accountHome, input.transcriptImport.conversationStore({ + accountHome, launchEnv: input.launchEnv + })) + } + return stores.get(accountHome) ?? null + } let admitted: { accountHome: AgentSessionAccountHome; path: string } | null = null if (transcriptPath) { for (const accountHome of candidates) { - const path = await input.transcriptImport.admitTranscriptPath({ - accountHome, transcriptPath, launchEnv: input.launchEnv - }) + const store = storeOf(accountHome) + const path = store + ? await input.transcriptImport.admitTranscriptPath({ store, transcriptPath }) + : null if (path) { admitted = { accountHome, path } break @@ -139,11 +151,21 @@ export async function resolveStructuredAgentSessionAdoptionForCreate(input: { } } } - const found = await input.transcriptImport.findTranscript({ ...args, strictErrors: true }) + const store = storeOf(args.accountHome) + if (!store) { + return null + } + const found = await input.transcriptImport.findTranscript({ + providerSessionId: args.providerSessionId, + store, + launchEnv: args.launchEnv, + workspaceCwd: args.workspaceCwd, + strictErrors: true + }) if (!found) { return null } - const path = await input.transcriptImport.admitTranscriptPath({ ...args, transcriptPath: found }) + const path = await input.transcriptImport.admitTranscriptPath({ store, transcriptPath: found }) if (!path) { throw new Error('The conversation path is outside its account storage.') } From 56b78b7aca75534de3a014a61443e54f8499da94 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:10:27 -0700 Subject: [PATCH 36/38] fix(native-chat): keep a History resume that joins a terminal resume alive when the terminal closes A History click that joins a pending terminal-tab resume now takes the launch over: the terminal hand-off runs at join time and the create resumes by conversation id, so closing the terminal before create no longer abandons the shared launch. --- .../tab-bar/cli-chat-resume-run.test.ts | 26 +++++++++++++++ .../lib/structured-agent-session-launch.ts | 32 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts index 13952dfa7d3d..6902d867543a 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.test.ts @@ -271,6 +271,32 @@ describe('CLI identity resume through the existing launch owner', () => { expect(tabs()).toHaveLength(1) }) + it('still opens an eager History joiner after the terminal closes before create', async () => { + const capability = deferred() + mocks.createCapability.mockReturnValue(capability.promise) + const running = runCliChatResume(SOURCE) + await vi.waitFor(() => expect(mocks.createCapability).toHaveBeenCalledOnce()) + const eager = beginStructuredAgentSessionProvisionalLaunch({ + hooks: {}, + plan: adoptAgentSessionLaunchVerdict({ + route: 'structured-native-chat', + requestId: newAgentLaunchRequestId(), + agent: 'claude', + worktreeId: 'wt-1', + executionHostId: 'local', + resumeFrom: { providerSessionId: 'provider-1' } + }) + }) + mocks.source = null + useAppStore.setState({}) + capability.resolve(true) + await Promise.all([running, eager?.settlement]) + expect(mocks.call).toHaveBeenCalledOnce() + expect(mocks.call.mock.calls[0][2].resumeFrom).toEqual({ providerSessionId: 'provider-1' }) + expect(tabs()).toHaveLength(1) + expect(mocks.toast).not.toHaveBeenCalled() + }) + it.each([ ['reply', 'B', 'B E S R', 'B E S D R'], ['inventory', 'E', 'S B R E', 'S B D R E'], diff --git a/src/renderer/src/lib/structured-agent-session-launch.ts b/src/renderer/src/lib/structured-agent-session-launch.ts index f0fb8136a4d1..de7e92e005d4 100644 --- a/src/renderer/src/lib/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/structured-agent-session-launch.ts @@ -49,6 +49,7 @@ import { trackStructuredLaunchConfirmationDeadline } from './structured-agent-session-launch-prompt-outcome' import { repeatedStructuredLaunchAttempt } from './structured-agent-session-launch-request' +import { structuredAgentSessionCreateFingerprint } from '../../../shared/structured-agent-session-mutation' export type { StructuredAgentLaunchOptions, StructuredAgentLaunchReceipt } export { @@ -157,6 +158,35 @@ function promptOwner(options: StructuredAgentLaunchOptions): { callerKeepsText?: return options.promptKeptByCaller ? { callerKeepsText: true } : {} } +/** A joiner without the terminal pane must not fail when that pane closes: the unsent create hands + * off now and resumes by conversation id, as a History click does. */ +function releaseStructuredLaunchSource(state: StructuredLaunchState): void { + const { intent } = state + const handoff = intent.beforeCreate + if (!handoff) { + return + } + delete intent.beforeCreate + handoff() + const resumeFrom = intent.params.resumeFrom + if (!resumeFrom?.cliSource) { + return + } + const { cliSource: _paneSource, ...resumeById } = resumeFrom + const params = { ...intent.params, resumeFrom: resumeById } + intent.params = { + ...params, + envelope: { + ...params.envelope, + payloadFingerprint: structuredAgentSessionCreateFingerprint({ + sessionId: intent.sessionId, + ...params + }) + } + } + setStructuredLaunchState(state) +} + function joinStructuredLaunchState( existing: StructuredLaunchState, agent: TuiAgent, @@ -173,6 +203,8 @@ function joinStructuredLaunchState( : (repeat?.stagedPrompt ?? null) if (retrying) { restartStructuredLaunchState(existing) + } else if (!options.resumeFrom?.cliSource) { + releaseStructuredLaunchSource(existing) } if (!retrying && !repeat) { launchDraft.seedStructuredAgentLaunchDraft(existing.intent.sessionId, agent, joined) From 26656f53fc4ad6b6ba737b0837bf92ca34fe9f6d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:12:43 -0700 Subject: [PATCH 37/38] refactor(native-chat): move the launch source hand-off into its own module --- ...red-agent-session-launch-source-handoff.ts | 34 +++++++++++++++++++ .../lib/structured-agent-session-launch.ts | 31 +---------------- 2 files changed, 35 insertions(+), 30 deletions(-) create mode 100644 src/renderer/src/lib/structured-agent-session-launch-source-handoff.ts diff --git a/src/renderer/src/lib/structured-agent-session-launch-source-handoff.ts b/src/renderer/src/lib/structured-agent-session-launch-source-handoff.ts new file mode 100644 index 000000000000..15a8113c2d14 --- /dev/null +++ b/src/renderer/src/lib/structured-agent-session-launch-source-handoff.ts @@ -0,0 +1,34 @@ +import { structuredAgentSessionCreateFingerprint } from '../../../shared/structured-agent-session-mutation' +import { + setStructuredLaunchState, + type StructuredLaunchState +} from './structured-agent-session-launch-registry' + +/** A joiner without the terminal pane must not fail when that pane closes: the unsent create hands + * off now and resumes by conversation id, as a History click does. */ +export function releaseStructuredLaunchSource(state: StructuredLaunchState): void { + const { intent } = state + const handoff = intent.beforeCreate + if (!handoff) { + return + } + delete intent.beforeCreate + handoff() + const resumeFrom = intent.params.resumeFrom + if (!resumeFrom?.cliSource) { + return + } + const { cliSource: _paneSource, ...resumeById } = resumeFrom + const params = { ...intent.params, resumeFrom: resumeById } + intent.params = { + ...params, + envelope: { + ...params.envelope, + payloadFingerprint: structuredAgentSessionCreateFingerprint({ + sessionId: intent.sessionId, + ...params + }) + } + } + setStructuredLaunchState(state) +} diff --git a/src/renderer/src/lib/structured-agent-session-launch.ts b/src/renderer/src/lib/structured-agent-session-launch.ts index de7e92e005d4..73f7bef79516 100644 --- a/src/renderer/src/lib/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/structured-agent-session-launch.ts @@ -49,7 +49,7 @@ import { trackStructuredLaunchConfirmationDeadline } from './structured-agent-session-launch-prompt-outcome' import { repeatedStructuredLaunchAttempt } from './structured-agent-session-launch-request' -import { structuredAgentSessionCreateFingerprint } from '../../../shared/structured-agent-session-mutation' +import { releaseStructuredLaunchSource } from './structured-agent-session-launch-source-handoff' export type { StructuredAgentLaunchOptions, StructuredAgentLaunchReceipt } export { @@ -158,35 +158,6 @@ function promptOwner(options: StructuredAgentLaunchOptions): { callerKeepsText?: return options.promptKeptByCaller ? { callerKeepsText: true } : {} } -/** A joiner without the terminal pane must not fail when that pane closes: the unsent create hands - * off now and resumes by conversation id, as a History click does. */ -function releaseStructuredLaunchSource(state: StructuredLaunchState): void { - const { intent } = state - const handoff = intent.beforeCreate - if (!handoff) { - return - } - delete intent.beforeCreate - handoff() - const resumeFrom = intent.params.resumeFrom - if (!resumeFrom?.cliSource) { - return - } - const { cliSource: _paneSource, ...resumeById } = resumeFrom - const params = { ...intent.params, resumeFrom: resumeById } - intent.params = { - ...params, - envelope: { - ...params.envelope, - payloadFingerprint: structuredAgentSessionCreateFingerprint({ - sessionId: intent.sessionId, - ...params - }) - } - } - setStructuredLaunchState(state) -} - function joinStructuredLaunchState( existing: StructuredLaunchState, agent: TuiAgent, From c818a61de28bed33cf2c9082a695d5d5a873c2e3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:59:32 -0700 Subject: [PATCH 38/38] fix: pick the chat that adopts a header resume the way History does --- .../ai-vault-session-resume-in-chat-launch.ts | 2 +- .../src/components/tab-bar/cli-chat-resume-run.ts | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts index 0a12a02b1b05..49cdfb0356f7 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-in-chat-launch.ts @@ -73,7 +73,7 @@ export async function resumeAiVaultSessionInNewChat( /** The first chat the worktree's host does not refuse to take the row over, trying them in order. * A host that cannot answer yet keeps the chat it was asked about, whose own launch reports it. */ -async function adoptingAgentOnHost( +export async function adoptingAgentOnHost( rowAgent: CliConversationRowAgent, worktreeId: string ): Promise { diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts index 3accb7044b94..87a5e93246e8 100644 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts +++ b/src/renderer/src/components/tab-bar/cli-chat-resume-run.ts @@ -9,6 +9,7 @@ import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason import { CLI_CONVERSATION_ADOPTING_AGENTS } from '../../../../shared/structured-agent-cli-conversation-adoption' import { resolveCliChatResumeSource, type CliChatResumeSource } from './cli-chat-resume-source' import { reportCliChatResumeFailure } from './cli-chat-resume-feedback' +import { adoptingAgentOnHost } from '../right-sidebar/ai-vault-session-resume-in-chat-launch' const pending = new Map() const listeners = new Set<() => void>() @@ -103,10 +104,17 @@ export async function runCliChatResume( if (!isCurrent()) { return } + const agent = await waitForPromiseWithSignal( + adoptingAgentOnHost(source.agent, source.workspaceId), + controller.signal + ) + if (!isCurrent()) { + return + } const plan = adoptAgentSessionLaunchVerdict({ route: 'structured-native-chat', requestId: newAgentLaunchRequestId(), - agent: CLI_CONVERSATION_ADOPTING_AGENTS[source.agent], + agent, worktreeId: source.workspaceId, executionHostId: source.executionHostId, resumeFrom: {