From ef49c858c56b50892f9f95c0a19221c3f53a66ed Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 11 Nov 2026 11:57:52 -0800 Subject: [PATCH 1/2] feat(cloud): N-01 per-create phase timing in app.log Each Orca Cloud create logs `[orca-cloud] create +` (ms since its provision started) to the main app log, so a slow create shows which phase took the time. The provision's own `[orca-cloud] ` progress lines are unchanged. Also folds the two identical post-start cleanup-and-fail blocks in the provision handler into one helper (ephemeral-vm.ts was at the 300-line cap). --- .../ipc/cloud-create-phase-timing.test.ts | 44 +++++++++++++ src/main/ipc/cloud-create-phase-timing.ts | 63 +++++++++++++++++++ src/main/ipc/ephemeral-vm.ts | 50 ++++++++------- src/preload/api/ephemeral-vm-api.ts | 3 + src/preload/api/ephemeral-vm-bridge.ts | 1 + .../src/lib/ephemeral-vm-worktree-creation.ts | 12 ++++ .../creation/worktree-creation-completion.ts | 4 ++ src/shared/orca-cloud/cloud-create-phases.ts | 50 +++++++++++++++ 8 files changed, 203 insertions(+), 24 deletions(-) create mode 100644 src/main/ipc/cloud-create-phase-timing.test.ts create mode 100644 src/main/ipc/cloud-create-phase-timing.ts create mode 100644 src/shared/orca-cloud/cloud-create-phases.ts diff --git a/src/main/ipc/cloud-create-phase-timing.test.ts b/src/main/ipc/cloud-create-phase-timing.test.ts new file mode 100644 index 00000000000..d1caab820f3 --- /dev/null +++ b/src/main/ipc/cloud-create-phase-timing.test.ts @@ -0,0 +1,44 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), removeHandler: vi.fn() } })) + +const { noteCloudCreatePhase, noteCloudCreateProvisionChunk, resetCloudCreatePhaseTimingForTest } = + await import('./cloud-create-phase-timing') + +describe('cloud create phase timing (N-01)', () => { + afterEach(() => { + resetCloudCreatePhaseTimingForTest() + vi.restoreAllMocks() + }) + + it('logs each phase with ms since the provision started, under a stable prefix', () => { + const lines: string[] = [] + const log = (line: string): void => void lines.push(line) + noteCloudCreatePhase('c1', 'provision-start', { now: 1000, log }) + noteCloudCreatePhase('c1', 'connecting', { now: 4200, log }) + noteCloudCreatePhase('c1', 'workspace-open', { now: 9000, log }) + expect(lines).toEqual([ + '[orca-cloud] create c1 provision-start +0', + '[orca-cloud] create c1 connecting +3200', + '[orca-cloud] create c1 workspace-open +8000' + ]) + }) + + it('stamps the driver progress lines in a provision chunk and ignores everything else', () => { + const info = vi.spyOn(console, 'info').mockImplementation(() => undefined) + noteCloudCreatePhase('c2', 'provision-start') + noteCloudCreateProvisionChunk( + 'c2', + '[orca-cloud] provisioning\nsome other line\n[orca-cloud] cloning octocat/Hello-World\n[orca-cloud] connecting\n' + ) + const phases = info.mock.calls.map(([line]) => String(line).split(' ')[3]) + expect(phases).toEqual(['provision-start', 'provisioning', 'cloning', 'connecting']) + }) + + it('never logs an id that could carry anything but an id', () => { + const lines: string[] = [] + noteCloudCreatePhase('bad id; token=abc', 'provision-start', { log: (l) => void lines.push(l) }) + noteCloudCreatePhase(undefined, 'provision-start', { log: (l) => void lines.push(l) }) + expect(lines).toEqual([]) + }) +}) diff --git a/src/main/ipc/cloud-create-phase-timing.ts b/src/main/ipc/cloud-create-phase-timing.ts new file mode 100644 index 00000000000..e0c8c225596 --- /dev/null +++ b/src/main/ipc/cloud-create-phase-timing.ts @@ -0,0 +1,63 @@ +// N-01: per-create phase timing in the main app log, so a slow "Start sandbox" can be localised from +// app.log alone: `[orca-cloud] create +`. Ids and phase names only, never +// tokens, URLs or pairing codes. +import { ipcMain } from 'electron' +import { + cloudCreatePhaseFromProvisionLine, + isCloudCreateRendererPhase, + type CloudCreatePhase +} from '../../shared/orca-cloud/cloud-create-phases' + +const startedAt = new Map() +// A create that never reports its end must not keep its entry forever. +const MAX_TRACKED_CREATES = 64 + +export function noteCloudCreatePhase( + creationId: string | undefined, + phase: CloudCreatePhase, + options: { now?: number; log?: (line: string) => void } = {} +): void { + if (!creationId || !/^[A-Za-z0-9_-]{1,80}$/.test(creationId)) { + return + } + const now = options.now ?? Date.now() + if (phase === 'provision-start' || !startedAt.has(creationId)) { + startedAt.set(creationId, now) + if (startedAt.size > MAX_TRACKED_CREATES) { + startedAt.delete(startedAt.keys().next().value as string) + } + } + const since = now - (startedAt.get(creationId) ?? now) + ;(options.log ?? console.info)(`[orca-cloud] create ${creationId} ${phase} +${since}`) + if (phase === 'workspace-open' || phase === 'failed') { + startedAt.delete(creationId) + } +} + +/** Notes every driver progress line in a provision event chunk. */ +export function noteCloudCreateProvisionChunk(creationId: string | undefined, chunk: string): void { + for (const line of chunk.split('\n')) { + const phase = cloudCreatePhaseFromProvisionLine(line) + if (phase) { + noteCloudCreatePhase(creationId, phase) + } + } +} + +/** The renderer's phases after the provision returns; anything else is ignored. */ +export function registerCloudCreatePhaseNotes(): void { + // Why: a handle (not on) so re-registering replaces the listener instead of doubling every line. + ipcMain.removeHandler('ephemeralVm:notePhase') + ipcMain.handle( + 'ephemeralVm:notePhase', + (_event, args: { provisionId?: unknown; phase?: unknown }): void => { + if (typeof args?.provisionId === 'string' && isCloudCreateRendererPhase(args.phase)) { + noteCloudCreatePhase(args.provisionId, args.phase) + } + } + ) +} + +export function resetCloudCreatePhaseTimingForTest(): void { + startedAt.clear() +} diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 5f831e464e4..4cf740cd9ae 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -1,4 +1,9 @@ import { app, ipcMain } from 'electron' +import { + noteCloudCreatePhase, + noteCloudCreateProvisionChunk, + registerCloudCreatePhaseNotes +} from './cloud-create-phase-timing' import type { Store } from '../persistence/loading-store/store' import { getEphemeralVmRecipeResultConnection, @@ -85,6 +90,7 @@ export type EphemeralVmProvisionIpcResult = } & EphemeralVmFailure) export function registerEphemeralVmHandlers(store: Store, pluginService?: PluginService): void { + registerCloudCreatePhaseNotes() installHostedSandbox(store) ipcMain.removeHandler('ephemeralVm:listRecipes') ipcMain.removeHandler('ephemeralVm:listRecipeCatalog') @@ -146,6 +152,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin if (refused) { return provisionFailure(refused) } + noteCloudCreatePhase(args.provisionId, 'provision-start') const controller = args.provisionId ? new AbortController() : null if (args.provisionId && controller) { activeProvisionControllers.set(args.provisionId, controller) @@ -154,6 +161,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin if (!args.provisionId) { return } + noteCloudCreateProvisionChunk(args.provisionId, chunk) _event.sender.send('ephemeralVm:provisionEvent', { provisionId: args.provisionId, stream, @@ -213,6 +221,21 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) } } + // Why: a started runtime that fails to connect or pair is cleaned up, not leaked. + const failAfterStart = async (error: unknown): Promise => { + await cleanupEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + recipe, + runtimeId: result.runtime.id + }).catch(() => undefined) + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } const connection = getEphemeralVmRecipeResultConnection(result.start.result) if (connection.type === 'ssh') { try { @@ -237,18 +260,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin warnings: getEphemeralVmRecipeResultWarnings(result.start.result) } } catch (error) { - await cleanupEphemeralVmRuntime({ - userDataPath: app.getPath('userData'), - repoPath: repo.repo.path, - recipe, - runtimeId: result.runtime.id - }).catch(() => undefined) - return { - ok: false, - error: error instanceof Error ? error.message : String(error), - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } + return failAfterStart(error) } } @@ -260,24 +272,14 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin source: 'ephemeral-vm' }) } catch (error) { - await cleanupEphemeralVmRuntime({ - userDataPath: app.getPath('userData'), - repoPath: repo.repo.path, - recipe, - runtimeId: result.runtime.id - }).catch(() => undefined) - return { - ok: false, - error: error instanceof Error ? error.message : String(error), - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } + return failAfterStart(error) } const runtime = requireEphemeralVmRecipeResult( updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { runtimeEnvironmentId: environment.id }) ) + noteCloudCreatePhase(args.provisionId, 'provision-end') return { ok: true, connectionType: 'orca-server', diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index e212d012f1e..c188ff50467 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -1,3 +1,4 @@ +import type { CloudCreateRendererPhase } from '../../shared/orca-cloud/cloud-create-phases' import type { OrcaCloudAvailability, OrcaHooks } from '../../shared/orca-yaml-hook-types' import type { HostedSessionIdleSleepEvent, @@ -83,6 +84,8 @@ export type EphemeralVmApi = { | ({ ok: false; stderr: string; stdout: string } & EphemeralVmFailure) > cancelProvision: (args: { provisionId: string }) => Promise<{ cancelled: boolean }> + /** N-01: the renderer's create phases after the provision, logged by main with the create's timing. */ + notePhase?: (args: { provisionId: string; phase: CloudCreateRendererPhase }) => void onProvisionEvent: ( callback: (event: { provisionId: string; stream: 'stdout' | 'stderr'; chunk: string }) => void ) => () => void diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index cf4e82a6289..73ea2fb2aa6 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -18,6 +18,7 @@ export const ephemeralVmApi = { doctor: (args) => ipcRenderer.invoke('ephemeralVm:doctor', args), provision: (args) => ipcRenderer.invoke('ephemeralVm:provision', args), cancelProvision: (args) => ipcRenderer.invoke('ephemeralVm:cancelProvision', args), + notePhase: (args) => void ipcRenderer.invoke('ephemeralVm:notePhase', args).catch(() => {}), onProvisionEvent: (callback) => { const listener = ( _event: Electron.IpcRendererEvent, diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 28e2ddffefa..fb39163f14a 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -1,4 +1,5 @@ import { toast } from 'sonner' +import type { CloudCreateRendererPhase } from '../../../shared/orca-cloud/cloud-create-phases' import { useAppStore } from '@/store' import { prepareEphemeralVmWorkspaceTarget } from '@/lib/ephemeral-vm-workspace-target' import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' @@ -95,6 +96,7 @@ async function prepareEphemeralVmRecipeRequest( unsubscribeProvisionEvents?.() } if (!preparedTarget.ok) { + notePhase(creationId, 'failed') if (!useAppStore.getState().pendingWorktreeCreations[creationId]) { return null } @@ -124,11 +126,13 @@ async function prepareEphemeralVmRecipeRequest( .getState() .updatePendingWorktreeCreation(creationId, { vmEnvironmentId: preparedTarget.environmentId }) // Why: the VM's first connect may have just deployed this server; host badges and removal read it. + notePhase(creationId, 'runtime-catalog-start') try { useAppStore.getState().setRuntimeEnvironments(await window.api.runtimeEnvironments.list()) } catch { // A stale catalog only delays host badges; removal re-reads it. } + notePhase(creationId, 'runtime-catalog-end') } const preparedRequest: WorktreeCreationRequest = { ...request, @@ -153,6 +157,7 @@ async function prepareEphemeralVmRecipeRequest( path: preparedTarget.setup.repo.path } } + notePhase(creationId, 'env-check-start') const gate = !useAppStore.getState().pendingWorktreeCreations[creationId] ? 'stop' : !preparedTarget.environmentId @@ -174,6 +179,7 @@ async function prepareEphemeralVmRecipeRequest( } : undefined ) + notePhase(creationId, gate === 'proceed' ? 'env-check-end' : 'failed') if (gate !== 'proceed') { await cleanupEphemeralVmRuntimeForFailedCreate(preparedRequest, creationId) if (gate === 'restart' && useAppStore.getState().pendingWorktreeCreations[creationId]) { @@ -188,6 +194,7 @@ async function prepareEphemeralVmRecipeRequest( phase: 'fetching', request: preparedRequest }) + notePhase(creationId, 'workspace-create-start') return preparedRequest } @@ -279,3 +286,8 @@ function cloudCreateIdempotency(recipeId: string, creationId: string): { idempot const key = cloudCreateIdempotencyKey(creationId) return key ? { idempotencyKey: key } : {} } + +/** N-01: reports a create phase to main's app log (no-op in the web client). */ +function notePhase(creationId: string, phase: CloudCreateRendererPhase): void { + window.api.ephemeralVm.notePhase?.({ provisionId: creationId, phase }) +} diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts index 4fb4bf1f71f..99d7e48e871 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-completion.ts @@ -36,6 +36,10 @@ export async function completeWorktreeCreation(args: { } // Why: clearing synchronously after activation lets React commit the panel-to-terminal swap in one frame. useAppStore.getState().removePendingWorktreeCreation(args.creationId, { cleanupVm: false }) + if (request.ephemeralVmRecipe?.provider === 'orca-cloud') { + // N-01: the create's last phase in main's app log. + window.api.ephemeralVm?.notePhase?.({ provisionId: args.creationId, phase: 'workspace-open' }) + } // Why: an agent the host planned but did not start has no tab to seed and is not the window's to start. const hostAgentMissing = args.hostPlannedStartup && !args.backendSpawned if (!args.structuredLaunchAccepted && !hostAgentMissing) { diff --git a/src/shared/orca-cloud/cloud-create-phases.ts b/src/shared/orca-cloud/cloud-create-phases.ts new file mode 100644 index 00000000000..010e71a888c --- /dev/null +++ b/src/shared/orca-cloud/cloud-create-phases.ts @@ -0,0 +1,50 @@ +// N-01: stable names for the phases of an Orca Cloud workspace create, logged to the main app log as +// `[orca-cloud] create +` (ms since the create's provision started). Keep the +// names stable: log readers grep for them. The provision's own `[orca-cloud] ` progress lines, +// which the create's progress text reads, are separate and unchanged. + +/** Phases main sees: the provision call itself, the driver's progress lines, and its return. */ +export const CLOUD_CREATE_MAIN_PHASES = [ + 'provision-start', + 'provisioning', + 'plan-clone', + 'plan-update', + 'cloning', + 'updating', + 'connecting', + 'provision-end' +] as const + +/** Phases the renderer reports after the provision returns, up to the workspace opening. */ +export const CLOUD_CREATE_RENDERER_PHASES = [ + 'runtime-catalog-start', + 'runtime-catalog-end', + 'env-check-start', + 'env-check-end', + 'workspace-create-start', + 'workspace-open', + 'failed' +] as const + +export type CloudCreateMainPhase = (typeof CLOUD_CREATE_MAIN_PHASES)[number] +export type CloudCreateRendererPhase = (typeof CLOUD_CREATE_RENDERER_PHASES)[number] +export type CloudCreatePhase = CloudCreateMainPhase | CloudCreateRendererPhase + +export function isCloudCreateRendererPhase(value: unknown): value is CloudCreateRendererPhase { + return (CLOUD_CREATE_RENDERER_PHASES as readonly unknown[]).includes(value) +} + +const PROVISION_LINE_PHASES = new Set([ + 'provisioning', + 'plan-clone', + 'plan-update', + 'cloning', + 'updating', + 'connecting' +]) + +/** The phase a driver progress line names (`[orca-cloud] …`), or null for any other line. */ +export function cloudCreatePhaseFromProvisionLine(line: string): CloudCreateMainPhase | null { + const match = /^\[orca-cloud\] ([a-z-]+)/.exec(line.trim()) + return match && PROVISION_LINE_PHASES.has(match[1]) ? (match[1] as CloudCreateMainPhase) : null +} From d4cd4dd2cb8564803e09f0e6d6e4763acb0537a9 Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 11 Nov 2026 13:01:34 -0800 Subject: [PATCH 2/2] fix(cloud): N-01 lint: no as-casts in phase guards, return await in failAfterStart --- src/main/ipc/cloud-create-phase-timing.ts | 5 ++++- src/main/ipc/ephemeral-vm.ts | 4 ++-- src/shared/orca-cloud/cloud-create-phases.ts | 11 +++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/ipc/cloud-create-phase-timing.ts b/src/main/ipc/cloud-create-phase-timing.ts index e0c8c225596..36af733c04c 100644 --- a/src/main/ipc/cloud-create-phase-timing.ts +++ b/src/main/ipc/cloud-create-phase-timing.ts @@ -24,7 +24,10 @@ export function noteCloudCreatePhase( if (phase === 'provision-start' || !startedAt.has(creationId)) { startedAt.set(creationId, now) if (startedAt.size > MAX_TRACKED_CREATES) { - startedAt.delete(startedAt.keys().next().value as string) + const oldest = startedAt.keys().next() + if (!oldest.done) { + startedAt.delete(oldest.value) + } } } const since = now - (startedAt.get(creationId) ?? now) diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 4cf740cd9ae..e29e15fdfb3 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -260,7 +260,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin warnings: getEphemeralVmRecipeResultWarnings(result.start.result) } } catch (error) { - return failAfterStart(error) + return await failAfterStart(error) } } @@ -272,7 +272,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin source: 'ephemeral-vm' }) } catch (error) { - return failAfterStart(error) + return await failAfterStart(error) } const runtime = requireEphemeralVmRecipeResult( updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { diff --git a/src/shared/orca-cloud/cloud-create-phases.ts b/src/shared/orca-cloud/cloud-create-phases.ts index 010e71a888c..3ad62f813a5 100644 --- a/src/shared/orca-cloud/cloud-create-phases.ts +++ b/src/shared/orca-cloud/cloud-create-phases.ts @@ -30,21 +30,24 @@ export type CloudCreateMainPhase = (typeof CLOUD_CREATE_MAIN_PHASES)[number] export type CloudCreateRendererPhase = (typeof CLOUD_CREATE_RENDERER_PHASES)[number] export type CloudCreatePhase = CloudCreateMainPhase | CloudCreateRendererPhase +const RENDERER_PHASES: ReadonlySet = new Set(CLOUD_CREATE_RENDERER_PHASES) + export function isCloudCreateRendererPhase(value: unknown): value is CloudCreateRendererPhase { - return (CLOUD_CREATE_RENDERER_PHASES as readonly unknown[]).includes(value) + return typeof value === 'string' && RENDERER_PHASES.has(value) } -const PROVISION_LINE_PHASES = new Set([ +const PROVISION_LINE_PHASES = [ 'provisioning', 'plan-clone', 'plan-update', 'cloning', 'updating', 'connecting' -]) +] as const satisfies readonly CloudCreateMainPhase[] /** The phase a driver progress line names (`[orca-cloud] …`), or null for any other line. */ export function cloudCreatePhaseFromProvisionLine(line: string): CloudCreateMainPhase | null { const match = /^\[orca-cloud\] ([a-z-]+)/.exec(line.trim()) - return match && PROVISION_LINE_PHASES.has(match[1]) ? (match[1] as CloudCreateMainPhase) : null + const named = match?.[1] + return PROVISION_LINE_PHASES.find((phase) => phase === named) ?? null }