diff --git a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx index 4efda413a59..dbbfafc2b82 100644 --- a/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx +++ b/src/renderer/src/components/orca-cloud/OrcaCloudWorkspaceSurface.tsx @@ -2,7 +2,6 @@ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from import { toast } from 'sonner' import { useAppStore } from '@/store' import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' -import { usePrefersReducedMotion } from '@/hooks/usePrefersReducedMotion' import { focusTerminalTabSurface } from '@/components/terminal-pane/input/focus/focus-terminal-tab-surface' import { returnFocusToWorkspace } from './cloud-focus-return' import { @@ -13,21 +12,18 @@ import { } from './cloud-cover-focus' import { useNow } from '@/hooks/use-now' import { useTranslate } from '@/i18n/use-translate' -import { - WAKE_STALE_MS, - isWakeActive, - isWakeFailedFresh -} from '@/lib/orca-cloud/orca-cloud-workspace-state' +import { isWakeActive } from '@/lib/orca-cloud/orca-cloud-workspace-state' import { cloudWorkspaceTarget, dismissCloudOom, dismissCloudWake, useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' -import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/cloud-workspace-api' import type { CloudOfflineSnapshot } from '../../../../shared/hosted-sandbox/cloud-workspace-offline-api' import { CloudArchivedWorkspaceView, type ArchiveLoad } from './CloudArchivedWorkspaceView' import { CloudWakingOverlay } from './CloudWakingOverlay' +import { useWakeOverlay } from './use-wake-overlay' +import { PairedCloudWorkspaceSurface, useIsPairedCloudRow } from './PairedCloudWorkspaceSurface' import { CloudWorkspaceNotice } from './CloudWorkspaceNotice' import { CloudSetupNoticesDock } from './CloudSetupNotices' import { useConfirmedRestart } from './use-cloud-panel-actions' @@ -47,12 +43,6 @@ import { clearWakeInput } from '@/components/terminal-pane/input/wake-input-buff import { runUnarchiveCloudWorkspace, wakeCloudWorkspace } from './cloud-workspace-actions' import { keepWorkspaceAwakeDuringSleep } from '@/components/sidebar/workspace-actions/sleep/workspace-sleep-follower' -/** A wake that settles faster than this never shows the overlay (no skeleton flash). */ -const SHOW_DELAY_MS = 300 -/** Once shown, the overlay stays at least this long so it never blinks. */ -const MIN_HOLD_MS = 600 -const FADE_MS = 200 - /** * The Orca Cloud layer over the active workspace, one mount for all of it: the archived view, * the "Waking…" overlay, the asleep (cached, read-only) view, and the not-responding / out-of- @@ -65,8 +55,12 @@ export function OrcaCloudWorkspaceSurface({ worktreeId: string | null }): React.JSX.Element | null { const isCloud = useIsCloudWorkspace(worktreeId) + const isPaired = useIsPairedCloudRow(worktreeId) if (!worktreeId || !isCloud) { - return null + // A PAIRED row (no runtime record here) gets its own waking, asleep and saving layers. + return worktreeId && isPaired ? ( + + ) : null } // Keyed: switching worktrees resets every piece of per-workspace state. return @@ -107,76 +101,6 @@ function useArchiveLoad(workspaceId: string, enabled: boolean): [ArchiveLoad, () return [load, useCallback(() => setAttempt((n) => n + 1), [])] } -/** - * The wake the overlay shows: shown after SHOW_DELAY_MS, held at least MIN_HOLD_MS, faded out - * after. A wake that stops reporting turns into a failure instead of quietly vanishing. - */ -function useWakeOverlay( - wake: CloudWakeProgressEvent | undefined, - now: number, - stalledMessage: string, - /** Typing is already held for this wake: show its pill now, not after the show delay. */ - immediate = false -): { wake: CloudWakeProgressEvent | null; leaving: boolean } { - const reducedMotion = usePrefersReducedMotion() - const effective: CloudWakeProgressEvent | null = !wake - ? null - : isWakeActive(wake, now) - ? wake - : isWakeFailedFresh(wake, now) - ? wake - : (wake.phase === 'waking' || wake.phase === 'connecting') && now - wake.at >= WAKE_STALE_MS - ? { ...wake, phase: 'failed', message: stalledMessage } - : null - const failed = effective?.phase === 'failed' - const [shown, setShown] = useState<{ wake: CloudWakeProgressEvent; at: number } | null>(null) - const [leaving, setLeaving] = useState(false) - const effectiveKey = effective ? `${effective.startedAt}:${effective.phase}` : null - const latest = useRef(effective) - latest.current = effective - - useEffect(() => { - if (effective) { - setLeaving(false) - if (shown) { - setShown({ wake: effective, at: shown.at }) - return undefined - } - // Failures show at once (and wakes the person is already typing into, and a wake that - // started earlier, e.g. on hover, and has already outlasted the delay); others only if they - // outlast the show delay. - if (failed || immediate || Date.now() - effective.startedAt >= SHOW_DELAY_MS) { - setShown({ wake: effective, at: Date.now() }) - return undefined - } - const timer = setTimeout(() => { - if (latest.current) { - setShown({ wake: latest.current, at: Date.now() }) - } - }, SHOW_DELAY_MS) - return () => clearTimeout(timer) - } - if (!shown) { - return undefined - } - const hold = Math.max(0, shown.at + MIN_HOLD_MS - Date.now()) - const fade = reducedMotion ? 0 : FADE_MS - const startFade = setTimeout(() => setLeaving(fade > 0), hold) - const hide = setTimeout(() => { - setLeaving(false) - setShown(null) - }, hold + fade) - return () => { - clearTimeout(startFade) - clearTimeout(hide) - } - // `shown` is read, not tracked: a re-run per show would restart the hold. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [effectiveKey, reducedMotion, immediate]) - - return { wake: shown?.wake ?? null, leaving } -} - function emptySnapshot(workspaceId: string): CloudOfflineSnapshot { return { workspaceId, asleep: true, capturedAt: null, git: null, terminals: [], chats: [] } } diff --git a/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.fixture.tsx b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.fixture.tsx new file mode 100644 index 00000000000..60ff4941fc3 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.fixture.tsx @@ -0,0 +1,143 @@ +// SLEEP-IN-PROGRESS (2/2): the layer over a PAIRED cloud workspace's panes (waking, asleep with its +// sealed copy, saving that copy after Sleep, and a wake the plan refused). +import React from 'react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { CloudWakeProgressEvent } from '../../../../shared/hosted-sandbox/cloud-workspace-api' +import type { ReadSnapshot } from '../../../../shared/cloud-workspaces/read-snapshot' +import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state' +import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { markSleepCopySaving, resetWorktreeSleepViewForTests } from '@/lib/worktree-sleep-view' +import { recordBillingStatus } from '../billing/billing-summary-store' +import { sampleTeam } from '../billing/plan-billing-fixtures' +import { PairedCloudWorkspaceSurface } from './PairedCloudWorkspaceSurface' + +const ID = 'paired-fixture::/workspace/orca-sandbox-checkout-retries' +const MIN = 60_000 + +const copy = (now: number): ReadSnapshot => ({ + v: 1, + workspaceId: 'sbx_paired_fixture', + snapshotId: 'snap_paired', + capturedAt: now - 42 * MIN, + reason: 'sleep', + pr: null, + sessions: [], + git: { + branch: 'checkout-retries', + head: '3f95655684912ab', + changeCount: 2, + added: 96, + removed: 21, + changes: [ + { + path: 'src/payments/webhooks.ts', + status: 'modified', + area: 'unstaged', + added: 88, + removed: 19 + }, + { path: 'src/payments/retry.ts', status: 'added', area: 'untracked', added: 8, removed: 2 } + ], + commits: [ + { + id: '3f95655684912ab', + subject: 'Retry checkout webhooks', + author: null, + at: now - 50 * MIN + } + ] + } +}) + +const asleep = { + state: 'sleeping' as const, + metrics: null, + uptimeMs: 0, + usage: { totalMs: 0, centsPerHour: 75, costCents: 0 }, + archive: null, + checkedAt: 1 +} + +function serve(read: (now: number) => CloudReadSnapshotState, wake?: CloudWakeProgressEvent): void { + const now = Date.now() + Object.defineProperty(window.api, 'cloudWorkspaces', { + configurable: true, + value: { + ...window.api.cloudWorkspaces, + readSnapshot: async () => ({ ok: true, value: read(now) }), + localWorkspaces: async () => [], + environmentBindings: async () => ({ sbx_paired_fixture: { environmentId: 'env-paired' } }) + } + }) + resetWorktreeSleepViewForTests() + seedCloudWorkspaceSnapshot({ + paired: { [ID]: 'env-paired' }, + status: { [ID]: { status: asleep, loading: false, error: null, fetchedAt: now } }, + wake: wake ? { [ID]: wake } : {}, + idsLoaded: true + }) +} + +const wakeEvent = (over: Partial = {}): CloudWakeProgressEvent => ({ + workspaceId: ID, + phase: 'waking', + source: 'open', + startedAt: Date.now() - 3_200, + at: Date.now(), + ...over +}) + +function Pane(): React.JSX.Element { + return ( +
+
+ Reconnecting… retrying automatically +
+ +
+ ) +} + +/** Opening a sleeping paired workspace: the same waking overlay an owned one shows. */ +export const pairedWaking = defineFixture({ + width: 720, + setup: () => serve(() => ({ state: 'no_snapshot' }), wakeEvent()), + render: () => +}) + +/** Asleep: the sealed copy the control plane holds, read-only, with Wake to continue. */ +export const pairedAsleepWithCopy = defineFixture({ + width: 720, + setup: () => serve((now) => ({ state: 'ready', snapshot: copy(now), storedAt: now })), + render: () => +}) + +/** Sleep just pressed here: saving its sealed copy, never "Nothing saved yet" meanwhile. */ +export const pairedSaving = defineFixture({ + width: 720, + setup: () => { + serve(() => ({ state: 'no_snapshot' })) + markSleepCopySaving(ID) + }, + render: () => +}) + +/** The plan refused the wake: the shared card carries the billing copy, as for an owned row. */ +export const pairedWakeRefusedBilling = defineFixture({ + width: 720, + setup: () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture entitlement overrides only the role the card reads. + const result = { status: 'ok', entitlement: { ...sampleTeam, canManageBilling: true } } as never + window.api.orcaProfiles.billingStatus = () => Promise.resolve(result) + recordBillingStatus(result) + serve( + () => ({ state: 'no_snapshot' }), + wakeEvent({ + phase: 'failed', + message: 'entitlement_denied', + billingDenial: { reason: 'included_hours_exhausted' } + }) + ) + }, + render: () => +}) diff --git a/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.test.tsx b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.test.tsx new file mode 100644 index 00000000000..c4ec26e7780 --- /dev/null +++ b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.test.tsx @@ -0,0 +1,219 @@ +// @vitest-environment happy-dom +// SLEEP-IN-PROGRESS (2/2): a PAIRED cloud workspace gets the waking overlay, the asleep sealed copy +// with Wake to continue, and the saving / failed states after a Sleep pressed here. + +import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ReadSnapshot } from '../../../../shared/cloud-workspaces/read-snapshot' +import type { CloudReadSnapshotState } from '../../../../shared/cloud-workspaces/read-snapshot-state' +import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { + SLEEP_COPY_DEADLINE_MS, + markSleepCopySaving, + resetWorktreeSleepViewForTests +} from '@/lib/worktree-sleep-view' +import { OrcaCloudWorkspaceSurface } from './OrcaCloudWorkspaceSurface' +import { SEALED_COPY_POLL_MS } from './PairedCloudWorkspaceSurface' + +const wakePaired = vi.hoisted(() => vi.fn(async () => ({ ok: true as const }))) +vi.mock('@/lib/orca-cloud/paired-cloud-wake', async (importOriginal) => ({ + ...(await importOriginal()), + wakePairedCloudWorkspace: wakePaired +})) +vi.mock('@/lib/orca-cloud/cloud-host-rows', async (importOriginal) => ({ + ...(await importOriginal()), + resolveCloudRowSandboxId: async () => 'sbx_paired' +})) +vi.mock('@/components/sidebar/workspace-actions/sleep/use-worktree-sleep-state', () => ({ + useIsSleepingWorktree: () => false +})) +vi.mock('@/components/sidebar/workspace-card/activity/use-worktree-activity-status', () => ({ + useWorktreeActivityStatus: () => 'inactive' +})) + +const T0 = 1_800_000_000_000 +const ID = 'repo::/workspace/orca-sandbox-paired' + +const status = (state: 'sleeping' | 'ready') => ({ + status: { + state, + metrics: null, + uptimeMs: 0, + usage: { totalMs: 0, centsPerHour: 75, costCents: 0 }, + archive: null, + checkedAt: T0 + }, + loading: false, + error: null, + fetchedAt: T0 +}) + +const copy = (capturedAt: number): ReadSnapshot => ({ + v: 1, + workspaceId: 'sbx_paired', + snapshotId: `snap_${capturedAt}`, + capturedAt, + reason: 'sleep', + pr: null, + sessions: [], + git: { + branch: 'paired-branch', + head: 'abc1234', + changeCount: 0, + added: null, + removed: null, + changes: [], + commits: [] + } +}) + +let reads: CloudReadSnapshotState[] +const readSnapshot = vi.fn(async () => ({ + ok: true as const, + value: reads.length > 1 ? (reads.shift() ?? reads[0]) : reads[0] +})) + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(T0) + resetWorktreeSleepViewForTests() + wakePaired.mockClear() + readSnapshot.mockClear() + reads = [{ state: 'no_snapshot' }] + Object.defineProperty(window, 'api', { + configurable: true, + value: { + cloudWorkspaces: { readSnapshot }, + orcaCloudWorkspace: { getStatus: async () => ({ ok: false, message: 'offline' }) } + } + }) +}) + +afterEach(() => { + cleanup() + seedCloudWorkspaceSnapshot({}) + resetWorktreeSleepViewForTests() + vi.useRealTimers() +}) + +function seedPaired( + state: 'sleeping' | 'ready', + extra: Parameters[0] = {} +) { + seedCloudWorkspaceSnapshot({ + paired: { [ID]: 'env-paired' }, + status: { [ID]: status(state) }, + idsLoaded: true, + ...extra + }) +} + +async function flush(ms = 0): Promise { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms) + }) +} + +describe('the paired cloud workspace surface', () => { + it('a paired row waking shows the waking overlay; Try again wakes it through the control plane', async () => { + seedPaired('sleeping', { + wake: { + [ID]: { workspaceId: ID, phase: 'waking', source: 'open', startedAt: T0 - 2_000, at: T0 } + } + }) + const { container } = render() + await flush() + expect(container.querySelector('[data-cloud-cover="waking"]')).not.toBeNull() + act(() => + seedPaired('sleeping', { + wake: { + [ID]: { + workspaceId: ID, + phase: 'failed', + source: 'open', + startedAt: T0 - 2_000, + at: T0, + message: 'boom' + } + } + }) + ) + await flush() + const retry = Array.from(container.querySelectorAll('button')).find((b) => + /Try again/.test(b.textContent ?? '') + ) + expect(retry).toBeDefined() + fireEvent.click(retry!) + expect(wakePaired).toHaveBeenCalledWith(ID) + }) + + it('a paired asleep row shows its sealed copy; Wake to continue wakes it', async () => { + reads = [{ state: 'ready', snapshot: copy(T0 - 60_000), storedAt: T0 }] + seedPaired('sleeping') + const { container, getByRole } = render() + await flush() + expect(readSnapshot).toHaveBeenCalledWith('sbx_paired') + expect(container.querySelector('[data-cloud-cover="asleep"]')).not.toBeNull() + expect(container.textContent).toContain('paired-branch') + fireEvent.click(getByRole('button', { name: 'Wake to continue' })) + expect(wakePaired).toHaveBeenCalledWith(ID, { source: 'open' }) + }) + + it('after a paired Sleep: saving (never the empty states) until a new-enough sealed copy is read', async () => { + // The old copy, then nothing new, then the one this Sleep sealed. + reads = [ + { state: 'ready', snapshot: copy(T0 - 60_000), storedAt: T0 }, + { state: 'no_snapshot' }, + { state: 'ready', snapshot: copy(T0 + 1_000), storedAt: T0 + 1_000 } + ] + markSleepCopySaving(ID, T0) + seedPaired('ready') + const { container, queryByRole } = render() + await flush() + expect(container.textContent).toContain('Saving a read-only copy…') + expect(container.textContent).not.toContain('paired-branch') + expect(container.textContent).not.toContain('Nothing saved yet') + expect(queryByRole('button', { name: 'Wake to continue' })).toBeNull() + await flush(SEALED_COPY_POLL_MS) + expect(container.textContent).toContain('Saving a read-only copy…') + expect(container.textContent).not.toContain('Nothing saved yet') + act(() => seedPaired('sleeping')) + await flush(SEALED_COPY_POLL_MS) + expect(readSnapshot).toHaveBeenCalledTimes(3) + expect(container.textContent).not.toContain('Saving a read-only copy…') + expect(container.textContent).toContain('paired-branch') + expect(queryByRole('button', { name: 'Wake to continue' })).not.toBeNull() + }) + + it('no sealed copy by the deadline: the failed line, with the header Wake as the one Wake', async () => { + markSleepCopySaving(ID, T0) + seedPaired('sleeping') + const { container, getAllByRole } = render() + await flush(SLEEP_COPY_DEADLINE_MS) + expect(container.querySelector('[data-cloud-sleep-copy="failed"]')).not.toBeNull() + expect(container.textContent).not.toContain('Nothing saved yet') + expect(getAllByRole('button', { name: /Wake/ })).toHaveLength(1) + // Polling stopped with the deadline. + const calls = readSnapshot.mock.calls.length + await flush(SEALED_COPY_POLL_MS * 3) + expect(readSnapshot.mock.calls.length).toBe(calls) + }) + + it('an owned row never mounts the paired layer, and a non-cloud row renders nothing', async () => { + seedCloudWorkspaceSnapshot({ + ids: new Set([ID]), + status: { [ID]: status('ready') }, + idsLoaded: true + }) + const owned = render() + await flush() + expect(owned.container.querySelector('[data-cloud-paired]')).toBeNull() + expect(owned.container.querySelector('[data-cloud-surface]')).not.toBeNull() + owned.unmount() + seedCloudWorkspaceSnapshot({ idsLoaded: true }) + const plain = render() + await flush() + expect(plain.container.innerHTML).toBe('') + expect(readSnapshot).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.tsx b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.tsx new file mode 100644 index 00000000000..992c332c9bd --- /dev/null +++ b/src/renderer/src/components/orca-cloud/PairedCloudWorkspaceSurface.tsx @@ -0,0 +1,209 @@ +// SLEEP-IN-PROGRESS (2/2): the Orca Cloud layer over a PAIRED workspace (a " (cloud)" server +// bound to a sandbox; this desktop has no runtime record for it). Same waking overlay as an owned +// workspace; asleep, the read-only copy is the control plane's SEALED snapshot (the only copy a +// paired workspace has), with the saving and failed states after a Sleep pressed here. +import React, { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { findWorktreeById } from '@/store/github/refresh/worktree-refresh' +import { useNow } from '@/hooks/use-now' +import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval' +import { useTranslate } from '@/i18n/use-translate' +import { isWakeActive } from '@/lib/orca-cloud/orca-cloud-workspace-state' +import { dismissCloudWake, useCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { isPairedCloudStatusRow } from '@/lib/orca-cloud/orca-cloud-workspace-rows' +import { wakePairedCloudWorkspace } from '@/lib/orca-cloud/paired-cloud-wake' +import { resolveCloudRowSandboxId } from '@/lib/orca-cloud/cloud-host-rows' +import { clearSleepCopySave, useSleepCopySave } from '@/lib/worktree-sleep-view' +import { + sandboxIdForWorktree, + useCloudWorkspaceIdentities +} from '@/components/cloud-workspaces/cloud-workspace-identity' +import { useCloudReadSnapshot } from '@/components/cloud-workspaces/use-cloud-read-snapshot' +import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import { coveredPaneHadFocus, useInertSiblings } from './cloud-cover-focus' +import { CloudWakingOverlay } from './CloudWakingOverlay' +import { useWakeOverlay } from './use-wake-overlay' +import { useConfirmedRestart } from './use-cloud-panel-actions' +import { useCloudWorkspaceView } from './use-cloud-workspace-view' +import { useSleepCopyProgress } from './offline/CloudSleepCopyState' +import { + CloudReadSnapshotView, + type CloudReadViewState +} from './read-snapshot/CloudReadSnapshotView' + +/** While its copy saves, the sealed snapshot is re-read this often (a read is otherwise once). */ +export const SEALED_COPY_POLL_MS = 2_500 + +/** Is this row PAIRED (cloud status, but not this desktop's own cloud workspace)? */ +export function useIsPairedCloudRow(workspaceId: string | null): boolean { + return useCloudWorkspace((s) => workspaceId !== null && isPairedCloudStatusRow(s, workspaceId)) +} + +/** The sandbox behind the paired row; `settled` once a lookup has answered (null: none found). */ +function usePairedSandboxId( + workspaceId: string, + enabled: boolean +): { sandboxId: string | null; settled: boolean } { + const environmentId = useCloudWorkspace((s) => s.paired[workspaceId] ?? null) + const hostId = environmentId ? toRuntimeExecutionHostId(environmentId) : null + const identities = useCloudWorkspaceIdentities() + const known = sandboxIdForWorktree({ id: workspaceId, hostId }, identities) + const [resolved, setResolved] = useState<{ sandboxId: string | null } | null>(null) + useEffect(() => { + if (!enabled || known) { + return + } + let live = true + // A pairing may be newer than the bindings this window loaded: re-read them first. + void resolveCloudRowSandboxId({ id: workspaceId, hostId }).then((sandboxId) => { + if (live) { + setResolved({ sandboxId }) + } + }) + return () => { + live = false + } + }, [enabled, known, workspaceId, hostId]) + return { sandboxId: known ?? resolved?.sandboxId ?? null, settled: known !== null || !!resolved } +} + +/** The sealed copy, re-read every SEALED_COPY_POLL_MS while it saves; a new-enough one ends saving. */ +function usePairedSealedCopy( + workspaceId: string, + sandboxId: string | null +): ReturnType & { copySave: 'saving' | 'failed' | null } { + const read = useCloudReadSnapshot(sandboxId) + const capturedAt = read.state.kind === 'ready' ? read.state.snapshot.capturedAt : undefined + const copySave = useSleepCopyProgress(workspaceId, capturedAt) + const polling = copySave === 'saving' && sandboxId !== null + // A ref, so a new `retry` per render never reinstalls the poller (it runs once on install). + const retryRef = useRef(read.retry) + retryRef.current = read.retry + useEffect(() => { + if (!polling) { + return + } + // The first read already ran when the view opened; re-read on the cadence after that. + let first = true + // Paused while the window is hidden; ends as soon as the copy is in (saving clears). + return installWindowVisibilityInterval({ + run: () => { + if (first) { + first = false + return + } + retryRef.current() + }, + intervalMs: SEALED_COPY_POLL_MS, + slowWhileUnfocused: false + }) + }, [polling]) + return { ...read, copySave } +} + +export function PairedCloudWorkspaceSurface({ + workspaceId +}: { + workspaceId: string +}): React.JSX.Element | null { + const t = useTranslate() + const view = useCloudWorkspaceView(workspaceId, { pairedRows: true }) + const name = useAppStore((state) => findWorktreeById(state, workspaceId)?.displayName ?? null) + const now = useNow(1_000, view.wake !== undefined) + const overlay = useWakeOverlay( + view.wake, + Math.max(now, view.wake?.at ?? 0), + t('orcaCloudWorkspace.overlay.stalled', 'Orca Cloud stopped responding while waking.') + ) + const copySaveEntry = useSleepCopySave(workspaceId) + const wakeInFlight = Boolean( + view.wake && + view.wake.phase !== 'failed' && + view.wake.phase !== 'ready' && + isWakeActive(view.wake, Math.max(now, view.wake.at)) + ) + // Sleep pressed here: its status read can still say ready, but it is going to sleep. + const asleep = + !wakeInFlight && + view.state !== 'archived' && + (view.state === 'sleeping' || copySaveEntry?.state === 'saving') + const layer: 'waking' | 'asleep' | null = overlay.wake ? 'waking' : asleep ? 'asleep' : null + + const sandbox = usePairedSandboxId(workspaceId, layer === 'asleep') + const copy = usePairedSealedCopy(workspaceId, layer === 'asleep' ? sandbox.sandboxId : null) + // No sandbox behind the row after a fresh lookup: never a skeleton forever. + const readState: CloudReadViewState = + sandbox.settled && !sandbox.sandboxId ? { kind: 'not_found' } : copy.state + const slowNow = useNow(30_000, layer === 'asleep') + const restart = useConfirmedRestart(workspaceId) + + const coverRef = useRef(null) + const headingRef = useRef(null) + const [takeFocus, setTakeFocus] = useState(false) + useInertSiblings(coverRef, layer !== null && !overlay.leaving) + useLayoutEffect(() => { + setTakeFocus(layer !== null && coveredPaneHadFocus(coverRef.current)) + }, [layer]) + useEffect(() => { + if (takeFocus && layer === 'asleep') { + headingRef.current?.focus() + } + }, [takeFocus, layer]) + + const wake = (): void => { + // Woken: no copy is coming any more. + clearSleepCopySave(workspaceId) + void wakePairedCloudWorkspace(workspaceId, { source: 'open' }) + } + const label = name || t('orcaCloudWorkspace.thisWorkspaceTitle', 'This workspace') + const announcement = + layer === 'waking' && overlay.wake && overlay.wake.phase !== 'failed' + ? t('orcaCloudWorkspace.announce.waking', 'Waking {{name}}.', { name: label }) + : layer === 'asleep' && copy.copySave !== 'saving' + ? t('orcaCloudWorkspace.announce.asleep', '{{name}} is asleep.', { name: label }) + : '' + + return ( + <> +
+ {announcement} +
+ {layer ? ( +
+ {layer === 'waking' && overlay.wake ? ( + void wakePairedCloudWorkspace(workspaceId)} + onRestart={restart} + onDismiss={() => dismissCloudWake(workspaceId)} + /> + ) : layer === 'asleep' ? ( +
+
+ +
+
+ ) : null} +
+ ) : null} + + ) +} diff --git a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx index 40ef63c8fb9..00d9370898e 100644 --- a/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx +++ b/src/renderer/src/components/orca-cloud/read-snapshot/CloudReadSnapshotView.tsx @@ -14,6 +14,7 @@ import { CloudWorkspaceHeader } from '../CloudWorkspaceHeader' import { asOfParts } from './cloud-read-snapshot-format' import { CloudReadPrLink } from './CloudReadPrLink' import { CloudReadSessions } from './CloudReadSessions' +import { CloudSleepCopyFailed, CloudSleepCopySaving } from '../offline/CloudSleepCopyState' export type CloudReadViewState = | { kind: 'loading' } @@ -44,6 +45,11 @@ export type CloudReadSnapshotViewProps = { headingRef?: React.Ref /** Linux names the keyring to set up; defaults to this renderer's platform. */ linux?: boolean + /** + * SLEEP-IN-PROGRESS (paired): Sleep was pressed here and its sealed copy is still being saved, or + * never arrived. Either replaces the copy and every empty state; saving has no Wake yet. + */ + copySave?: 'saving' | 'failed' | null } export type CloudReadWake = @@ -140,6 +146,10 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. ? t('orcaCloudWorkspace.state.waking', 'Waking') : t('components.orcaCloud.read.asleep', 'Asleep') const linux = props.linux ?? isLinuxUserAgent() + const saving = props.copySave === 'saving' + const copyFailed = !saving && props.copySave === 'failed' + // The copy's own lines (and its empty states) only once a copy is known to be in. + const body = saving || copyFailed ? null : state.kind return (
- {waking ? : } - {waking ? ( - - {t('components.orcaCloud.read.wakingElapsed', 'Waking… {{elapsed}}', { - elapsed: formatElapsedTime(elapsedMs) - })} - - ) : ( - t('components.orcaCloud.read.wakeToContinue', 'Wake to continue') - )} - + // Still saving its copy: not asleep yet, so no Wake to continue beside the spinner. + saving ? undefined : ( + + ) } /> {/* Announced once when the wake crosses the slow mark (the text changes only then). */} @@ -218,9 +236,13 @@ export function CloudReadSnapshotView(props: CloudReadSnapshotViewProps): React. onRetry={props.onWake} /> ) : null} - {state.kind === 'loading' ? : null} - {state.kind === 'ready' ? : null} - {state.kind === 'no_snapshot' ? ( + {saving ? : null} + {copyFailed ? : null} + {body === 'loading' ? : null} + {state.kind === 'ready' && body === 'ready' ? ( + + ) : null} + {body === 'no_snapshot' ? ( ) : null} - {state.kind === 'not_sealed_for_key' ? ( + {body === 'not_sealed_for_key' ? ( ) : null} - {state.kind === 'stale' ? ( + {body === 'stale' ? ( ) : null} - {state.kind === 'unverified' ? ( + {body === 'unverified' ? ( ) : null} - {state.kind === 'signer_changed' ? ( + {body === 'signer_changed' ? ( ) : null} - {state.kind === 'not_found' ? ( + {body === 'not_found' ? ( ) : null} - {state.kind === 'unavailable' ? ( + {body === 'unavailable' ? ( ) : null} - {state.kind === 'error' ? ( + {state.kind === 'error' && body === 'error' ? ( = WAKE_STALE_MS + ? { ...wake, phase: 'failed', message: stalledMessage } + : null + const failed = effective?.phase === 'failed' + const [shown, setShown] = useState<{ wake: CloudWakeProgressEvent; at: number } | null>(null) + const [leaving, setLeaving] = useState(false) + const effectiveKey = effective ? `${effective.startedAt}:${effective.phase}` : null + const latest = useRef(effective) + latest.current = effective + + useEffect(() => { + if (effective) { + setLeaving(false) + if (shown) { + setShown({ wake: effective, at: shown.at }) + return undefined + } + // Failures show at once (and wakes the person is already typing into, and a wake that + // started earlier, e.g. on hover, and has already outlasted the delay); others only if they + // outlast the show delay. + if (failed || immediate || Date.now() - effective.startedAt >= SHOW_DELAY_MS) { + setShown({ wake: effective, at: Date.now() }) + return undefined + } + const timer = setTimeout(() => { + if (latest.current) { + setShown({ wake: latest.current, at: Date.now() }) + } + }, SHOW_DELAY_MS) + return () => clearTimeout(timer) + } + if (!shown) { + return undefined + } + const hold = Math.max(0, shown.at + MIN_HOLD_MS - Date.now()) + const fade = reducedMotion ? 0 : FADE_MS + const startFade = setTimeout(() => setLeaving(fade > 0), hold) + const hide = setTimeout(() => { + setLeaving(false) + setShown(null) + }, hold + fade) + return () => { + clearTimeout(startFade) + clearTimeout(hide) + } + // `shown` is read, not tracked: a re-run per show would restart the hold. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [effectiveKey, reducedMotion, immediate]) + + return { wake: shown?.wake ?? null, leaving } +} diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow-paired-copy.test.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow-paired-copy.test.ts new file mode 100644 index 00000000000..2c25f2fb9e1 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow-paired-copy.test.ts @@ -0,0 +1,68 @@ +// SLEEP-IN-PROGRESS (2/2): Sleep on a PAIRED cloud workspace marks its read-only copy saving from the +// press (like an owned one), and clears it when the control plane left its sandbox running. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + sleepPairedCloudSandboxes: vi.fn(async (_ids: readonly string[]): Promise => []) +})) + +vi.mock('sonner', () => ({ toast: { warning: vi.fn(), error: vi.fn() } })) +vi.mock('@/store', () => ({ useAppStore: { getState: () => ({}) } })) +vi.mock('@/lib/orca-cloud/paired-cloud-sleep', () => ({ + sleepPairedCloudSandboxes: mocks.sleepPairedCloudSandboxes +})) +vi.mock('@/lib/orca-cloud/cloud-sleep-failure-toast', () => ({ + toastCloudSleepFailure: () => true +})) +vi.mock('@/lib/orca-cloud/cloud-predictive-wake', () => ({ notePredictiveWakeSlept: vi.fn() })) +vi.mock('@/lib/orca-cloud-session-toasts', () => ({ dismissOrcaCloudRestartWarning: vi.fn() })) +vi.mock('./workspace-sleep-view-hold', () => ({ holdActiveCloudSleepView: vi.fn() })) +vi.mock('./workspace-sleep-target', () => ({ + workspaceSleepTarget: (_state: unknown, worktreeId: string) => ({ worktreeId }) +})) + +import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store' +import { resetWorktreeSleepViewForTests, sleepCopySave } from '@/lib/worktree-sleep-view' +import { runSleepWorktrees } from './sleep-worktree-flow' + +const T0 = 1_800_000_000_000 +const PAIRED = 'repo::/workspace/orca-sandbox-paired' +const LOCAL = 'repo::/local' + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(T0) + resetWorktreeSleepViewForTests() + mocks.sleepPairedCloudSandboxes.mockReset() + mocks.sleepPairedCloudSandboxes.mockResolvedValue([]) + seedCloudWorkspaceSnapshot({ paired: { [PAIRED]: 'env-paired' }, idsLoaded: true }) + vi.stubGlobal('window', { + api: { + worktrees: { + sleep: async ({ targets }: { targets: { worktreeId: string }[] }) => + targets.map(({ worktreeId }) => ({ worktreeId, chatFailed: false, receipts: [] })) + } + } + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() + seedCloudWorkspaceSnapshot({}) + resetWorktreeSleepViewForTests() + vi.useRealTimers() +}) + +describe('runSleepWorktrees on a paired cloud workspace', () => { + it('marks the paired copy saving from the press; a non-cloud row gets nothing', async () => { + await runSleepWorktrees([PAIRED, LOCAL]) + expect(sleepCopySave(PAIRED)).toEqual({ state: 'saving', since: T0 }) + expect(sleepCopySave(LOCAL)).toBeNull() + }) + + it('clears it when the control plane left the paired sandbox running', async () => { + mocks.sleepPairedCloudSandboxes.mockResolvedValue([PAIRED]) + await runSleepWorktrees([PAIRED]) + expect(sleepCopySave(PAIRED)).toBeNull() + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow.ts b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow.ts index 242ec889c5e..513d96da0ac 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/sleep/sleep-worktree-flow.ts @@ -1,6 +1,7 @@ import { toast } from 'sonner' import { toastCloudSleepFailure } from '@/lib/orca-cloud/cloud-sleep-failure-toast' import { sleepPairedCloudSandboxes } from '@/lib/orca-cloud/paired-cloud-sleep' +import { isPairedCloudWorkspace } from '@/lib/orca-cloud/paired-cloud-wake' import { useAppStore } from '@/store' import { translate } from '@/i18n/i18n' import type { ExecutionHostId } from '../../../../../../shared/execution-host' @@ -86,8 +87,9 @@ export async function runSleepWorktrees( const pressedAt = Date.now() const ownedCloud = getCloudWorkspaceSnapshot().ids for (const id of worktreeIds) { - if (ownedCloud.has(id)) { - // Saving its read-only copy until the asleep view reads one back (SLEEP-IN-PROGRESS). + if (ownedCloud.has(id) || isPairedCloudWorkspace(id)) { + // Saving its read-only copy until the asleep view reads one back (SLEEP-IN-PROGRESS); a + // PAIRED one's is the sealed snapshot its sandbox hands the control plane as it sleeps. markSleepCopySaving(id, pressedAt) } notePredictiveWakeSlept(id) @@ -115,6 +117,10 @@ export async function runSleepWorktrees( worktreeIds.filter((id) => !unslept.has(id)) ) const stillRunningIds = [...vmStillRunningIds, ...pairedStillRunning] + // The paired sandbox kept running: no sealed copy is coming either. + for (const id of pairedStillRunning) { + clearSleepCopySave(id) + } // An Orca Cloud sandbox left running gets the cloud copy (sandbox hours, Try again) instead. const cloudToasted = toastCloudSleepFailure(stillRunningIds, (ids) => void runSleepWorktrees(ids)) toastSleepFailures(new Set(worktreeIds).size, errors, stillRunningIds.length > 0 && !cloudToasted)