diff --git a/src/main/ephemeral-vm/quiet-wakes.test.ts b/src/main/ephemeral-vm/quiet-wakes.test.ts index 2e610658d1a..cdf7afa1a72 100644 --- a/src/main/ephemeral-vm/quiet-wakes.test.ts +++ b/src/main/ephemeral-vm/quiet-wakes.test.ts @@ -5,7 +5,9 @@ import { endQuietWake, isQuietWake, markQuietWake, + noteQuietWakeResumed, noteQuietWakeWoke, + takeQuietWakeResumed, unopenedIdleStopMs } from './quiet-wakes' @@ -28,4 +30,16 @@ describe('quiet wakes', () => { noteQuietWakeWoke('ws2') expect(unopenedIdleStopMs('ws2')).toBeNull() }) + + it('records whether a quiet wake actually resumed the VM, once', () => { + markQuietWake('ws3') + expect(takeQuietWakeResumed('ws3')).toBe(false) + noteQuietWakeResumed('ws3') + expect(takeQuietWakeResumed('ws3')).toBe(true) + expect(takeQuietWakeResumed('ws3')).toBe(false) + endQuietWake('ws3') + // An ordinary (not quiet) wake's resume is not recorded. + noteQuietWakeResumed('ws4') + expect(takeQuietWakeResumed('ws4')).toBe(false) + }) }) diff --git a/src/main/ephemeral-vm/quiet-wakes.ts b/src/main/ephemeral-vm/quiet-wakes.ts index f2dee98978e..973a1facb82 100644 --- a/src/main/ephemeral-vm/quiet-wakes.ts +++ b/src/main/ephemeral-vm/quiet-wakes.ts @@ -5,12 +5,27 @@ // sleep. Opening the workspace (any wake without `quiet`) claims it back to the normal window. const quiet = new Set() const unopened = new Set() +// Quiet wakes whose VM actually resumed (not one that was already up, which wakes nothing). +const resumed = new Set() /** Idle window for a VM woken on intent and not opened. */ export const UNOPENED_IDLE_STOP_MS = 3 * 60_000 export function markQuietWake(workspaceId: string): void { quiet.add(workspaceId) + resumed.delete(workspaceId) +} + +/** The wake path ran the VM's resume; only then did a quiet wake wake anything. */ +export function noteQuietWakeResumed(workspaceId: string): void { + if (quiet.has(workspaceId)) { + resumed.add(workspaceId) + } +} + +/** Whether this quiet wake resumed the VM; consumes the answer. */ +export function takeQuietWakeResumed(workspaceId: string): boolean { + return resumed.delete(workspaceId) } /** The quiet wake woke the VM; it stays on the short idle window until claimed. */ @@ -22,6 +37,7 @@ export function noteQuietWakeWoke(workspaceId: string): void { export function claimQuietWake(workspaceId: string): void { quiet.delete(workspaceId) + resumed.delete(workspaceId) unopened.delete(workspaceId) } diff --git a/src/main/ephemeral-vm/workspace-resume-slept-elsewhere.test.ts b/src/main/ephemeral-vm/workspace-resume-slept-elsewhere.test.ts new file mode 100644 index 00000000000..eda0e2ad74f --- /dev/null +++ b/src/main/ephemeral-vm/workspace-resume-slept-elsewhere.test.ts @@ -0,0 +1,83 @@ +// A cloud VM slept from the CLI, the phone or another window still reads as running here until +// Orca loses contact with it. A wake (an open or a predictive wake) must resume it now instead of +// returning the stale record, and only a resume that ran counts as a quiet wake that woke it. +import { afterEach, describe, expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ + record: {} as Record, + asleep: false +})) +const mocks = vi.hoisted(() => ({ + resume: vi.fn(async () => ({ + ok: true, + skipped: false, + runtime: { id: 'vm-1', status: 'running' } + })), + markSlept: vi.fn((_path: string, seen: Record) => ({ + ...seen, + status: 'suspended' + })), + updateStatus: vi.fn((_userDataPath: string, _id: string, patch: Record) => patch) +})) + +vi.mock('electron', () => ({ app: { getPath: () => '/user-data' } })) +vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ + updateEphemeralVmRuntimeStatus: mocks.updateStatus +})) +vi.mock('../../shared/ephemeral-vm-workspace-runtime', () => ({ + findWorkspaceEphemeralVmRuntime: () => state.record +})) +vi.mock('../hosted-sandbox/hosted-remote-sleep', () => ({ + isCloudWorkspaceAsleepOnControlPlane: async () => state.asleep, + markCloudRuntimeSleptElsewhere: mocks.markSlept +})) +vi.mock('../ipc/ephemeral-vm-recipe-context', () => ({ + getRuntimeRecipeContext: () => ({ repoPath: '/repo', recipe: { resume: 'orca-cloud resume' } }) +})) +vi.mock('./runtime-service', () => ({ resumeEphemeralVmRuntime: mocks.resume })) + +import type { Store } from '../persistence/loading-store/store' +import { resumeEphemeralVmWorkspace } from './workspace-resume' +import { endQuietWake, markQuietWake, takeQuietWakeResumed } from './quiet-wakes' + +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recipe context reader is mocked, so the resume never reads this store. +const STORE = {} as Store +const REQUEST = { sshHeld: false, sshUserDisconnects: 0 } +const CLOUD_RUNNING = { id: 'vm-1', status: 'running', recipe: { provider: 'orca-cloud' } } + +describe('waking a cloud VM another client put to sleep', () => { + afterEach(() => { + state.asleep = false + mocks.resume.mockClear() + mocks.markSlept.mockClear() + endQuietWake('ws') + takeQuietWakeResumed('ws') + }) + + it('marks the stale running record asleep and resumes the VM', async () => { + state.record = { ...CLOUD_RUNNING } + state.asleep = true + markQuietWake('ws') + await resumeEphemeralVmWorkspace(STORE, 'ws', REQUEST) + expect(mocks.markSlept).toHaveBeenCalledWith('/user-data', state.record) + expect(mocks.resume).toHaveBeenCalledTimes(1) + expect(takeQuietWakeResumed('ws')).toBe(true) + }) + + it('leaves a VM the control plane says is up alone, and a quiet wake of it woke nothing', async () => { + state.record = { ...CLOUD_RUNNING } + markQuietWake('ws') + expect(await resumeEphemeralVmWorkspace(STORE, 'ws', REQUEST)).toBe(state.record) + expect(mocks.markSlept).not.toHaveBeenCalled() + expect(mocks.resume).not.toHaveBeenCalled() + expect(takeQuietWakeResumed('ws')).toBe(false) + }) + + it('never asks about a record that is not a running cloud VM', async () => { + state.record = { ...CLOUD_RUNNING, recipe: { provider: 'other' } } + state.asleep = true + await resumeEphemeralVmWorkspace(STORE, 'ws', REQUEST) + expect(mocks.markSlept).not.toHaveBeenCalled() + expect(mocks.resume).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ephemeral-vm/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index f81e5ed6e7d..c9fb730dd14 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -17,11 +17,15 @@ import { import { resumeEphemeralVmRuntime } from './runtime-service' import { syncHostedSessions } from '../hosted-sandbox/hosted-session-sync' import { isCloudWorkspaceArchivedOnControlPlane } from '../hosted-sandbox/hosted-workspace-runtime' +import { + isCloudWorkspaceAsleepOnControlPlane, + markCloudRuntimeSleptElsewhere +} from '../hosted-sandbox/hosted-remote-sleep' import { CLOUD_WORKSPACE_ARCHIVED_ERROR } from '../../shared/hosted-sandbox/cloud-workspace-api' import { connectRuntimeOwnedSshTarget, refreshRuntimeOwnedSshTarget } from './runtime-ssh' import { noteRecipeVmWakePairing } from './recipe-vm-wake-pairings' import { applyResumedRuntimePairing, probeSavedPairing } from './runtime-resume-pairing' -import { isQuietWake } from './quiet-wakes' +import { isQuietWake, noteQuietWakeResumed } from './quiet-wakes' import { getRecipeVmWaker } from '../runtime/workspaces/sleep/recipe-vm-waker-registry' import { preconnectWokenServer, @@ -58,10 +62,18 @@ export async function resumeEphemeralVmWorkspace( request: VmWakeRequest ): Promise { const userDataPath = app.getPath('userData') - const runtime = findWorkspaceEphemeralVmRuntime(userDataPath, workspaceId) - if (!runtime) { + const found = findWorkspaceEphemeralVmRuntime(userDataPath, workspaceId) + if (!found) { return null } + // Slept from the CLI, the phone or another window: the record still says running, and the + // control plane says otherwise. Resume it now instead of waiting minutes for lost contact. + const runtime = + found.status === 'running' && + found.recipe?.provider === 'orca-cloud' && + (await isCloudWorkspaceAsleepOnControlPlane(workspaceId).catch(() => false)) + ? (markCloudRuntimeSleptElsewhere(userDataPath, found) ?? found) + : found // A VM recorded as up whose host Orca gave up reaching may have been stopped or reclaimed by its // provider (#34089): its recipe's resume brings it back. A failure there keeps the record as it // was, so a VM that was only out of reach is still reconnected as before. @@ -165,6 +177,8 @@ export async function resumeEphemeralVmWorkspace( ...pickEphemeralVmFailureCode(result) }) } + // The VM really resumed (not an early return on a VM already up): a quiet wake may count it. + noteQuietWakeResumed(workspaceId) if (lostContact && runtime.runtimeEnvironmentId) { // The resume restarted the VM; its server's old failures say nothing about the new boot. clearRuntimeEnvironmentContactLoss(runtime.runtimeEnvironmentId) diff --git a/src/main/hosted-sandbox/hosted-remote-sleep.test.ts b/src/main/hosted-sandbox/hosted-remote-sleep.test.ts new file mode 100644 index 00000000000..51c75687d0a --- /dev/null +++ b/src/main/hosted-sandbox/hosted-remote-sleep.test.ts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ + records: [] as Record[], + updates: [] as { id: string; patch: Record }[] +})) +vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ + listEphemeralVmRuntimes: () => state.records, + updateEphemeralVmRuntimeStatus: (_path: string, id: string, patch: Record) => { + state.updates.push({ id, patch }) + return { ...state.records.find((r) => r.id === id), ...patch } + } +})) +vi.mock('./hosted-workspace-runtime', () => ({ + findCloudRuntime: (_path: string, workspaceId: string) => + workspaceId === 'ws' ? { runtime: state.records[0], sandboxId: 'sbx_1' } : null +})) +vi.mock('../environment-providers/environment-provider-recipe-adapter', () => ({ + environmentHandleFromRecipeResult: (result: { sandboxId: string }) => ({ + driverState: { sandboxId: result.sandboxId } + }) +})) +vi.mock('./hosted-sandbox-driver', () => ({ HOSTED_SANDBOX_DRIVER_ID: 'orca-cloud' })) + +import { + findCloudRuntimeBySandboxId, + isAsleepOnControlPlane, + markCloudRuntimeSleptElsewhere, + noteCloudRuntimeRemoteState +} from './hosted-remote-sleep' +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' + +const RUNNING = { + id: 'vm-1', + status: 'running', + updatedAt: 100, + workspaceId: 'ws', + recipe: { provider: 'orca-cloud' }, + recipeResult: { sandboxId: 'sbx_1' } +} +// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the fields read here. +const record = (patch: Record = {}) => + ({ ...RUNNING, ...patch }) as unknown as EphemeralVmRuntimeRecord + +describe('a cloud VM slept from another client', () => { + beforeEach(() => { + state.records = [{ ...RUNNING }] + state.updates = [] + }) + + it('marks the running record suspended so the row reads Asleep and the next wake resumes it', () => { + expect(markCloudRuntimeSleptElsewhere('/u', record())?.status).toBe('suspended') + expect(state.updates).toEqual([{ id: 'vm-1', patch: { status: 'suspended' } }]) + }) + + it('leaves a record that changed while the control plane answered (a wake or sleep here wins)', () => { + state.records = [{ ...RUNNING, updatedAt: 200 }] + expect(markCloudRuntimeSleptElsewhere('/u', record())).toBeNull() + state.records = [{ ...RUNNING, status: 'suspended' }] + expect(markCloudRuntimeSleptElsewhere('/u', record())).toBeNull() + expect(state.updates).toEqual([]) + }) + + it('only touches running Orca Cloud records', () => { + expect(markCloudRuntimeSleptElsewhere('/u', record({ status: 'suspended' }))).toBeNull() + expect( + markCloudRuntimeSleptElsewhere('/u', record({ recipe: { provider: 'other' } })) + ).toBeNull() + expect(state.updates).toEqual([]) + }) + + it('asks the control plane; only a suspended sandbox counts, and an error counts as awake', async () => { + const get = vi.fn() + get.mockResolvedValueOnce({ status: 'suspended' }) + expect(await isAsleepOnControlPlane('/u', { get }, 'ws')).toBe(true) + get.mockResolvedValueOnce({ status: 'suspending' }) + expect(await isAsleepOnControlPlane('/u', { get }, 'ws')).toBe(false) + get.mockRejectedValueOnce(new Error('offline')) + expect(await isAsleepOnControlPlane('/u', { get }, 'ws')).toBe(false) + expect(await isAsleepOnControlPlane('/u', { get }, 'other')).toBe(false) + expect(get).toHaveBeenCalledTimes(3) + }) + + it('a status read that says sleeping marks the record read before it, then resyncs sessions', () => { + const syncSessions = vi.fn() + const seen = findCloudRuntimeBySandboxId('/u', 'sbx_1') + expect(seen?.id).toBe('vm-1') + expect(findCloudRuntimeBySandboxId('/u', 'sbx_2')).toBeNull() + noteCloudRuntimeRemoteState({ userDataPath: '/u', syncSessions }, seen!, 'ready') + expect(syncSessions).not.toHaveBeenCalled() + noteCloudRuntimeRemoteState({ userDataPath: '/u', syncSessions }, seen!, 'sleeping') + expect(state.updates).toEqual([{ id: 'vm-1', patch: { status: 'suspended' } }]) + expect(syncSessions).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/main/hosted-sandbox/hosted-remote-sleep.ts b/src/main/hosted-sandbox/hosted-remote-sleep.ts new file mode 100644 index 00000000000..a0bb24af006 --- /dev/null +++ b/src/main/hosted-sandbox/hosted-remote-sleep.ts @@ -0,0 +1,96 @@ +// A cloud VM put to sleep somewhere else (the CLI, the phone, another window) still reads as +// running in this desktop's runtime record until Orca loses contact with it, minutes later. Until +// then the row shows it awake and every wake returns at once without resuming it. The control +// plane knows: whenever it says the sandbox is asleep while the record says running, the record +// changes to suspended, so the row reads Asleep and the next wake really resumes it. +import { + listEphemeralVmRuntimes, + updateEphemeralVmRuntimeStatus +} from '../../shared/ephemeral-vm-runtime-store' +import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client' +import { findCloudRuntime } from './hosted-workspace-runtime' +import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter' +import { HOSTED_SANDBOX_DRIVER_ID } from './hosted-sandbox-driver' + +/** + * Marks `seen` (a running cloud record read before asking the control plane) suspended. Only when + * the stored record is still exactly the one that was read: a wake or sleep of this app that + * landed while the control plane answered wins. Returns the updated record, or null. + */ +export function markCloudRuntimeSleptElsewhere( + userDataPath: string, + seen: EphemeralVmRuntimeRecord +): EphemeralVmRuntimeRecord | null { + if (seen.status !== 'running' || seen.recipe?.provider !== 'orca-cloud') { + return null + } + const current = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === seen.id) + if (!current || current.status !== 'running' || current.updatedAt !== seen.updatedAt) { + return null + } + return updateEphemeralVmRuntimeStatus(userDataPath, seen.id, { status: 'suspended' }) +} + +/** The running Orca Cloud record for a sandbox id, as read now (before asking the control plane). */ +export function findCloudRuntimeBySandboxId( + userDataPath: string, + sandboxId: string +): EphemeralVmRuntimeRecord | null { + for (const runtime of listEphemeralVmRuntimes(userDataPath)) { + if ( + runtime.recipe?.provider !== 'orca-cloud' || + runtime.status !== 'running' || + !runtime.recipeResult + ) { + continue + } + const handle = environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID) + if (handle?.driverState.sandboxId === sandboxId) { + return runtime + } + } + return null +} + +/** A status read said `state`: asleep there but running here was slept from another client. */ +export function noteCloudRuntimeRemoteState( + deps: { userDataPath: string; syncSessions: () => void }, + seen: EphemeralVmRuntimeRecord, + state: string +): void { + if (state === 'sleeping' && markCloudRuntimeSleptElsewhere(deps.userDataPath, seen)) { + // Its lease scheduler stops: the session it renewed is gone. + deps.syncSessions() + } +} + +/** Whether the control plane says this workspace's sandbox is asleep; unknown counts as not. */ +export async function isAsleepOnControlPlane( + userDataPath: string, + client: Pick, + workspaceId: string +): Promise { + const found = findCloudRuntime(userDataPath, workspaceId) + if (!found) { + return false + } + try { + return (await client.get(found.sandboxId)).status === 'suspended' + } catch { + // Unreachable: the wake goes on as before (lost contact still recovers it later). + return false + } +} + +let asleepCheck: ((workspaceId: string) => Promise) | null = null +/** Installed with Orca Cloud; a wake of a cloud VM recorded as running asks it first. */ +export function setCloudAsleepCheck( + check: ((workspaceId: string) => Promise) | null +): void { + asleepCheck = check +} +/** False when Orca Cloud is off in this build. */ +export function isCloudWorkspaceAsleepOnControlPlane(workspaceId: string): Promise { + return asleepCheck ? asleepCheck(workspaceId) : Promise.resolve(false) +} diff --git a/src/main/hosted-sandbox/hosted-sandbox-install.ts b/src/main/hosted-sandbox/hosted-sandbox-install.ts index 4f2d1ae0b8b..923ca2a52c2 100644 --- a/src/main/hosted-sandbox/hosted-sandbox-install.ts +++ b/src/main/hosted-sandbox/hosted-sandbox-install.ts @@ -1,4 +1,10 @@ import { cloudDevSigningAllowed, withCloudBuildDefaults } from '../cloud-build-defaults' +import { + findCloudRuntimeBySandboxId, + isAsleepOnControlPlane, + noteCloudRuntimeRemoteState, + setCloudAsleepCheck +} from './hosted-remote-sleep' // Wires Orca Cloud into the desktop when this build has a control plane configured (off by default). import { app, BrowserWindow, ipcMain } from 'electron' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' @@ -114,10 +120,19 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo client: { ...client, workspaceStatus: async (sandboxId, signal) => { + // Asleep there but recorded running here: slept from another client (hosted-remote-sleep). + const seen = findCloudRuntimeBySandboxId(userDataPath, sandboxId) const answer = await client.workspaceStatus(sandboxId, signal) if (answer.status.idleSleepMinutes) { noteIdleSleepMinutes(answer.status.idleSleepMinutes) } + if (seen) { + noteCloudRuntimeRemoteState( + { userDataPath, syncSessions: () => void registry.sync() }, + seen, + answer.status.state + ) + } return answer } }, @@ -131,6 +146,7 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo windows: () => BrowserWindow.getAllWindows() }) setCloudArchiveCheck((workspaceId) => isArchivedOnControlPlane(userDataPath, client, workspaceId)) + setCloudAsleepCheck((workspaceId) => isAsleepOnControlPlane(userDataPath, client, workspaceId)) const offline = installCloudOfflineService({ userDataPath, call: (environmentId, method, params, timeoutMs) => @@ -182,6 +198,7 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo disposeTransfer() setHostedWorkspaceService(null) setCloudArchiveCheck(null) + setCloudAsleepCheck(null) offline.dispose() setCloudOfflineService(null) }) diff --git a/src/main/ipc/runtime.ts b/src/main/ipc/runtime.ts index 099e17316b8..5af0d00cdc0 100644 --- a/src/main/ipc/runtime.ts +++ b/src/main/ipc/runtime.ts @@ -3,7 +3,8 @@ import { claimQuietWake, endQuietWake, markQuietWake, - noteQuietWakeWoke + noteQuietWakeWoke, + takeQuietWakeResumed } from '../ephemeral-vm/quiet-wakes' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { @@ -61,10 +62,13 @@ export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void { return toWorkspaceLifecycleResult(() => runtime.wakeWorkspaceVm(args.workspaceId)).then( (result) => { if (args.quiet === true) { - if (result.ok) { + // A VM already up (or recorded so) resumes nothing: no wake to count, no short idle window. + const resumed = takeQuietWakeResumed(args.workspaceId) + if (result.ok && resumed) { noteQuietWakeWoke(args.workspaceId) } endQuietWake(args.workspaceId) + return result.ok ? { ...result, resumed } : result } return result } diff --git a/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.test.ts b/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.test.ts index e846090e9b7..0a74c5b8052 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.test.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.test.ts @@ -15,6 +15,8 @@ function harness( enabled?: boolean candidates?: Set refuse?: boolean + /** Main found nothing to resume (the VM was already up). */ + alreadyUp?: boolean preflight?: (id: string) => Promise } = {} ) { @@ -32,8 +34,8 @@ function harness( ...(overrides.preflight ? { preflight: overrides.preflight } : {}), wake: (id) => { woken.push(id) - return new Promise((resolve) => { - settle[id] = () => resolve(!overrides.refuse) + return new Promise((resolve) => { + settle[id] = () => resolve(overrides.alreadyUp ? 'skipped' : !overrides.refuse) }) }, setTimer: (run, ms) => { @@ -244,4 +246,34 @@ describe('predictive wake', () => { await h.advance(SELECT_DEBOUNCE_MS) expect(h.woken).toEqual([]) }) + + it('a hover the server preflight skips gives the hover gap back, so the next hover asks again', async () => { + let allow = false + const h = harness({ preflight: async () => allow }) + h.controller.hoverStart('ws-a') + await h.advance(HOVER_DWELL_MS) + h.controller.hoverEnd('ws-a') + expect(h.woken).toEqual([]) + // The hold ended a moment later: well inside the 30 s gap, the next hover still wakes. + allow = true + await h.advance(1_000) + h.controller.hoverStart('ws-a') + await h.advance(HOVER_DWELL_MS) + expect(h.woken).toEqual(['ws-a']) + expect(WEAK_TRIGGER_MIN_GAP_MS).toBeGreaterThan(1_000 + HOVER_DWELL_MS) + }) + + it('a wake that found the VM already up counts as no wake: no hold, no backoff, gap given back', async () => { + const h = harness({ alreadyUp: true }) + h.controller.hoverStart('ws-a') + await h.advance(HOVER_DWELL_MS) + await h.settleAll('ws-a') + expect(h.controller.awakeUnopened().size).toBe(0) + expect(h.controller.inFlight().size).toBe(0) + h.controller.hoverEnd('ws-a') + await h.advance(1_000) + h.controller.hoverStart('ws-a') + await h.advance(HOVER_DWELL_MS) + expect(h.woken).toEqual(['ws-a', 'ws-a']) + }) }) diff --git a/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.ts b/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.ts index c863fbdd8ec..b91e0602cb9 100644 --- a/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.ts +++ b/src/renderer/src/lib/orca-cloud/cloud-predictive-wake.ts @@ -23,8 +23,11 @@ export type PredictiveWakeDeps = { * slept on purpose from another client moments ago, or its owner's seat is at or near its cap. */ preflight?: (workspaceId: string) => Promise - /** Starts the ordinary wake quietly; resolves true when the sandbox woke, false when refused. */ - wake: (workspaceId: string) => Promise + /** + * Starts the ordinary wake quietly; resolves true when the sandbox woke, false when refused, and + * 'skipped' when there was nothing to resume (it was already up): no wake, and no backoff. + */ + wake: (workspaceId: string) => Promise /** Schedules `run`; returns a cancel function. */ setTimer: (run: () => void, ms: number) => () => void } @@ -117,12 +120,15 @@ export function createPredictiveWakeController(deps: PredictiveWakeDeps): Predic if (trigger === 'focus' && sleptNoFocus.has(workspaceId)) { return } + // A wake that turns out skipped never happened, so it gives the hover/focus gap back. + const previousWeakWakeAt = lastWeakWakeAt if (trigger !== 'select') { if (deps.now() - lastWeakWakeAt < WEAK_TRIGGER_MIN_GAP_MS) { return } lastWeakWakeAt = deps.now() } + const thisWeakWakeAt = lastWeakWakeAt running.add(workspaceId) silent.add(workspaceId) void Promise.resolve() @@ -136,6 +142,10 @@ export function createPredictiveWakeController(deps: PredictiveWakeDeps): Predic .then((woke) => { const claimed = !silent.has(workspaceId) if (woke === 'skipped') { + // Unless a later wake took the gap since. + if (trigger !== 'select' && lastWeakWakeAt === thisWeakWakeAt) { + lastWeakWakeAt = previousWeakWakeAt + } return } if (!woke) { diff --git a/src/renderer/src/lib/orca-cloud/install-cloud-predictive-wake.ts b/src/renderer/src/lib/orca-cloud/install-cloud-predictive-wake.ts index 12df77f4320..ea809fba9f3 100644 --- a/src/renderer/src/lib/orca-cloud/install-cloud-predictive-wake.ts +++ b/src/renderer/src/lib/orca-cloud/install-cloud-predictive-wake.ts @@ -62,6 +62,10 @@ export function installCloudPredictiveWake(): () => void { .resumeWorkspace({ workspaceId, quiet: true }) .catch(() => null) await refreshCloudWorkspaceStatus(workspaceId) + if (result?.ok === true && result.resumed === false) { + // Already up (main found nothing to resume): no wake happened, so nothing to hold. + return 'skipped' + } if (result?.ok === true && useAppStore.getState().activeWorktreeId === workspaceId) { // Woken for the workspace the user is already in (window focus, or hover then open): // it is open, not a guess, so it keeps the normal idle window. diff --git a/src/shared/ephemeral-vm-runtimes.ts b/src/shared/ephemeral-vm-runtimes.ts index 4c713985efa..7afc9f38f9e 100644 --- a/src/shared/ephemeral-vm-runtimes.ts +++ b/src/shared/ephemeral-vm-runtimes.ts @@ -120,7 +120,12 @@ export type EphemeralVmRuntimeStatusPatch = { /** Suspend/resume over IPC: failures come back as values so the code reaches the renderer catalog. */ export type EphemeralVmWorkspaceLifecycleResult = - | { ok: true; runtime: EphemeralVmRuntimeRecord | null } + | { + ok: true + runtime: EphemeralVmRuntimeRecord | null + /** Quiet (intent) wakes only: whether the VM actually resumed; false when it was already up. */ + resumed?: boolean + } | ({ ok: false } & EphemeralVmFailure) export const EphemeralVmRuntimeStoreSchema = z.object({