diff --git a/src/main/ai-vault/runtime-session-scanner.test.ts b/src/main/ai-vault/runtime-session-scanner.test.ts new file mode 100644 index 000000000..ffb2a1c39 --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.test.ts @@ -0,0 +1,144 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AiVaultListResult, AiVaultSession } from '../../shared/ai-vault-types' + +const mocks = vi.hoisted(() => ({ + callRuntimeEnvironment: vi.fn(), + listEnvironments: vi.fn() +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: mocks.listEnvironments +})) + +vi.mock('../ipc/runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: mocks.callRuntimeEnvironment +})) + +const { getSavedRuntimeAiVaultHostInfos, scanRuntimeAiVaultSessions } = + await import('./runtime-session-scanner') + +beforeEach(() => { + vi.clearAllMocks() + mocks.listEnvironments.mockReturnValue([]) + mocks.callRuntimeEnvironment.mockResolvedValue({ + ok: true, + result: result([session('runtime:env-1', 'session-1')]) + }) +}) + +describe('runtime AI Vault session scanner', () => { + it('lists saved runtime environments as runtime execution hosts', () => { + mocks.listEnvironments.mockReturnValue([ + { id: 'env-1', name: 'Server 1' }, + { id: 'env-2', name: 'Server 2' } + ]) + + expect(getSavedRuntimeAiVaultHostInfos('/user-data')).toEqual([ + { environmentId: 'env-1', executionHostId: 'runtime:env-1' }, + { environmentId: 'env-2', executionHostId: 'runtime:env-2' } + ]) + }) + + it('forwards scan options to the runtime transport', async () => { + await scanRuntimeAiVaultSessions( + '/user-data', + 'env-1', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'] + }, + { timeoutMs: 3000 } + ) + + expect(mocks.callRuntimeEnvironment).toHaveBeenCalledWith( + '/user-data', + 'env-1', + 'aiVault.listSessions', + { + limit: 25, + force: true, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:env-1' + }, + 3000 + ) + }) + + it('stamps sessions and issues returned for a different execution host', async () => { + mocks.callRuntimeEnvironment.mockResolvedValueOnce({ + ok: true, + result: result( + [session('local', 'session-1')], + [ + { + executionHostId: 'ssh:dev-box', + agent: 'codex', + path: '/sessions/session-1.jsonl', + message: 'could not parse session' + } + ] + ) + }) + + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + expect(scanResult.issues).toEqual([ + expect.objectContaining({ + executionHostId: 'runtime:env-1', + agent: 'codex', + path: '/sessions/session-1.jsonl' + }) + ]) + }) + + it('stamps accepted sessions with the requested runtime host', async () => { + const scanResult = await scanRuntimeAiVaultSessions('/user-data', 'env-1', {}) + + expect(scanResult.sessions).toEqual([ + expect.objectContaining({ + id: 'runtime:env-1:codex:session-1:/sessions/session-1.jsonl', + executionHostId: 'runtime:env-1' + }) + ]) + }) +}) + +function result( + sessions: AiVaultSession[], + issues: AiVaultListResult['issues'] = [] +): AiVaultListResult { + return { sessions, issues, scannedAt: '2026-07-04T00:00:00.000Z' } +} + +function session( + executionHostId: AiVaultSession['executionHostId'], + sessionId: string +): AiVaultSession { + return { + id: `${executionHostId}:codex:${sessionId}:/sessions/${sessionId}.jsonl`, + executionHostId, + executionHostPlatform: 'linux', + agent: 'codex', + sessionId, + title: sessionId, + cwd: '/srv/app', + branch: null, + model: null, + filePath: `/sessions/${sessionId}.jsonl`, + codexHome: null, + createdAt: null, + updatedAt: '2026-07-04T03:00:00.000Z', + modifiedAt: '2026-07-04T00:00:00.000Z', + messageCount: 1, + totalTokens: 0, + previewMessages: [], + resumeCommand: `codex resume ${sessionId}` + } +} diff --git a/src/main/ai-vault/runtime-session-scanner.ts b/src/main/ai-vault/runtime-session-scanner.ts new file mode 100644 index 000000000..7a7008922 --- /dev/null +++ b/src/main/ai-vault/runtime-session-scanner.ts @@ -0,0 +1,176 @@ +import { z } from 'zod' +import { + AI_VAULT_AGENTS, + type AiVaultListArgs, + type AiVaultListResult, + type AiVaultSession +} from '../../shared/ai-vault-types' +import { normalizeExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host' +import { listEnvironments } from '../../shared/runtime-environment-store' +import { callRuntimeEnvironment } from '../ipc/runtime-environment-transport-routing' + +export type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + +export type RuntimeAiVaultScanOptions = { + timeoutMs?: number +} + +const nodePlatformSchema = z.enum([ + 'aix', + 'android', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'openbsd', + 'sunos', + 'win32', + 'cygwin', + 'netbsd' +] satisfies NodeJS.Platform[]) + +const aiVaultSessionPreviewMessageSchema = z.object({ + role: z.enum(['user', 'assistant', 'system', 'tool', 'unknown']), + text: z.string(), + timestamp: z.string().nullable() +}) + +const executionHostIdSchema = z.string().transform((value, ctx) => { + const normalized = normalizeExecutionHostId(value) + if (normalized) { + return normalized + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid execution host id' + }) + return z.NEVER +}) + +const aiVaultListResultSchema = z.object({ + sessions: z.array( + z.object({ + id: z.string(), + executionHostId: executionHostIdSchema, + executionHostPlatform: nodePlatformSchema.nullable().optional(), + agent: z.enum(AI_VAULT_AGENTS), + sessionId: z.string(), + title: z.string(), + cwd: z.string().nullable(), + branch: z.string().nullable(), + model: z.string().nullable(), + filePath: z.string(), + codexHome: z.string().nullable(), + createdAt: z.string().nullable(), + updatedAt: z.string().nullable(), + modifiedAt: z.string(), + messageCount: z.number(), + totalTokens: z.number(), + previewMessages: z.array(aiVaultSessionPreviewMessageSchema), + resumeCommand: z.string() + }) + ), + issues: z.array( + z.object({ + executionHostId: executionHostIdSchema.optional(), + agent: z.enum(AI_VAULT_AGENTS), + path: z.string(), + message: z.string() + }) + ), + scannedAt: z.string() +}) + +export function getSavedRuntimeAiVaultHostInfos( + userDataPath: string +): readonly RuntimeAiVaultHostInfo[] { + return listEnvironments(userDataPath).map((environment) => ({ + environmentId: environment.id, + executionHostId: toRuntimeExecutionHostId(environment.id) + })) +} + +export async function scanRuntimeAiVaultSessions( + userDataPath: string, + environmentId: string, + args: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const executionHostId = toRuntimeExecutionHostId(environmentId) + const response = await callRuntimeEnvironment( + userDataPath, + environmentId, + 'aiVault.listSessions', + { + limit: args.limit, + force: args.force, + scopePaths: args.scopePaths, + executionHostId + }, + options.timeoutMs + ) + if (response.ok === true) { + const parsed = aiVaultListResultSchema.safeParse(response.result) + if (parsed.success) { + return withRuntimeExecutionHost(parsed.data, executionHostId) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: `Invalid aiVault.listSessions response: ${ + parsed.error.issues[0]?.message ?? 'unexpected result shape' + }` + }) + } + return runtimeScanIssueResult({ + executionHostId, + environmentId, + message: response.error.message + }) +} + +function withRuntimeExecutionHost( + result: AiVaultListResult, + executionHostId: `runtime:${string}` +): AiVaultListResult { + return { + sessions: result.sessions.map((session) => retagRuntimeSession(session, executionHostId)), + issues: result.issues.map((issue) => ({ ...issue, executionHostId })), + scannedAt: result.scannedAt + } +} + +function retagRuntimeSession( + session: AiVaultSession, + executionHostId: `runtime:${string}` +): AiVaultSession { + // The paired server is the transport, but the parent owns which concrete + // runtime host was scanned; never trust returned host ids across the boundary. + return { + ...session, + executionHostId, + id: `${executionHostId}:${session.agent}:${session.sessionId}:${session.filePath}` + } +} + +function runtimeScanIssueResult(args: { + executionHostId: `runtime:${string}` + environmentId: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + executionHostId: args.executionHostId, + agent: 'codex', + path: args.environmentId, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/ai-vault/session-list-results.ts b/src/main/ai-vault/session-list-results.ts new file mode 100644 index 000000000..ea21dc590 --- /dev/null +++ b/src/main/ai-vault/session-list-results.ts @@ -0,0 +1,48 @@ +import type { + AiVaultListResult, + AiVaultScanIssue, + AiVaultSession +} from '../../shared/ai-vault-types' +import type { ExecutionHostId } from '../../shared/execution-host' +import { sessionSortTime } from './session-scanner-accumulator' + +export function aiVaultScanIssueResult(args: { + executionHostId?: ExecutionHostId + path: string + message: string +}): AiVaultListResult { + return { + sessions: [], + issues: [ + { + ...(args.executionHostId ? { executionHostId: args.executionHostId } : {}), + agent: 'codex', + path: args.path, + message: args.message + } + ], + scannedAt: new Date().toISOString() + } +} + +export function mergeAiVaultListResults( + results: readonly AiVaultListResult[], + rawLimit: number | undefined +): AiVaultListResult { + const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 + const byId = new Map() + const issues: AiVaultScanIssue[] = [] + for (const result of results) { + for (const session of result.sessions) { + byId.set(session.id, session) + } + issues.push(...result.issues) + } + return { + sessions: [...byId.values()] + .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) + .slice(0, limit), + issues, + scannedAt: new Date().toISOString() + } +} diff --git a/src/main/ipc/ai-vault.test.ts b/src/main/ipc/ai-vault.test.ts index 9cc8060ee..0fae2259f 100644 --- a/src/main/ipc/ai-vault.test.ts +++ b/src/main/ipc/ai-vault.test.ts @@ -6,6 +6,7 @@ import { getRemoteHostPlatform } from '../ssh/ssh-remote-platform' const mocks = vi.hoisted(() => ({ scanAiVaultSessions: vi.fn(), scanRemoteAiVaultSessions: vi.fn(), + scanRuntimeAiVaultSessions: vi.fn(), getAiVaultWslHomeDirs: vi.fn(), getSshFilesystemProvider: vi.fn(), getActiveSshAiVaultHostInfo: vi.fn(), @@ -41,7 +42,7 @@ vi.mock('./ssh', () => ({ getActiveSshAiVaultHostInfos: mocks.getActiveSshAiVaultHostInfos })) -const { _internals } = await import('./ai-vault') +const { _internals, registerAiVaultHandlers } = await import('./ai-vault') const provider = {} as IFilesystemProvider @@ -52,6 +53,9 @@ beforeEach(() => { mocks.scanRemoteAiVaultSessions.mockResolvedValue( result([session('ssh:dev-box', 'remote-session')]) ) + mocks.scanRuntimeAiVaultSessions.mockResolvedValue( + result([session('runtime:remote-server', 'runtime-session')]) + ) mocks.getSshFilesystemProvider.mockReturnValue(provider) mocks.getActiveSshAiVaultHostInfo.mockReturnValue(hostInfo('dev-box')) mocks.getActiveSshAiVaultHostInfos.mockReturnValue([hostInfo('dev-box')]) @@ -96,6 +100,77 @@ describe('listAiVaultSessions host routing', () => { expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) }) + it('merges paired runtime servers for all hosts', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [ + { + environmentId: 'remote-server', + executionHostId: 'runtime:remote-server' + } + ], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server' + }, + expect.objectContaining({ timeoutMs: expect.any(Number) }) + ) + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual([ + 'runtime:remote-server', + 'ssh:dev-box', + 'local' + ]) + }) + + it('keeps local and SSH results when runtime host discovery fails', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => { + throw new Error('runtime store is invalid') + }, + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + const result = await _internals.listAiVaultSessions({ executionHostScope: 'all' }) + + expect(mocks.scanAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRemoteAiVaultSessions).toHaveBeenCalledTimes(1) + expect(mocks.scanRuntimeAiVaultSessions).not.toHaveBeenCalled() + expect(result.sessions.map((entry) => entry.executionHostId)).toEqual(['ssh:dev-box', 'local']) + expect(result.issues).toEqual([ + expect.objectContaining({ + agent: 'codex', + path: 'runtime environments', + message: 'runtime store is invalid' + }) + ]) + }) + + it('keeps direct runtime host scans on the normal runtime timeout', async () => { + registerAiVaultHandlers({ + getActiveRuntimeAiVaultHostInfos: () => [], + scanRuntimeAiVaultSessions: mocks.scanRuntimeAiVaultSessions + }) + + await _internals.listAiVaultSessions({ + executionHostScope: 'runtime:remote-server', + force: true + }) + + expect(mocks.scanRuntimeAiVaultSessions).toHaveBeenCalledWith( + 'remote-server', + { + executionHostScope: 'runtime:remote-server', + force: true + }, + {} + ) + }) + it('returns a scan issue for a disconnected SSH target', async () => { mocks.getActiveSshAiVaultHostInfo.mockReturnValue(null) mocks.getSshFilesystemProvider.mockReturnValue(undefined) @@ -153,7 +228,11 @@ function session( codexHome: null, createdAt: null, updatedAt: - sessionId === 'remote-session' ? '2026-07-04T02:00:00.000Z' : '2026-07-04T01:00:00.000Z', + sessionId === 'runtime-session' + ? '2026-07-04T03:00:00.000Z' + : sessionId === 'remote-session' + ? '2026-07-04T02:00:00.000Z' + : '2026-07-04T01:00:00.000Z', modifiedAt: '2026-07-04T00:00:00.000Z', messageCount: 1, totalTokens: 0, diff --git a/src/main/ipc/ai-vault.ts b/src/main/ipc/ai-vault.ts index 4551379af..94a8de0c4 100644 --- a/src/main/ipc/ai-vault.ts +++ b/src/main/ipc/ai-vault.ts @@ -2,17 +2,14 @@ import { app, ipcMain } from 'electron' import { join } from 'node:path' import { scanRemoteAiVaultSessions } from '../ai-vault/remote-session-scanner' import { scanAiVaultSessions } from '../ai-vault/session-scanner' -import { sessionSortTime } from '../ai-vault/session-scanner-accumulator' +import { aiVaultScanIssueResult, mergeAiVaultListResults } from '../ai-vault/session-list-results' import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' -import type { - AiVaultListArgs, - AiVaultListResult, - AiVaultScanIssue -} from '../../shared/ai-vault-types' +import type { AiVaultListArgs, AiVaultListResult } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostScope, parseExecutionHostId, + toRuntimeExecutionHostId, toSshExecutionHostId, type ExecutionHostScope } from '../../shared/execution-host' @@ -23,9 +20,20 @@ import { import { getActiveSshAiVaultHostInfo, getActiveSshAiVaultHostInfos } from './ssh' const AI_VAULT_CACHE_TTL_MS = 15_000 +const AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS = 3_000 type AiVaultHandlerOptions = { getAdditionalCodexHomePaths?: () => readonly string[] + getActiveRuntimeAiVaultHostInfos?: () => readonly RuntimeAiVaultHostInfo[] + scanRuntimeAiVaultSessions?: ( + environmentId: string, + args: AiVaultListArgs, + options?: RuntimeAiVaultScanOptions + ) => Promise +} + +type RuntimeAiVaultScanOptions = { + timeoutMs?: number } type CachedAiVaultList = { @@ -34,6 +42,11 @@ type CachedAiVaultList = { expiresAt: number } +type RuntimeAiVaultHostInfo = { + environmentId: string + executionHostId: `runtime:${string}` +} + let cachedList: CachedAiVaultList | null = null let inflightList: Promise | null = null let inflightKey: string | null = null @@ -89,12 +102,20 @@ async function scanAiVaultSessionsByHostScope( } if (executionHostScope === 'all') { + const runtimeHosts = getActiveRuntimeAiVaultHostInfosResult() + const runtimeResults = runtimeHosts.issue ? [runtimeHosts.issue] : [] return mergeAiVaultListResults( await Promise.all([ scanLocalAiVaultSessions(args), ...getActiveSshAiVaultHostInfos().map((hostInfo) => scanSshAiVaultSessions(hostInfo.targetId, args) - ) + ), + ...runtimeHosts.hostInfos.map((hostInfo) => + scanRuntimeAiVaultSessions(hostInfo, args, { + timeoutMs: AI_VAULT_ALL_HOST_RUNTIME_TIMEOUT_MS + }) + ), + ...runtimeResults ]), args?.limit ) @@ -104,19 +125,88 @@ async function scanAiVaultSessionsByHostScope( if (parsed?.kind === 'ssh') { return scanSshAiVaultSessions(parsed.targetId, args) } - - return { - sessions: [], - issues: [ + if (parsed?.kind === 'runtime') { + return scanRuntimeAiVaultSessions( { - executionHostId: executionHostScope, - agent: 'codex', - path: executionHostScope, - message: 'Agent Session History is not available for this execution host.' - } - ], - scannedAt: new Date().toISOString() + environmentId: parsed.environmentId, + executionHostId: toRuntimeExecutionHostId(parsed.environmentId) + }, + args + ) } + + return aiVaultScanIssueResult({ + executionHostId: executionHostScope, + path: executionHostScope, + message: 'Agent Session History is not available for this execution host.' + }) +} + +function getActiveRuntimeAiVaultHostInfos(): readonly RuntimeAiVaultHostInfo[] { + return handlerOptions.getActiveRuntimeAiVaultHostInfos?.() ?? [] +} + +function getActiveRuntimeAiVaultHostInfosResult(): { + hostInfos: readonly RuntimeAiVaultHostInfo[] + issue?: AiVaultListResult +} { + try { + return { hostInfos: getActiveRuntimeAiVaultHostInfos() } + } catch (error) { + return { + hostInfos: [], + issue: runtimeHostDiscoveryIssueResult( + error instanceof Error ? error.message : 'Runtime hosts are unavailable.' + ) + } + } +} + +async function scanRuntimeAiVaultSessions( + hostInfo: RuntimeAiVaultHostInfo, + args?: AiVaultListArgs, + options: RuntimeAiVaultScanOptions = {} +): Promise { + const scanner = handlerOptions.scanRuntimeAiVaultSessions + if (!scanner) { + return runtimeScanIssueResult( + hostInfo, + 'Agent Session History is not available for this execution host.' + ) + } + const scanArgs: AiVaultListArgs = { executionHostScope: hostInfo.executionHostId } + if (args?.limit !== undefined) { + scanArgs.limit = args.limit + } + if (args?.force !== undefined) { + scanArgs.force = args.force + } + if (args?.scopePaths !== undefined) { + scanArgs.scopePaths = args.scopePaths + } + try { + return await scanner(hostInfo.environmentId, scanArgs, options) + } catch (error) { + return runtimeScanIssueResult( + hostInfo, + error instanceof Error ? error.message : 'Remote Orca server is unavailable.' + ) + } +} + +function runtimeScanIssueResult( + hostInfo: RuntimeAiVaultHostInfo, + message: string +): AiVaultListResult { + return aiVaultScanIssueResult({ + executionHostId: hostInfo.executionHostId, + path: hostInfo.environmentId, + message + }) +} + +function runtimeHostDiscoveryIssueResult(message: string): AiVaultListResult { + return aiVaultScanIssueResult({ path: 'runtime environments', message }) } async function scanLocalAiVaultSessions(args?: AiVaultListArgs): Promise { @@ -161,40 +251,11 @@ function sshScanIssueResult(args: { targetId: string message: string }): AiVaultListResult { - return { - sessions: [], - issues: [ - { - executionHostId: args.executionHostId, - agent: 'codex', - path: args.targetId, - message: args.message - } - ], - scannedAt: new Date().toISOString() - } -} - -function mergeAiVaultListResults( - results: readonly AiVaultListResult[], - rawLimit: number | undefined -): AiVaultListResult { - const limit = rawLimit && rawLimit > 0 ? Math.floor(rawLimit) : 1000 - const byId = new Map() - const issues: AiVaultScanIssue[] = [] - for (const result of results) { - for (const session of result.sessions) { - byId.set(session.id, session) - } - issues.push(...result.issues) - } - return { - sessions: [...byId.values()] - .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) - .slice(0, limit), - issues, - scannedAt: new Date().toISOString() - } + return aiVaultScanIssueResult({ + executionHostId: args.executionHostId, + path: args.targetId, + message: args.message + }) } export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): void { diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 0b7c4e071..6a73db56d 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -1,6 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { + getPathMock, + listEnvironmentsMock, + callRuntimeEnvironmentMock, registerCliHandlersMock, registerPreflightHandlersMock, registerClaudeUsageHandlersMock, @@ -57,6 +60,9 @@ const { registerEmulatorFrameStreamHandlersMock, registerEmulatorVideoStreamHandlersMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(() => '/test/user-data'), + listEnvironmentsMock: vi.fn(() => []), + callRuntimeEnvironmentMock: vi.fn(), registerCliHandlersMock: vi.fn(), registerPreflightHandlersMock: vi.fn(), registerClaudeUsageHandlersMock: vi.fn(), @@ -114,6 +120,20 @@ const { registerEmulatorVideoStreamHandlersMock: vi.fn() })) +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +vi.mock('../../shared/runtime-environment-store', () => ({ + listEnvironments: listEnvironmentsMock +})) + +vi.mock('./runtime-environment-transport-routing', () => ({ + callRuntimeEnvironment: callRuntimeEnvironmentMock +})) + vi.mock('./onboarding', () => ({ registerOnboardingHandlers: registerOnboardingHandlersMock })) @@ -326,6 +346,11 @@ import { registerCoreHandlers } from './register-core-handlers' describe('registerCoreHandlers', () => { beforeEach(() => { + getPathMock.mockReset() + getPathMock.mockReturnValue('/test/user-data') + listEnvironmentsMock.mockReset() + listEnvironmentsMock.mockReturnValue([]) + callRuntimeEnvironmentMock.mockReset() registerCliHandlersMock.mockReset() registerPreflightHandlersMock.mockReset() registerClaudeUsageHandlersMock.mockReset() @@ -382,7 +407,7 @@ describe('registerCoreHandlers', () => { registerEmulatorVideoStreamHandlersMock.mockReset() }) - it('passes the store through to handler registrars that need it', () => { + it('passes the store through to handler registrars that need it', async () => { const store = { marker: 'store' } const runtime = { marker: 'runtime', getAgentBrowserBridge: () => null } const stats = { marker: 'stats' } @@ -415,6 +440,14 @@ describe('registerCoreHandlers', () => { { getAdditionalAiVaultCodexHomePaths, onBeforeRelaunch } ) + const aiVaultOptions = registerAiVaultHandlersMock.mock.calls[0]?.[0] + expect(aiVaultOptions).toBeDefined() + + callRuntimeEnvironmentMock.mockResolvedValueOnce({ + ok: true, + result: { sessions: 'bad-shape' } + }) + expect(registerClaudeUsageHandlersMock).toHaveBeenCalledWith(claudeUsage) expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) expect(registerOpenCodeUsageHandlersMock).toHaveBeenCalledWith(openCodeUsage) @@ -451,9 +484,14 @@ describe('registerCoreHandlers', () => { expect(registerRuntimeHandlersMock).toHaveBeenCalledWith(runtime) expect(registerRuntimeEnvironmentHandlersMock).toHaveBeenCalledWith(store) expect(registerEphemeralVmHandlersMock).toHaveBeenCalledWith(store) - expect(registerAiVaultHandlersMock).toHaveBeenCalledWith({ - getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths - }) + expect(registerAiVaultHandlersMock).toHaveBeenCalledWith( + expect.objectContaining({ + getAdditionalCodexHomePaths: getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: expect.any(Function), + scanRuntimeAiVaultSessions: expect.any(Function) + }) + ) + expect(aiVaultOptions.getActiveRuntimeAiVaultHostInfos()).toEqual([]) expect(registerNativeChatHandlersMock).toHaveBeenCalled() expect(registerCliHandlersMock).toHaveBeenCalled() expect(registerPreflightHandlersMock).toHaveBeenCalled() @@ -466,6 +504,40 @@ describe('registerCoreHandlers', () => { expect(registerBrowserHandlersMock).toHaveBeenCalled() expect(registerFilesystemWatcherHandlersMock).toHaveBeenCalled() expect(registerSpeechHandlersMock).toHaveBeenCalledWith(store) + + await expect( + aiVaultOptions.scanRuntimeAiVaultSessions( + 'env-123', + { + limit: 10, + scopePaths: ['/workspace'] + }, + { timeoutMs: 3000 } + ) + ).resolves.toEqual({ + sessions: [], + issues: [ + expect.objectContaining({ + executionHostId: 'runtime:env-123', + agent: 'codex', + path: 'env-123', + message: expect.stringContaining('Invalid aiVault.listSessions response') + }) + ], + scannedAt: expect.any(String) + }) + expect(callRuntimeEnvironmentMock).toHaveBeenCalledWith( + '/test/user-data', + 'env-123', + 'aiVault.listSessions', + { + limit: 10, + force: undefined, + scopePaths: ['/workspace'], + executionHostId: 'runtime:env-123' + }, + 3000 + ) }) it('only registers IPC handlers once but always updates web contents id', () => { diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 50dbd0a8f..f651cd002 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -1,3 +1,4 @@ +import { app } from 'electron' import { registerAppHandlers } from './app' import { registerCliHandlers } from './cli' import { registerPreflightHandlers } from './preflight' @@ -69,6 +70,10 @@ import type { AutomationService } from '../automations/service' import type { AgentAwakeService } from '../agent-awake-service' import type { CrashReportStore } from '../crash-reporting/crash-report-store' import type { KeybindingService } from '../keybindings/keybinding-service' +import { + getSavedRuntimeAiVaultHostInfos, + scanRuntimeAiVaultSessions +} from '../ai-vault/runtime-session-scanner' let registered = false @@ -171,7 +176,11 @@ export function registerCoreHandlers( registerRuntimeEnvironmentHandlers(store) registerEphemeralVmHandlers(store) registerAiVaultHandlers({ - getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths + getAdditionalCodexHomePaths: lifecycleOptions.getAdditionalAiVaultCodexHomePaths, + getActiveRuntimeAiVaultHostInfos: () => + getSavedRuntimeAiVaultHostInfos(app.getPath('userData')), + scanRuntimeAiVaultSessions: async (environmentId, args, options) => + scanRuntimeAiVaultSessions(app.getPath('userData'), environmentId, args, options) }) registerNativeChatHandlers() registerClipboardHandlers(store) diff --git a/src/main/runtime/rpc/methods/ai-vault.test.ts b/src/main/runtime/rpc/methods/ai-vault.test.ts new file mode 100644 index 000000000..c7cc56a64 --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { AI_VAULT_METHODS } from './ai-vault' + +const mocks = vi.hoisted(() => ({ + scanAiVaultSessions: vi.fn() +})) + +vi.mock('../../../ai-vault/session-scanner', () => ({ + scanAiVaultSessions: mocks.scanAiVaultSessions +})) + +beforeEach(() => { + vi.clearAllMocks() + mocks.scanAiVaultSessions.mockResolvedValue({ + sessions: [], + issues: [], + scannedAt: '2026-07-04T00:00:00.000Z' + }) +}) + +describe('aiVault.listSessions runtime RPC', () => { + it('scans server-local sessions under the caller supplied runtime host id', async () => { + const method = AI_VAULT_METHODS.find((entry) => entry.name === 'aiVault.listSessions') + expect(method).toBeDefined() + + const params = method!.params!.parse({ + limit: 25, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:remote-server' + }) + + await method!.handler(params, {} as never) + + expect(mocks.scanAiVaultSessions).toHaveBeenCalledWith({ + limit: 25, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:remote-server' + }) + }) + + it('rejects non-runtime execution host ids before dispatch', () => { + const method = AI_VAULT_METHODS.find((entry) => entry.name === 'aiVault.listSessions') + expect(method).toBeDefined() + + expect(() => + method!.params!.parse({ + executionHostId: 'not-a-runtime-host' + }) + ).toThrow('Invalid runtime execution host id') + expect(() => + method!.params!.parse({ + executionHostId: 'local' + }) + ).toThrow('Invalid runtime execution host id') + expect(() => + method!.params!.parse({ + executionHostId: 'ssh:dev-box' + }) + ).toThrow('Invalid runtime execution host id') + }) +}) diff --git a/src/main/runtime/rpc/methods/ai-vault.ts b/src/main/runtime/rpc/methods/ai-vault.ts new file mode 100644 index 000000000..49591ea1e --- /dev/null +++ b/src/main/runtime/rpc/methods/ai-vault.ts @@ -0,0 +1,36 @@ +import { z } from 'zod' +import { scanAiVaultSessions } from '../../../ai-vault/session-scanner' +import { defineMethod, type RpcMethod } from '../core' +import { parseExecutionHostId } from '../../../../shared/execution-host' + +const executionHostIdSchema = z.string().transform((value, ctx): `runtime:${string}` => { + const parsed = parseExecutionHostId(value) + if (parsed?.kind === 'runtime') { + return parsed.id + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid runtime execution host id' + }) + return z.NEVER +}) + +const listSessionsParamsSchema = z.object({ + limit: z.number().int().positive().optional(), + force: z.boolean().optional(), + scopePaths: z.array(z.string()).optional(), + executionHostId: executionHostIdSchema +}) + +export const AI_VAULT_METHODS: RpcMethod[] = [ + defineMethod({ + name: 'aiVault.listSessions', + params: listSessionsParamsSchema, + handler: async (params) => + scanAiVaultSessions({ + limit: params.limit, + scopePaths: params.scopePaths, + executionHostId: params.executionHostId + }) + }) +] diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 8018375a8..bc0a73985 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -1,5 +1,6 @@ import type { RpcAnyMethod } from '../core' import { STATUS_METHODS } from './status' +import { AI_VAULT_METHODS } from './ai-vault' import { AUTOMATION_METHODS } from './automations' import { REPO_METHODS } from './repo' import { WORKTREE_METHODS } from './worktree' @@ -39,6 +40,7 @@ import { EMULATOR_METHODS } from './emulator' // auditing the security boundary or wiring new CLI commands. export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ ...STATUS_METHODS, + ...AI_VAULT_METHODS, ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx index 8442e73f5..4a6bccec9 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanel.tsx @@ -28,7 +28,6 @@ import { import { useAiVaultSessionLaunchActions } from './ai-vault-session-launch-actions' import { useAiVaultSessionWorktreeMap } from './ai-vault-session-worktree' import { useAiVaultOriginalPaneActions } from './ai-vault-original-pane-actions' -import { getAiVaultResumeWorkspaceTargetStatus } from '@/lib/ai-vault-resume-target' import { AI_VAULT_AGENTS, type AiVaultAgent, @@ -41,7 +40,11 @@ import { translate } from '@/i18n/i18n' import { AiVaultPanelHeader } from './AiVaultPanelHeader' import { AiVaultSessionVirtualList } from './AiVaultSessionVirtualList' import { useAiVaultSessionRefresh } from './ai-vault-session-refresh' -import { useAiVaultExecutionHostScope } from './ai-vault-host-scope' +import { + buildAiVaultHostScopeOptions, + buildRuntimeAiVaultHostScopeOptions, + useAiVaultExecutionHostScope +} from './ai-vault-host-scope' export default function AiVaultPanel(): React.JSX.Element { const activeWorktreeId = useActiveWorktreeId() @@ -59,6 +62,7 @@ export default function AiVaultPanel(): React.JSX.Element { })) ) const settings = useAppStore((s) => s.settings) + const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments) const agentCmdOverrides = settings?.agentCmdOverrides const { getOriginalPaneTarget, jumpToOriginalPane, jumpToWorktree } = useAiVaultOriginalPaneActions() @@ -72,17 +76,28 @@ export default function AiVaultPanel(): React.JSX.Element { const userChangedScopeRef = useRef(false) const preferredScopeRef = useRef(DEFAULT_AI_VAULT_SCOPE) - const isRuntimeWorktree = useMemo( - () => - getAiVaultResumeWorkspaceTargetStatus(resumeTargetState, activeWorktreeId ?? null) === - 'runtime', - [activeWorktreeId, resumeTargetState] + const runtimeHostOptions = useMemo( + () => buildRuntimeAiVaultHostScopeOptions(runtimeEnvironments), + [runtimeEnvironments] ) - const { executionHostScope, activeSshExecutionHostScope, onExecutionHostScopeChange } = + const availableExecutionHostScopes = useMemo( + () => runtimeHostOptions.map((option) => option.id), + [runtimeHostOptions] + ) + const { executionHostScope, activeExecutionHostScope, onExecutionHostScopeChange } = useAiVaultExecutionHostScope({ activeWorktreeId: activeWorktreeId ?? null, - resumeTargetState + resumeTargetState, + availableExecutionHostScopes }) + const hostScopeOptions = useMemo( + () => + buildAiVaultHostScopeOptions({ + activeExecutionHostScope, + runtimeHostOptions + }), + [activeExecutionHostScope, runtimeHostOptions] + ) const activeWorktreePath = activeWorktree?.path ?? null // Why: AI Vault ownership is cwd-based, so we must consider live worktrees across all repos. const activeWorktreePaths = useMemo( @@ -306,7 +321,7 @@ export default function AiVaultPanel(): React.JSX.Element { activeProjectKey={activeProjectKey} scope={scope} executionHostScope={executionHostScope} - activeSshExecutionHostScope={activeSshExecutionHostScope} + hostScopeOptions={hostScopeOptions} agents={agents} sort={sort} group={group} @@ -323,15 +338,6 @@ export default function AiVaultPanel(): React.JSX.Element { onRefresh={() => void refresh({ force: true })} /> - {isRuntimeWorktree ? ( -
- {translate( - 'auto.components.right.sidebar.AiVaultPanel.runtimeBrowseLocalHistory', - 'Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.' - )} -
- ) : null} - {error ? (
{error} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx index 2b3cc2802..b64308b94 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelControls.tsx @@ -32,14 +32,10 @@ import { type AiVaultScope, type AiVaultSort } from '../../../../shared/ai-vault-types' -import { - ALL_EXECUTION_HOSTS_SCOPE, - getExecutionHostLabel, - LOCAL_EXECUTION_HOST_ID, - type ExecutionHostScope -} from '../../../../shared/execution-host' +import { getExecutionHostLabel, type ExecutionHostScope } from '../../../../shared/execution-host' import { agentLabel, type AiVaultSessionGroup } from './ai-vault-session-filters' import { translate } from '@/i18n/i18n' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' const VAULT_HEADER_CONTROL_CLASS = 'size-6 shrink-0' @@ -184,19 +180,15 @@ export function VaultScopeSwitch({ export function VaultHostScopeMenu({ executionHostScope, - activeSshExecutionHostScope, + hostOptions, onExecutionHostScopeChange }: { executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostOptions: readonly AiVaultHostScopeOption[] onExecutionHostScopeChange: (scope: ExecutionHostScope) => void }): React.JSX.Element { - const hostOptions = [ - LOCAL_EXECUTION_HOST_ID, - ...(activeSshExecutionHostScope ? [activeSshExecutionHostScope] : []), - ALL_EXECUTION_HOSTS_SCOPE - ] as const - const label = getExecutionHostLabel(executionHostScope) + const selectedOption = hostOptions.find((option) => option.id === executionHostScope) + const label = selectedOption?.label ?? getExecutionHostLabel(executionHostScope) return ( @@ -224,9 +216,9 @@ export function VaultHostScopeMenu({ value={executionHostScope} onValueChange={(value) => onExecutionHostScopeChange(value as ExecutionHostScope)} > - {hostOptions.map((scope) => ( - - {getExecutionHostLabel(scope)} + {hostOptions.map((option) => ( + + {option.label} ))} diff --git a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx index b463e188a..b3ec2ba36 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultPanelHeader.tsx @@ -9,6 +9,7 @@ import type { } from '../../../../shared/ai-vault-types' import type { ExecutionHostScope } from '../../../../shared/execution-host' import { VaultHostScopeMenu, VaultScopeSwitch, VaultViewMenu } from './AiVaultPanelControls' +import type { AiVaultHostScopeOption } from './ai-vault-host-scope' type AiVaultPanelHeaderProps = { query: string @@ -20,7 +21,7 @@ type AiVaultPanelHeaderProps = { activeProjectKey: string | null scope: AiVaultScope executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + hostScopeOptions: readonly AiVaultHostScopeOption[] agents: readonly AiVaultAgent[] sort: AiVaultSort group: AiVaultGroup @@ -47,7 +48,7 @@ export function AiVaultPanelHeader({ activeProjectKey, scope, executionHostScope, - activeSshExecutionHostScope, + hostScopeOptions, agents, sort, group, @@ -108,7 +109,7 @@ export function AiVaultPanelHeader({
@@ -15,6 +20,7 @@ let latest: HostScopeResult | null = null function HookProbe(props: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): null { latest = useAiVaultExecutionHostScope(props) return null @@ -23,6 +29,7 @@ function HookProbe(props: { async function renderHook(props: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): Promise { if (!root) { const container = document.createElement('div') @@ -83,7 +90,7 @@ describe('useAiVaultExecutionHostScope', () => { }) expect(latest?.executionHostScope).toBe('ssh:dev-box') - expect(latest?.activeSshExecutionHostScope).toBe('ssh:dev-box') + expect(latest?.activeExecutionHostScope).toBe('ssh:dev-box') }) it('defaults local worktrees to local history', async () => { @@ -96,7 +103,22 @@ describe('useAiVaultExecutionHostScope', () => { }) expect(latest?.executionHostScope).toBe('local') - expect(latest?.activeSshExecutionHostScope).toBeNull() + expect(latest?.activeExecutionHostScope).toBeNull() + }) + + it('defaults runtime worktrees to their runtime execution host', async () => { + await renderHook({ + activeWorktreeId: 'repo-1::/runtime/repo', + resumeTargetState: stateForWorktree({ + worktreeId: 'repo-1::/runtime/repo', + repoId: 'repo-1', + executionHostId: 'runtime:remote-server' + }), + availableExecutionHostScopes: ['runtime:remote-server'] as const + }) + + expect(latest?.executionHostScope).toBe('runtime:remote-server') + expect(latest?.activeExecutionHostScope).toBe('runtime:remote-server') }) it('preserves manual host scope changes across unrelated rerenders', async () => { @@ -117,4 +139,56 @@ describe('useAiVaultExecutionHostScope', () => { expect(latest?.executionHostScope).toBe('all') }) + + it('preserves manual runtime host scope choices while they are still available', async () => { + const props = { + activeWorktreeId: 'repo-1::/local/repo', + resumeTargetState: stateForWorktree({ + worktreeId: 'repo-1::/local/repo', + repoId: 'repo-1' + }), + availableExecutionHostScopes: ['runtime:remote-server'] as const + } + await renderHook(props) + + await act(async () => { + latest?.onExecutionHostScopeChange('runtime:remote-server') + }) + await renderHook({ ...props, resumeTargetState: { ...props.resumeTargetState } }) + + expect(latest?.executionHostScope).toBe('runtime:remote-server') + }) +}) + +describe('buildAiVaultHostScopeOptions', () => { + it('adds saved runtime hosts between active SSH and all hosts', () => { + const runtimeHostOptions = buildRuntimeAiVaultHostScopeOptions([ + { id: 'remote-server', name: 'VPS Orca Server' } + ]) + + expect( + buildAiVaultHostScopeOptions({ + activeExecutionHostScope: 'ssh:dev-box', + runtimeHostOptions + }) + ).toEqual([ + { id: 'local', label: expect.any(String) }, + { id: 'ssh:dev-box', label: 'dev-box' }, + { id: 'runtime:remote-server', label: 'VPS Orca Server' }, + { id: 'all', label: 'All hosts' } + ]) + }) + + it('keeps a runtime active host visible even before the saved environment list hydrates', () => { + expect( + buildAiVaultHostScopeOptions({ + activeExecutionHostScope: 'runtime:remote-server', + runtimeHostOptions: [] + }) + ).toEqual([ + { id: 'local', label: expect.any(String) }, + { id: 'runtime:remote-server', label: 'remote-server' }, + { id: 'all', label: 'All hosts' } + ]) + }) }) diff --git a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts index 8993e8a00..0acb4f546 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-host-scope.ts @@ -2,18 +2,28 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { getAiVaultResumeWorkspaceExecutionHostId } from '@/lib/ai-vault-resume-target' import { ALL_EXECUTION_HOSTS_SCOPE, + getExecutionHostLabel, LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostId, type ExecutionHostScope } from '../../../../shared/execution-host' +import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' import type { AiVaultSessionResumeTargetState } from './ai-vault-session-resume' +export type AiVaultHostScopeOption = { + id: ExecutionHostScope + label: string +} + export function useAiVaultExecutionHostScope(args: { activeWorktreeId: string | null resumeTargetState: AiVaultSessionResumeTargetState + availableExecutionHostScopes?: readonly ExecutionHostScope[] }): { executionHostScope: ExecutionHostScope - activeSshExecutionHostScope: ExecutionHostScope | null + activeExecutionHostScope: ExecutionHostId | null onExecutionHostScopeChange: (scope: ExecutionHostScope) => void } { const userChangedHostScopeRef = useRef(false) @@ -22,10 +32,12 @@ export function useAiVaultExecutionHostScope(args: { [args.activeWorktreeId, args.resumeTargetState] ) const activeExecutionHost = parseExecutionHostId(activeExecutionHostId) + const activeExecutionHostScope: ExecutionHostId | null = + activeExecutionHost?.kind === 'ssh' || activeExecutionHost?.kind === 'runtime' + ? activeExecutionHost.id + : null const defaultExecutionHostScope: ExecutionHostScope = - activeExecutionHost?.kind === 'ssh' ? activeExecutionHost.id : LOCAL_EXECUTION_HOST_ID - const activeSshExecutionHostScope: ExecutionHostScope | null = - activeExecutionHost?.kind === 'ssh' ? activeExecutionHost.id : null + activeExecutionHostScope ?? LOCAL_EXECUTION_HOST_ID const [executionHostScope, setExecutionHostScope] = useState(defaultExecutionHostScope) @@ -36,7 +48,8 @@ export function useAiVaultExecutionHostScope(args: { const allowedScopes = new Set([ LOCAL_EXECUTION_HOST_ID, ALL_EXECUTION_HOSTS_SCOPE, - ...(activeSshExecutionHostScope ? [activeSshExecutionHostScope] : []) + ...(activeExecutionHostScope ? [activeExecutionHostScope] : []), + ...(args.availableExecutionHostScopes ?? []) ]) if (!allowedScopes.has(executionHostScope)) { setExecutionHostScope(defaultExecutionHostScope) @@ -46,7 +59,12 @@ export function useAiVaultExecutionHostScope(args: { if (!userChangedHostScopeRef.current && executionHostScope !== defaultExecutionHostScope) { setExecutionHostScope(defaultExecutionHostScope) } - }, [activeSshExecutionHostScope, defaultExecutionHostScope, executionHostScope]) + }, [ + activeExecutionHostScope, + args.availableExecutionHostScopes, + defaultExecutionHostScope, + executionHostScope + ]) const handleExecutionHostScopeChange = useCallback( (nextScope: ExecutionHostScope) => { @@ -58,7 +76,49 @@ export function useAiVaultExecutionHostScope(args: { return { executionHostScope, - activeSshExecutionHostScope, + activeExecutionHostScope, onExecutionHostScopeChange: handleExecutionHostScopeChange } } + +export function buildRuntimeAiVaultHostScopeOptions( + runtimeEnvironments: readonly Pick[] +): AiVaultHostScopeOption[] { + return runtimeEnvironments.map((environment) => { + const id = toRuntimeExecutionHostId(environment.id) + const label = environment.name.trim() || getExecutionHostLabel(id) + return { id, label } + }) +} + +export function buildAiVaultHostScopeOptions(args: { + activeExecutionHostScope: ExecutionHostId | null + runtimeHostOptions: readonly AiVaultHostScopeOption[] +}): AiVaultHostScopeOption[] { + const options: AiVaultHostScopeOption[] = [] + const seen = new Set() + const add = (option: AiVaultHostScopeOption): void => { + if (seen.has(option.id)) { + return + } + seen.add(option.id) + options.push(option) + } + const activeHost = args.activeExecutionHostScope + ? parseExecutionHostId(args.activeExecutionHostScope) + : null + + add({ id: LOCAL_EXECUTION_HOST_ID, label: getExecutionHostLabel(LOCAL_EXECUTION_HOST_ID) }) + if (activeHost?.kind === 'ssh') { + add({ id: activeHost.id, label: getExecutionHostLabel(activeHost.id) }) + } + for (const option of args.runtimeHostOptions) { + add(option) + } + if (activeHost?.kind === 'runtime') { + add({ id: activeHost.id, label: getExecutionHostLabel(activeHost.id) }) + } + add({ id: ALL_EXECUTION_HOSTS_SCOPE, label: getExecutionHostLabel(ALL_EXECUTION_HOSTS_SCOPE) }) + + return options +} diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts index c55acb1e9..78daad963 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-launch-actions.ts @@ -100,21 +100,40 @@ export function useAiVaultSessionLaunchActions({ return } - launchAiVaultSessionInNewTab({ + const launchResult = launchAiVaultSessionInNewTab({ agent: session.agent, worktreeId: targetId.worktreeId, ...buildResumeStartup(session, targetId.worktreeId) }) + const showQueuedToast = (): void => { + toast.success( + translate( + 'auto.components.right.sidebar.AiVaultPanel.agentSessionQueued', + '{{value0}} session queued', + { value0: agentLabel(session.agent) } + ) + ) + } + if (launchResult.tabId === null) { + void launchResult.runtimeLaunch.then((created) => { + if (!created) { + toast.error( + translate( + 'auto.lib.launch.agent.in.new.tab.11cce5cc77', + 'Could not launch {{value0}} in a new terminal.', + { value0: agentLabel(session.agent) } + ) + ) + return + } + showQueuedToast() + }) + return + } if (useAppStore.getState().activeWorktreeId !== targetId.worktreeId) { activateAiVaultResumeWorkspace(targetId.worktreeId) } - toast.success( - translate( - 'auto.components.right.sidebar.AiVaultPanel.agentSessionQueued', - '{{value0}} session queued', - { value0: agentLabel(session.agent) } - ) - ) + showQueuedToast() }, [activeWorktree?.id, activeWorktreeId, buildResumeStartup, targetState] ) @@ -167,15 +186,9 @@ export function resolveAiVaultSessionLaunchTarget(args: { function aiVaultResumeUnsupportedMessage( targetStatus: ReturnType ): string { - if (targetStatus === 'runtime') { - return translate( - 'auto.components.right.sidebar.AiVaultPanel.runtimeWorkspacesUnsupported', - 'Resume from history is not available in runtime-hosted workspaces.' - ) - } // Why: local and SSH targets can both be valid generally; this branch means // the session's recorded host does not match the selected workspace. - if (targetStatus === 'ssh' || targetStatus === 'local') { + if (targetStatus === 'ssh' || targetStatus === 'local' || targetStatus === 'runtime') { return translate( 'auto.components.right.sidebar.AiVaultPanel.sessionHostMismatchUnsupported', 'This session belongs to a different host. Open a workspace on the same host to resume it.' @@ -183,7 +196,7 @@ function aiVaultResumeUnsupportedMessage( } return translate( 'auto.components.right.sidebar.AiVaultPanel.openSupportedWorkspace', - 'Open a local or SSH workspace before resuming a session.' + 'Open a workspace before resuming a session.' ) } diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts index 5e8bc3f42..381b1d49c 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume.test.ts @@ -194,10 +194,33 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks runtime-owned targets even when they have no SSH connection', () => { + it('allows runtime-owned targets for matching runtime sessions', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', + worktreeInfo: makeWorktreeInfo('active'), + activeWorktreeId: null, + worktrees: [makeWorktree()], + repos: [ + makeRepo({ + connectionId: null, + executionHostId: 'runtime:env-1' + }) + ] + }) + ).toEqual({ + blocked: false, + worktreeId: 'repo-1::/repo/orca', + usesSessionWorktree: true + }) + }) + + it('blocks runtime-owned targets for sessions from another host', () => { + expect( + resolveAiVaultSessionResumeState({ + sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'local', worktreeInfo: makeWorktreeInfo('active'), activeWorktreeId: null, worktrees: [makeWorktree()], @@ -215,19 +238,20 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks runtime-stamped worktrees even when the repo owner is local', () => { + it('allows runtime-stamped worktrees even when the repo owner is local', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('active'), activeWorktreeId: null, worktrees: [makeWorktree({ hostId: 'runtime:env-1' })], repos: [makeRepo({ connectionId: null, executionHostId: 'local' })] }) ).toEqual({ - blocked: true, - worktreeId: null, - usesSessionWorktree: false + blocked: false, + worktreeId: 'repo-1::/repo/orca', + usesSessionWorktree: true }) }) @@ -319,10 +343,11 @@ describe('resolveAiVaultSessionResumeState', () => { }) }) - it('blocks an active runtime folder workspace', () => { + it('allows an active runtime folder workspace for matching runtime sessions', () => { expect( resolveAiVaultSessionResumeState({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('archived'), activeWorktreeId: folderWorkspaceKey('folder-1'), worktrees: [], @@ -330,8 +355,8 @@ describe('resolveAiVaultSessionResumeState', () => { targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) }) ).toEqual({ - blocked: true, - worktreeId: null, + blocked: false, + worktreeId: folderWorkspaceKey('folder-1'), usesSessionWorktree: false }) }) @@ -461,10 +486,11 @@ describe('resolveAiVaultSessionResumeActions', () => { }) }) - it('disables the active folder workspace action when it is runtime-owned', () => { + it('enables the active folder workspace action when it is a matching runtime host', () => { expect( resolveAiVaultSessionResumeActions({ sessionFilePath: HOST_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', worktreeInfo: makeWorktreeInfo('archived'), activeWorktreeId: folderWorkspaceKey('folder-1'), worktrees: [], @@ -473,7 +499,7 @@ describe('resolveAiVaultSessionResumeActions', () => { }) ).toEqual({ worktree: { worktreeId: null, disabled: true }, - newTab: { worktreeId: folderWorkspaceKey('folder-1'), disabled: true } + newTab: { worktreeId: folderWorkspaceKey('folder-1'), disabled: false } }) }) }) @@ -505,10 +531,25 @@ describe('resolveAiVaultSessionLaunchTarget', () => { }) }) - it('blocks direct resume into a runtime folder workspace', () => { + it('allows direct resume into a matching runtime folder workspace', () => { expect( resolveAiVaultSessionLaunchTarget({ sessionFilePath: WSL_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-1', + activeWorktreeId: folderWorkspaceKey('folder-1'), + targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) + }) + ).toEqual({ + status: 'ready', + worktreeId: folderWorkspaceKey('folder-1') + }) + }) + + it('blocks direct resume into a mismatched runtime folder workspace', () => { + expect( + resolveAiVaultSessionLaunchTarget({ + sessionFilePath: WSL_SESSION_FILE, + sessionExecutionHostId: 'runtime:env-2', activeWorktreeId: folderWorkspaceKey('folder-1'), targetState: makeFolderTargetState({ id: 'group-1', executionHostId: 'runtime:env-1' }) }) diff --git a/src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx b/src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx index af09c852c..2ae776502 100644 --- a/src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx +++ b/src/renderer/src/components/tab-group/AiVaultSessionDropLayer.tsx @@ -173,20 +173,11 @@ export default function AiVaultSessionDropLayer({ const state = useAppStore.getState() const targetStatus = getAiVaultResumeWorkspaceTargetStatus(state, worktreeId) const targetExecutionHostId = getAiVaultResumeWorkspaceExecutionHostId(state, worktreeId) - if (targetStatus === 'runtime') { - toast.error( - translate( - 'auto.components.tab.group.AiVaultSessionDropLayer.runtimeWorkspacesUnsupported', - 'Resume from history is not available in runtime-hosted workspaces.' - ) - ) - return true - } if (targetStatus === 'unknown') { toast.error( translate( 'auto.components.tab.group.AiVaultSessionDropLayer.openSupportedWorkspace', - 'Open a local or SSH workspace before resuming a session.' + 'Open a workspace before resuming a session.' ) ) return true @@ -208,7 +199,7 @@ export default function AiVaultSessionDropLayer({ return true } - launchAiVaultSessionInNewTab({ + const launchResult = launchAiVaultSessionInNewTab({ agent: payload.agent, worktreeId, command: payload.command, @@ -217,12 +208,31 @@ export default function AiVaultSessionDropLayer({ targetGroupId: dropTarget.groupId, splitDirection: dropTarget.zone === 'center' ? undefined : dropTarget.zone }) - toast.success( - translate( - 'auto.components.tab.group.AiVaultSessionDropLayer.sessionQueued', - 'Session queued' + const showQueuedToast = (): void => { + toast.success( + translate( + 'auto.components.tab.group.AiVaultSessionDropLayer.sessionQueued', + 'Session queued' + ) ) - ) + } + if (launchResult.tabId === null) { + void launchResult.runtimeLaunch.then((created) => { + if (!created) { + toast.error( + translate( + 'auto.lib.launch.agent.in.new.tab.11cce5cc77', + 'Could not launch {{value0}} in a new terminal.', + { value0: payload.agent } + ) + ) + return + } + showQueuedToast() + }) + return true + } + showQueuedToast() return true }, [clearDragState, target, updateTarget, worktreeId] diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 01637ff30..d0dc2e8de 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Connect to Orca", "mobileScopeRejected": "This QR code grants limited (mobile) access. To use the full web app, open the browser access link from Settings → Runtime Environments → Share this Orca server → New Link." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "Agent Session History is not available for this execution host." + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "Resume from history is only available in local workspaces.", "openLocalWorkspace": "Open a local workspace before resuming a session.", "sessionQueued": "Session queued", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "sessionHostMismatchUnsupported": "This session belongs to a different host. Drop it onto a workspace on the same host.", "localSessionSshWorkspaceUnsupported": "This session's history is stored on this machine, so it can't resume in an SSH workspace. Drop it onto a local workspace instead." }, @@ -9648,9 +9650,7 @@ "logPath": "Log path", "originalPaneUnavailable": "Original pane is no longer available.", "worktreeUnavailable": "Worktree is no longer available.", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "sessionHostMismatchUnsupported": "This session belongs to a different host. Open a workspace on the same host to resume it.", "localSessionSshWorkspaceUnsupported": "This session's history is stored on this machine, so it can't resume in an SSH workspace. Open a local workspace instead." }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index e9af23a0c..8923d561d 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Conectar con Orca", "mobileScopeRejected": "Este código QR solo da acceso limitado para móvil. Para usar la app web completa, abre el enlace para navegador desde Ajustes → Servidores remotos de Orca → Comparte este servidor Orca → Nuevo enlace." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "El historial de sesiones de Agents no está disponible para este host de ejecución." + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "Reanudar desde el historial solo está disponible en espacios de trabajo locales.", "openLocalWorkspace": "Abre un espacio de trabajo local antes de reanudar una sesión.", "sessionQueued": "Sesión en cola", - "runtimeWorkspacesUnsupported": "Reanudar desde el historial no está disponible en espacios de trabajo alojados en un host.", - "openSupportedWorkspace": "Abre un espacio de trabajo local o SSH antes de reanudar una sesión.", + "openSupportedWorkspace": "Abre un espacio de trabajo antes de reanudar una sesión.", "localSessionSshWorkspaceUnsupported": "El historial de esta sesión solo existe en este equipo. Para reanudarla, arrástrala a un workspace local. Los workspaces SSH no tienen acceso a ese historial.", "sessionHostMismatchUnsupported": "Esta sesión pertenece a un host diferente. Suéltala en un espacio de trabajo del mismo host." }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} mostradas", "originalPaneUnavailable": "El panel original ya no está disponible.", "worktreeUnavailable": "El worktree ya no está disponible.", - "runtimeBrowseLocalHistory": "Los workspaces alojados en runtime pueden explorar el historial local. Las acciones de reanudación están disponibles en workspaces locales y SSH.", - "runtimeWorkspacesUnsupported": "Reanudar desde el historial no está disponible en workspaces alojados en runtime.", - "openSupportedWorkspace": "Abre un workspace local o SSH antes de reanudar una sesión.", + "openSupportedWorkspace": "Abre un workspace antes de reanudar una sesión.", "localSessionSshWorkspaceUnsupported": "El historial de esta sesión solo existe en este equipo. Para reanudarla, abre un workspace local. Los workspaces SSH no tienen acceso a ese historial.", "sessionHostMismatchUnsupported": "Esta sesión pertenece a un host diferente. Abre un espacio de trabajo en el mismo host para reanudarla." }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 2aa5e2411..e5bdf3384 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Orca に接続", "mobileScopeRejected": "この QR コードは制限付き(モバイル)アクセスを許可します。完全な Web アプリを使うには、設定 → リモート Orca サーバー → この Orca サーバーを共有する → 新規リンク からブラウザー用アクセスリンクを開いてください。" }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "この実行ホストでは Agent セッション履歴を使用できません。" + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "履歴からの再開はローカルワークスペースでのみ利用できます。", "openLocalWorkspace": "セッションを再開する前にローカルワークスペースを開いてください。", "sessionQueued": "セッションをキューに追加しました", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "このセッションの履歴はこのマシンに保存されているため、SSH ワークスペースでは再開できません。代わりにローカルワークスペースにドロップしてください。", "sessionHostMismatchUnsupported": "このセッションは別のホストに属しています。同じホスト上のワークスペースにドロップしてください。" }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} 件表示", "originalPaneUnavailable": "元のペインは利用できなくなりました。", "worktreeUnavailable": "ワークツリーは利用できなくなりました。", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "このセッションの履歴はこのマシンに保存されているため、SSH ワークスペースでは再開できません。代わりにローカルワークスペースを開いてください。", "sessionHostMismatchUnsupported": "このセッションは別のホストに属しています。再開するには同じホスト上のワークスペースを開いてください。" }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index dcbaadc3e..db8a2aea5 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -137,6 +137,9 @@ "e3bcd082ac": "Orca에 연결", "mobileScopeRejected": "이 QR 코드는 제한된(모바일) 액세스 권한만 제공합니다. 전체 웹 앱을 사용하려면 설정 → 원격 Orca 서버 → 이 Orca 서버 공유 → 새 링크에서 브라우저 액세스 링크를 여세요." }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "이 실행 호스트에서는 Agent 세션 기록을 사용할 수 없습니다." + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "기록에서 재개하기는 로컬 워크스페이스에서만 사용할 수 있습니다.", "openLocalWorkspace": "세션을 재개하기 전에 로컬 워크스페이스를 여세요.", "sessionQueued": "세션이 대기열에 추가됨", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "이 세션의 기록은 이 컴퓨터에 저장되어 있어 SSH 워크스페이스에서는 재개할 수 없습니다. 대신 로컬 워크스페이스에 놓으세요.", "sessionHostMismatchUnsupported": "이 세션은 다른 호스트에 속합니다. 같은 호스트의 워크스페이스에 놓으세요." }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "{{value0}} 표시됨", "originalPaneUnavailable": "원래 창은 더 이상 사용할 수 없습니다.", "worktreeUnavailable": "워크트리는 더 이상 사용할 수 없습니다.", - "runtimeBrowseLocalHistory": "Runtime-hosted workspaces can browse local history. Resume actions are available in local and SSH workspaces.", - "runtimeWorkspacesUnsupported": "Resume from history is not available in runtime-hosted workspaces.", - "openSupportedWorkspace": "Open a local or SSH workspace before resuming a session.", + "openSupportedWorkspace": "Open a workspace before resuming a session.", "localSessionSshWorkspaceUnsupported": "이 세션의 기록은 이 컴퓨터에 저장되어 있어 SSH 워크스페이스에서는 재개할 수 없습니다. 대신 로컬 워크스페이스를 여세요.", "sessionHostMismatchUnsupported": "이 세션은 다른 호스트에 속합니다. 재개하려면 같은 호스트의 워크스페이스를 여세요." }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 968e88e0e..d6cce4de2 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -137,6 +137,9 @@ "e3bcd082ac": "连接到 Orca", "mobileScopeRejected": "此二维码仅授予受限(移动端)访问权限。若要使用完整 Web 应用,请从设置 → 远程 Orca 服务器 → 分享此 Orca 服务器 → 新链接打开浏览器访问链接。" }, + "webPreloadApi": { + "aiVaultUnavailableForHost": "此执行主机不支持 Agent 会话历史记录。" + }, "web": { "preload": { "api": { @@ -2588,8 +2591,7 @@ "localWorkspacesOnly": "从历史恢复仅支持本地工作区。", "openLocalWorkspace": "恢复会话前请先打开一个本地工作区。", "sessionQueued": "会话已排队", - "runtimeWorkspacesUnsupported": "在远程运行时托管的工作区中无法从历史记录恢复会话。", - "openSupportedWorkspace": "在恢复会话之前,请先打开一个本地或 SSH 工作区。", + "openSupportedWorkspace": "在恢复会话之前,请先打开一个工作区。", "localSessionSshWorkspaceUnsupported": "此会话的历史记录存储在本机上,因此无法在 SSH 工作区中恢复。请改为将其拖放到本地工作区。", "sessionHostMismatchUnsupported": "此会话属于其他主机。请将其拖放到同一主机上的工作区。" }, @@ -9648,9 +9650,7 @@ "sessionsShownCompact": "已显示 {{value0}} 个", "originalPaneUnavailable": "原始面板不再可用。", "worktreeUnavailable": "工作树不再可用。", - "runtimeBrowseLocalHistory": "远程运行时托管的工作区可以浏览本地历史。恢复操作在本地和 SSH 工作区中可用。", - "runtimeWorkspacesUnsupported": "在远程运行时托管的工作区中无法从历史记录恢复会话。", - "openSupportedWorkspace": "在恢复会话之前,请先打开一个本地或 SSH 工作区。", + "openSupportedWorkspace": "在恢复会话之前,请先打开一个工作区。", "localSessionSshWorkspaceUnsupported": "此会话的历史记录存储在本机上,因此无法在 SSH 工作区中恢复。请改为打开一个本地工作区。", "sessionHostMismatchUnsupported": "此会话属于其他主机。请打开同一主机上的工作区以恢复它。" }, diff --git a/src/renderer/src/lib/ai-vault-resume-target.test.ts b/src/renderer/src/lib/ai-vault-resume-target.test.ts index 207bc525a..f7903f130 100644 --- a/src/renderer/src/lib/ai-vault-resume-target.test.ts +++ b/src/renderer/src/lib/ai-vault-resume-target.test.ts @@ -114,10 +114,33 @@ describe('ai vault session storage compatibility', () => { ).toBe(true) }) - it('never allows runtime or unknown targets', () => { + it('allows runtime sessions only on the matching runtime target', () => { expect( - canResumeAiVaultSessionOnTarget({ sessionFilePath: wslSessionFile, targetStatus: 'runtime' }) + canResumeAiVaultSessionOnTarget({ + sessionFilePath: '/home/ada/.codex/sessions/remote.jsonl', + sessionExecutionHostId: 'runtime:env-1', + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-1' + }) + ).toBe(true) + expect( + canResumeAiVaultSessionOnTarget({ + sessionFilePath: '/home/ada/.codex/sessions/remote.jsonl', + sessionExecutionHostId: 'runtime:env-1', + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-2' + }) ).toBe(false) + expect( + canResumeAiVaultSessionOnTarget({ + sessionFilePath: wslSessionFile, + targetStatus: 'runtime', + targetExecutionHostId: 'runtime:env-1' + }) + ).toBe(false) + }) + + it('never allows unknown targets', () => { expect( canResumeAiVaultSessionOnTarget({ sessionFilePath: hostSessionFile, targetStatus: 'unknown' }) ).toBe(false) @@ -149,8 +172,11 @@ describe('ai vault resume target ownership', () => { true ) expect( - isUnsupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) + isSupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) ).toBe(true) + expect( + isUnsupportedAiVaultResumeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) + ).toBe(false) }) it('resolves runtime-owned worktree targets through their repo owner', () => { diff --git a/src/renderer/src/lib/ai-vault-resume-target.ts b/src/renderer/src/lib/ai-vault-resume-target.ts index 823840ec8..f52e26c62 100644 --- a/src/renderer/src/lib/ai-vault-resume-target.ts +++ b/src/renderer/src/lib/ai-vault-resume-target.ts @@ -35,7 +35,7 @@ export function isSupportedAiVaultResumeRepo( } export function isSupportedAiVaultResumeTargetStatus(status: AiVaultResumeTargetStatus): boolean { - return status === 'local' || status === 'ssh' + return status === 'local' || status === 'ssh' || status === 'runtime' } export function isWslStoredAiVaultSessionFile(sessionFilePath: string | null | undefined): boolean { @@ -48,11 +48,20 @@ export function canResumeAiVaultSessionOnTarget(args: { targetStatus: AiVaultResumeTargetStatus targetExecutionHostId?: ExecutionHostId | null }): boolean { + const sessionExecutionHostId = normalizeExecutionHostId(args.sessionExecutionHostId) + const targetExecutionHostId = normalizeExecutionHostId(args.targetExecutionHostId) + if (args.targetStatus === 'runtime') { + // Runtime session stores live on one paired server; only queue resumes back + // onto that exact server host. + return Boolean( + sessionExecutionHostId && + targetExecutionHostId && + sessionExecutionHostId === targetExecutionHostId + ) + } if (!isSupportedAiVaultResumeTargetStatus(args.targetStatus)) { return false } - const sessionExecutionHostId = normalizeExecutionHostId(args.sessionExecutionHostId) - const targetExecutionHostId = normalizeExecutionHostId(args.targetExecutionHostId) if (sessionExecutionHostId) { if (targetExecutionHostId) { if (sessionExecutionHostId === targetExecutionHostId) { @@ -84,7 +93,8 @@ export function canResumeAiVaultSessionOnTarget(args: { export function isUnsupportedAiVaultResumeRepo( repo: AiVaultResumeRepoOwner | null | undefined ): boolean { - return getAiVaultResumeRepoTargetStatus(repo) === 'runtime' + const status = getAiVaultResumeRepoTargetStatus(repo) + return status !== 'unknown' && !isSupportedAiVaultResumeTargetStatus(status) } export function getAiVaultResumeWorktreeTargetStatus(args: { diff --git a/src/renderer/src/lib/launch-ai-vault-session.test.ts b/src/renderer/src/lib/launch-ai-vault-session.test.ts index e6a1c083a..ef0425b58 100644 --- a/src/renderer/src/lib/launch-ai-vault-session.test.ts +++ b/src/renderer/src/lib/launch-ai-vault-session.test.ts @@ -5,6 +5,11 @@ const mockCreateEmptySplitGroup = vi.fn() const mockQueueTabStartupCommand = vi.fn() const mockSetActiveTabType = vi.fn() const mockSetTabBarOrder = vi.fn() +const runtimeMocks = vi.hoisted(() => ({ + createWebRuntimeSessionTerminal: vi.fn(), + getRuntimeEnvironmentIdForWorktree: vi.fn<() => string | null>(() => null), + isWebRuntimeSessionActive: vi.fn(() => false) +})) const mockState = { createTab: mockCreateTab, @@ -37,11 +42,23 @@ vi.mock('@/lib/telemetry', () => ({ tuiAgentToAgentKind: (agent: string) => agent })) +vi.mock('@/lib/worktree-runtime-owner', () => ({ + getRuntimeEnvironmentIdForWorktree: runtimeMocks.getRuntimeEnvironmentIdForWorktree +})) + +vi.mock('@/runtime/web-runtime-session', () => ({ + createWebRuntimeSessionTerminal: runtimeMocks.createWebRuntimeSessionTerminal, + isWebRuntimeSessionActive: runtimeMocks.isWebRuntimeSessionActive +})) + import { launchAiVaultSessionInNewTab } from './launch-ai-vault-session' describe('launchAiVaultSessionInNewTab', () => { beforeEach(() => { vi.clearAllMocks() + runtimeMocks.getRuntimeEnvironmentIdForWorktree.mockReturnValue(null) + runtimeMocks.isWebRuntimeSessionActive.mockReturnValue(false) + runtimeMocks.createWebRuntimeSessionTerminal.mockResolvedValue(true) mockState.tabsByWorktree = {} mockState.openFiles = [] mockState.browserTabsByWorktree = {} @@ -118,4 +135,45 @@ describe('launchAiVaultSessionInNewTab', () => { expect(mockCreateEmptySplitGroup).toHaveBeenCalledWith('wt-1', 'group-1', 'right') expect(mockCreateTab).toHaveBeenCalledWith('wt-1', 'group-new') }) + + it('creates runtime-hosted resume terminals through the paired host', async () => { + runtimeMocks.getRuntimeEnvironmentIdForWorktree.mockReturnValue('env-1') + runtimeMocks.isWebRuntimeSessionActive.mockReturnValue(true) + + const result = launchAiVaultSessionInNewTab({ + agent: 'codex', + worktreeId: 'wt-1', + targetGroupId: 'group-1', + command: "codex resume 'session-1'", + env: { CODEX_PROFILE: 'runtime' }, + launchConfig: { + agentCommand: 'codex', + agentArgs: '', + agentEnv: { CODEX_PROFILE: 'runtime' } + } + }) + + expect(result.tabId).toBeNull() + expect(runtimeMocks.createWebRuntimeSessionTerminal).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + environmentId: 'env-1', + targetGroupId: 'group-1', + command: "codex resume 'session-1'", + env: { CODEX_PROFILE: 'runtime' }, + launchConfig: { + agentCommand: 'codex', + agentArgs: '', + agentEnv: { CODEX_PROFILE: 'runtime' } + }, + launchAgent: 'codex', + activate: true + }) + expect(mockCreateTab).not.toHaveBeenCalled() + expect(mockQueueTabStartupCommand).not.toHaveBeenCalled() + + if (result.tabId === null) { + await expect(result.runtimeLaunch).resolves.toBe(true) + } + expect(mockSetActiveTabType).toHaveBeenCalledWith('terminal') + }) }) diff --git a/src/renderer/src/lib/launch-ai-vault-session.ts b/src/renderer/src/lib/launch-ai-vault-session.ts index a22f00271..e04e35345 100644 --- a/src/renderer/src/lib/launch-ai-vault-session.ts +++ b/src/renderer/src/lib/launch-ai-vault-session.ts @@ -1,10 +1,19 @@ import { useAppStore } from '@/store' import { reconcileTabOrder } from '@/components/tab-bar/reconcile-order' import { tuiAgentToAgentKind } from '@/lib/telemetry' +import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + createWebRuntimeSessionTerminal, + isWebRuntimeSessionActive +} from '@/runtime/web-runtime-session' import type { AiVaultAgent } from '../../../shared/ai-vault-types' import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session-resume' import type { TabSplitDirection } from '@/store/slices/tabs' +export type LaunchAiVaultSessionInNewTabResult = + | { tabId: string; groupId?: string } + | { tabId: null; groupId?: string; runtimeLaunch: Promise } + export function launchAiVaultSessionInNewTab(args: { agent: AiVaultAgent worktreeId: string @@ -13,9 +22,33 @@ export function launchAiVaultSessionInNewTab(args: { launchConfig?: SleepingAgentLaunchConfig targetGroupId?: string splitDirection?: TabSplitDirection -}): { tabId: string; groupId?: string } { +}): LaunchAiVaultSessionInNewTabResult { const store = useAppStore.getState() let targetGroupId = args.targetGroupId + const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(store, args.worktreeId) + if (isWebRuntimeSessionActive(runtimeEnvironmentId)) { + const runtimeLaunch = createWebRuntimeSessionTerminal({ + worktreeId: args.worktreeId, + environmentId: runtimeEnvironmentId, + ...(targetGroupId ? { targetGroupId } : {}), + command: args.command, + ...(args.env ? { env: args.env } : {}), + ...(args.launchConfig ? { launchConfig: args.launchConfig } : {}), + launchAgent: args.agent, + activate: true + }).then((created) => { + if (created) { + useAppStore.getState().setActiveTabType('terminal') + } + return created + }) + return { + tabId: null, + ...(targetGroupId ? { groupId: targetGroupId } : {}), + runtimeLaunch + } + } + if (args.splitDirection && targetGroupId) { targetGroupId = store.createEmptySplitGroup(args.worktreeId, targetGroupId, args.splitDirection) ?? diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index 4a1d7b36f..bf46bd403 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -592,6 +592,104 @@ describe('web MiniMax preload API', () => { }) }) +describe('web AI Vault preload API', () => { + beforeEach(() => { + vi.resetModules() + }) + + afterEach(() => { + vi.unstubAllGlobals() + vi.doUnmock('./web-runtime-client') + }) + + it('routes session scans through the paired runtime host', async () => { + const runtimeCalls: { method: string; params: unknown }[] = [] + const scanResult = { + sessions: [], + issues: [], + scannedAt: '2026-07-04T00:00:00.000Z' + } + vi.doMock('./web-runtime-client', () => ({ + WebRuntimeClient: class { + call(method: string, params?: unknown): Promise> { + runtimeCalls.push({ method, params }) + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: scanResult, + _meta: { runtimeId: 'runtime-1' } + }) + } + + close(): void {} + } + })) + + const globals = installBrowserGlobals('Linux') + writeStoredRuntimeEnvironment(globals.storage) + const { installWebPreloadApi } = await import('./web-preload-api') + installWebPreloadApi() + + await expect( + globals.window.api.aiVault.listSessions({ + executionHostScope: 'all', + limit: 25, + force: true, + scopePaths: ['/srv/app'] + }) + ).resolves.toEqual(scanResult) + expect(runtimeCalls).toEqual([ + { + method: 'aiVault.listSessions', + params: { + limit: 25, + force: true, + scopePaths: ['/srv/app'], + executionHostId: 'runtime:web-env-1' + } + } + ]) + }) + + it('returns unavailable history for explicit non-runtime host scopes', async () => { + const runtimeCalls: { method: string; params: unknown }[] = [] + vi.doMock('./web-runtime-client', () => ({ + WebRuntimeClient: class { + call(method: string, params?: unknown): Promise> { + runtimeCalls.push({ method, params }) + return Promise.resolve({ + id: `call-${runtimeCalls.length}`, + ok: true, + result: { sessions: [], issues: [], scannedAt: '2026-07-04T00:00:00.000Z' }, + _meta: { runtimeId: 'runtime-1' } + }) + } + + close(): void {} + } + })) + + const globals = installBrowserGlobals('Linux') + writeStoredRuntimeEnvironment(globals.storage) + const { installWebPreloadApi } = await import('./web-preload-api') + installWebPreloadApi() + + await expect( + globals.window.api.aiVault.listSessions({ executionHostScope: 'local' }) + ).resolves.toEqual({ + sessions: [], + issues: [ + expect.objectContaining({ + executionHostId: 'local', + agent: 'codex' + }) + ], + scannedAt: expect.any(String) + }) + expect(runtimeCalls).toEqual([]) + }) +}) + describe('web UI preload API', () => { beforeEach(() => { vi.resetModules() diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 30b97677b..7696f454f 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -10,6 +10,7 @@ import type { NativeChatAppendedMessages } from '../../../preload/api-types' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' +import type { AiVaultListArgs, AiVaultListResult } from '../../../shared/ai-vault-types' import { buildNativeChatUnsubscribe } from '../../../shared/native-chat-stream-unsubscribe' import type { ComputerUsePermissionSetupResult, @@ -47,7 +48,13 @@ import { import { legacyBaseRefSearchResult } from '../../../shared/base-ref-search-result' import { createE2EConfig } from '../../../shared/e2e-config' import { relativePathInsideRoot } from '../../../shared/cross-platform-path' -import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostId } from '../../../shared/execution-host' +import { + LOCAL_EXECUTION_HOST_ID, + normalizeExecutionHostScope, + normalizeExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' import { toRuntimeWorktreeSelector } from '../runtime/runtime-worktree-selector' import { normalizeDisabledTuiAgents } from '../../../shared/tui-agent-selection' import { @@ -626,15 +633,7 @@ function createWebPreloadApi(): Partial { memory: { getSnapshot: () => Promise.resolve(createEmptyMemorySnapshot()) }, - aiVault: { - listSessions: () => - Promise.resolve({ - sessions: [], - issues: [], - scannedAt: new Date().toISOString() - }), - onWindowFocused: () => () => {} - }, + aiVault: createAiVaultApi(), preflight: createPreflightApi(), notifications: createNotificationsApi(), rateLimits: createRateLimitsApi(), @@ -1116,6 +1115,48 @@ function createRuntimeEnvironmentsApi(): NonNullable['runtim } } +function createAiVaultApi(): NonNullable['aiVault']> { + return { + listSessions: (args?: AiVaultListArgs) => { + const environment = requireActiveEnvironment() + const executionHostId = toRuntimeExecutionHostId(environment.id) + const requestedScope = normalizeExecutionHostScope( + args?.executionHostScope ?? executionHostId + ) + if (requestedScope !== 'all' && requestedScope !== executionHostId) { + return Promise.resolve(webAiVaultUnavailableResult(requestedScope)) + } + // Why: the browser client has no local filesystem; every history scan + // runs on the paired server and must be stamped as that runtime host. + return callRuntimeResult('aiVault.listSessions', { + limit: args?.limit, + force: args?.force, + scopePaths: args?.scopePaths, + executionHostId + }) + }, + onWindowFocused: () => noopUnsubscribe + } +} + +function webAiVaultUnavailableResult(executionHostId: ExecutionHostId): AiVaultListResult { + return { + sessions: [], + issues: [ + { + executionHostId, + agent: 'codex', + path: executionHostId, + message: translate( + 'auto.web.webPreloadApi.aiVaultUnavailableForHost', + 'Agent Session History is not available for this execution host.' + ) + } + ], + scannedAt: new Date().toISOString() + } +} + function createReposApi(): NonNullable['repos']> { return { list: async () => (await callRuntimeResult<{ repos: Repo[] }>('repo.list')).repos,