fix(cloud): archive from the team list really stops the sandbox (Sleep → archive with Undo, or the control-plane archive); archive never runs after a failed sleep (DS-01, DS-09)

This commit is contained in:
Neil
2026-11-10 02:19:03 -08:00
parent 209d658b03
commit 264f30f8a3
11 changed files with 285 additions and 36 deletions
+12 -1
View File
@@ -111,6 +111,7 @@ import type { GoldenImageProviderApi } from './golden-image-provider'
import { CreateRequestSchema, LeaseRequestSchema, parseWakeWait, readyView, sandboxView } from './wire'
import { ArchiveRequestSchema } from './sandbox-vm-inspect'
import {
restoreArchivedToSleeping,
archiveSandbox,
readArchive,
restartSandbox,
@@ -1372,7 +1373,17 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
if (!body.success) {
return fail('invalid_request', 400)
}
const patched = await patchWorkspace(db, caller, row, body.data, now)
const { archived, ...rest } = body.data
// Archive/unarchive are lifecycle changes, not labels: the sandbox really stops (snapshot kept
// with a TTL) or comes back asleep. Permissions are checked by patchWorkspace first.
let patched = await patchWorkspace(db, caller, row, archived === undefined ? body.data : { ...rest, archived }, now)
if (archived === true && (patched.row.status === 'running' || patched.row.status === 'suspended')) {
const stopped = await archiveSandbox(life, patched.row, {}, workspaceConfig(env, deps))
patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, stopped.id)) ?? patched.row }
} else if (archived === false && patched.row.status === 'archived') {
const restored = await restoreArchivedToSleeping(life, patched.row)
patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, restored.id)) ?? patched.row }
}
const revoked =
patched.revoke === 'none' ? null : await revokeForAccessChange(life, patched.row, patched.revoke, caller.userId)
return json({ workspace: await view(patched.row), ...(revoked ? { revoked } : {}) })
@@ -332,6 +332,21 @@ export async function unarchiveSandbox(deps: LifecycleDeps, row: SandboxRow): Pr
return resumeSandbox(deps, suspended)
}
/**
* Unarchive without waking (the team list): the snapshot backstop is restored and the workspace is
* asleep again; opening it later runs the ordinary billed, capped wake.
*/
export async function restoreArchivedToSleeping(deps: LifecycleDeps, row: SandboxRow): Promise<SandboxRow> {
if (row.status !== 'archived') {
return row
}
await deps.provider.updateSnapshotExpiration(
row.provider_name,
deps.config.snapshotExpirationMs ?? DEFAULT_SNAPSHOT_EXPIRATION_MS
)
return claim(deps, row, { status: 'suspended', archived_at: null, archive_expires_at: null })
}
/** Cron: archives past their TTL are destroyed (snapshots included). */
export async function expiredArchives(db: D1Database, now: number): Promise<SandboxRow[]> {
const { results } = await db
@@ -81,6 +81,26 @@ describe('workspace registry', () => {
expect((await t.req(t.admin, 'POST', `/v1/sandboxes/${t.id}/resume`)).status).toBe(404)
})
it('archives for real from the team list: the sandbox stops with a snapshot TTL; unarchive leaves it asleep', async () => {
const t = await team()
const name = `orca-test-${t.id}`
expect(t.h.vercel.boxes.get(name)!.status).toBe('running')
const archived = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })
expect(archived.status).toBe(200)
expect(archived.body.workspace.archivedAt).toBe(t.h.now())
expect(t.h.vercel.boxes.get(name)!.status).toBe('stopped')
expect(t.h.raw.prepare('SELECT status, archive_expires_at FROM sandboxes WHERE id = ?').get(t.id)).toMatchObject({
status: 'archived'
})
expect(t.h.vercel.snapshotExpirations.get(name)).toBe(37 * 24 * 60 * MIN)
const restored = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: false })
expect(restored.body.workspace.archivedAt).toBeNull()
expect(t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ status: 'suspended' })
// Restoring does not start (or bill) the sandbox; opening it wakes it as usual.
expect(t.h.vercel.boxes.get(name)!.status).toBe('stopped')
expect(t.h.vercel.snapshotExpirations.get(name)).toBe(104 * 24 * 60 * MIN)
})
it('reports cost from metered compute at the billing rate, plus reported token spend', async () => {
const t = await team()
t.h.advance(90 * MIN)
@@ -44,6 +44,9 @@ export type RowActions = {
/** One-time jump: open the workspace on the chat this teammate has in front. */
goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void
patch: (w: CloudWorkspace, patch: CloudWorkspacePatch) => void
/** Sleep and archive with a snapshot (Undo for 5 s); never just a label. */
archive: (w: CloudWorkspace) => void
unarchive: (w: CloudWorkspace) => void
}
/** Placeholder replaced by the inline section editor in CloudWorkspacesHome. */
@@ -238,12 +241,12 @@ export function CloudWorkspaceRowMenu({
)}
<DropdownMenuSeparator />
{w.archivedAt === null ? (
<DropdownMenuItem onSelect={() => actions.patch(w, { archived: true })}>
<DropdownMenuItem onSelect={() => actions.archive(w)}>
<Archive />
{t('auto.components.cloudWorkspaces.archive', 'Archive')}
</DropdownMenuItem>
) : (
<DropdownMenuItem onSelect={() => actions.patch(w, { archived: false })}>
<DropdownMenuItem onSelect={() => actions.unarchive(w)}>
<ArchiveRestore />
{t('auto.components.cloudWorkspaces.unarchive', 'Unarchive')}
</DropdownMenuItem>
@@ -21,6 +21,7 @@ import { formatSandboxHours, sandboxHours, type MemberDirectory } from './cloud-
import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender'
import { describeError } from './cloud-workspace-errors'
import { focusCloudChat } from './cloud-chat-focus'
import { archiveFromHome, unarchiveFromHome } from './cloud-workspace-home-archive'
import { frontCloudChat } from './cloud-workspace-links'
import {
cloudWorkspaceTitle,
@@ -217,12 +218,6 @@ export function CloudWorkspacesHome({
)
} else if (change.ownerUserId) {
toast.success(t('auto.components.cloudWorkspaces.ownerChanged', 'Owner changed'))
} else if (change.archived !== undefined) {
toast.success(
change.archived
? t('auto.components.cloudWorkspaces.archived', 'Archived')
: t('auto.components.cloudWorkspaces.restored', 'Restored')
)
}
refresh()
},
@@ -238,9 +233,13 @@ export function CloudWorkspacesHome({
},
copyWorkspaceLink: (w: CloudWorkspace) => void copyCloudWorkspaceLink(w.id),
goToChat: (w: CloudWorkspace, member: CloudWorkspacePresence) => void open(w, member.chatId),
patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change)
patch: (w: CloudWorkspace, change: CloudWorkspacePatch) => void patch(w, change),
archive: (w: CloudWorkspace) =>
void archiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh),
unarchive: (w: CloudWorkspace) =>
void unarchiveFromHome(w, cloudWorkspaceTitle(w, t)).finally(refresh)
}),
[open, patch]
[open, patch, refresh, t]
)
// Nothing (not even a skeleton) until we know this build has a control plane and you are in.
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from 'vitest'
vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }))
vi.mock('../orca-cloud/cloud-workspace-actions', () => ({
runArchiveCloudWorkspace: vi.fn(),
runArchiveWithUndo: vi.fn(),
runUnarchiveCloudWorkspace: vi.fn()
}))
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { archiveFromHome, unarchiveFromHome } from './cloud-workspace-home-archive'
const w = { id: 'sbx_1' } as CloudWorkspace
function deps(local: string | null) {
return {
localWorktreeId: vi.fn(async () => local),
patchArchived: vi.fn(async () => ({ ok: true as const, value: {} as never })),
archiveLocal: vi.fn(async () => undefined),
// Commit immediately, as if the Undo window passed.
archiveWithUndo: vi.fn(
async (_key: string, options: { commit: () => Promise<{ ok: boolean }> }) =>
(await options.commit()).ok
),
unarchiveLocal: vi.fn(async () => true)
}
}
describe('archive from the team list', () => {
it('runs the sidebar sleep → archive (with Undo) for a workspace this desktop runs', async () => {
const d = deps('wt-1')
await archiveFromHome(w, 'Fix login', d as never)
expect(d.archiveLocal).toHaveBeenCalledWith('wt-1', { name: 'Fix login' })
expect(d.patchArchived).not.toHaveBeenCalled()
})
it('asks the control plane to archive (it stops the sandbox) for any other workspace, behind the Undo toast', async () => {
const d = deps(null)
await archiveFromHome(w, 'Fix login', d as never)
expect(d.archiveWithUndo).toHaveBeenCalledWith(
'home:sbx_1',
expect.objectContaining({ name: 'Fix login' })
)
expect(d.patchArchived).toHaveBeenCalledWith('sbx_1', true)
expect(d.archiveLocal).not.toHaveBeenCalled()
})
it('unarchives locally (wakes) or through the control plane (stays asleep)', async () => {
const local = deps('wt-1')
await unarchiveFromHome(w, 'Fix login', local as never)
expect(local.unarchiveLocal).toHaveBeenCalledWith('wt-1')
const remote = deps(null)
await unarchiveFromHome(w, 'Fix login', remote as never)
expect(remote.patchArchived).toHaveBeenCalledWith('sbx_1', false)
})
})
@@ -0,0 +1,92 @@
// Archive and unarchive from the team list. Both are lifecycle changes, never just a label:
// a workspace this desktop runs goes through the same Sleep → archive (with Undo) as the sidebar;
// any other one is archived by the control plane, which stops its sandbox and keeps a snapshot.
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import type { CloudWorkspaceResult } from '../../../../shared/hosted-sandbox/cloud-workspace-api'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import {
runArchiveCloudWorkspace,
runArchiveWithUndo,
runUnarchiveCloudWorkspace
} from '../orca-cloud/cloud-workspace-actions'
import { describeError } from './cloud-workspace-errors'
type HomeArchiveDeps = {
localWorktreeId: (sandboxId: string) => Promise<string | null>
patchArchived: (
sandboxId: string,
archived: boolean
) => ReturnType<typeof window.api.cloudWorkspaces.patch>
archiveLocal: typeof runArchiveCloudWorkspace
archiveWithUndo: typeof runArchiveWithUndo
unarchiveLocal: typeof runUnarchiveCloudWorkspace
}
const defaultDeps = (): HomeArchiveDeps => ({
localWorktreeId: async (sandboxId) =>
(await window.api.cloudWorkspaces.localWorkspaces()).find(
(local) => local.sandboxId === sandboxId && local.worktreeId
)?.worktreeId ?? null,
patchArchived: (sandboxId, archived) => window.api.cloudWorkspaces.patch(sandboxId, { archived }),
archiveLocal: runArchiveCloudWorkspace,
archiveWithUndo: runArchiveWithUndo,
unarchiveLocal: runUnarchiveCloudWorkspace
})
function asResult(
result: Awaited<ReturnType<HomeArchiveDeps['patchArchived']>>
): CloudWorkspaceResult<null> {
return result.ok
? { ok: true, value: null }
: {
ok: false,
code: 'failed',
message: describeError(result.error, result.reason, translate)
}
}
export async function archiveFromHome(
w: CloudWorkspace,
name: string,
deps: HomeArchiveDeps = defaultDeps()
): Promise<void> {
const worktreeId = await deps.localWorktreeId(w.id)
if (worktreeId) {
await deps.archiveLocal(worktreeId, { name })
return
}
await deps.archiveWithUndo(`home:${w.id}`, {
name,
commit: async () => asResult(await deps.patchArchived(w.id, true))
})
}
export async function unarchiveFromHome(
w: CloudWorkspace,
name: string,
deps: HomeArchiveDeps = defaultDeps()
): Promise<void> {
const worktreeId = await deps.localWorktreeId(w.id)
if (worktreeId) {
// Same as the sidebar: the disk comes back and the workspace wakes.
await deps.unarchiveLocal(worktreeId)
return
}
const result = await deps.patchArchived(w.id, false)
if (!result.ok) {
toast.error(
translate('orcaCloudWorkspace.unarchiveFailedNamed', 'Couldn’t unarchive {{name}}', { name }),
{
description: describeError(result.error, result.reason, translate)
}
)
return
}
toast.success(translate('orcaCloudWorkspace.unarchivedNamed', 'Unarchived {{name}}', { name }), {
description: translate(
'orcaCloudWorkspace.unarchivedAsleep',
'It’s asleep. Opening it wakes it.'
)
})
}
@@ -9,6 +9,7 @@ import {
showOrcaCloudRestartWarningToast,
showOrcaCloudRestartingToast
} from '@/lib/orca-cloud-session-toasts'
import { runArchiveWithUndo } from './cloud-workspace-actions'
import type { HostedSessionWarningEvent } from '../../../../shared/hosted-sandbox/hosted-session-events'
const workspace = { workspaceId: 'wt-cloud', workspaceName: 'fix-login-flake' }
@@ -82,3 +83,13 @@ export const restartedAfterRestartNow = defineFixture({
export const cleanupInProgress = toastFixture(() => showOrcaCloudCleanupStartedToast('c-1'))
export const cleanupDone = toastFixture(() => showOrcaCloudCleanupDoneToast('c-1'))
export const cleanupFailed = toastFixture(() => showOrcaCloudCleanupFailedToast('c-1', noop))
/** Archive from the sidebar or the team list: the same toast with Undo for 5 s (DS-01). */
export const archivedWithUndo = toastFixture(
() =>
void runArchiveWithUndo('fixture-archive', {
name: workspace.workspaceName,
undoMs: 60_000,
commit: async () => ({ ok: true, value: null })
})
)
@@ -87,57 +87,61 @@ export async function runRestartCloudWorkspace(
export const ARCHIVE_UNDO_MS = 5_000
/**
* Archive with a real undo: nothing happens for 5 s while the toast offers Undo; then the
* workspace sleeps and is archived.
* Archive with a real undo: nothing happens for 5 s while the toast offers Undo; then `commit`
* runs. Used by the sidebar (sleep → archive) and the team list (control-plane archive).
*/
export function runArchiveCloudWorkspace(
workspaceId: string,
options: { name?: string | null; undoMs?: number } = {}
): Promise<void> {
export function runArchiveWithUndo(
key: string,
options: {
name?: string | null
undoMs?: number
commit: () => Promise<CloudWorkspaceResult<null>>
/** False while the workspace is being deleted: its failure is not worth a toast. */
reportFailure?: () => boolean
}
): Promise<boolean> {
return new Promise((resolve) => {
let undone = false
const toastId = `orca-cloud-archive:${workspaceId}`
const toastId = `orca-cloud-archive:${key}`
const cancel = (): void => {
undone = true
clearTimeout(commit)
toast.dismiss(toastId)
unregister()
resolve()
resolve(false)
}
const commit = setTimeout(() => {
unregister()
toast.dismiss(toastId)
if (undone) {
resolve()
resolve(false)
return
}
// A Delete that starts while this runs destroys the sandbox; its sleep and archive then fail
// for a workspace that is going away, which is not worth an error toast.
const sleep = (id: string): Promise<unknown> =>
isCloudWorkspaceDeleting(id) ? Promise.resolve() : runSleepWorktree(id)
void archiveCloudWorkspace(workspaceId, { sleep }).then((result) => {
if (!isCloudWorkspaceDeleting(workspaceId)) {
void options.commit().then((result) => {
if (options.reportFailure?.() ?? true) {
failureToast(
translate('orcaCloudWorkspace.archiveFailed', 'Couldn’t archive the workspace'),
options.name
? translate('orcaCloudWorkspace.archiveFailedNamed', 'Couldn’t archive {{name}}', {
name: options.name
})
: translate('orcaCloudWorkspace.archiveFailed', 'Couldn’t archive the workspace'),
result
)
}
resolve()
resolve(result.ok)
})
}, options.undoMs ?? ARCHIVE_UNDO_MS)
const unregister = registerQueuedCloudArchive(workspaceId, cancel)
const unregister = registerQueuedCloudArchive(key, cancel)
toast(
options.name
? translate('orcaCloudWorkspace.archivingNamed', 'Archiving {{name}}…', {
name: options.name
})
: translate('orcaCloudWorkspace.archiving', 'Archiving workspace…'),
? translate('orcaCloudWorkspace.archivedNamed', 'Archived {{name}}', { name: options.name })
: translate('orcaCloudWorkspace.archivedWorkspace', 'Archived the workspace'),
{
id: toastId,
duration: options.undoMs ?? ARCHIVE_UNDO_MS,
description: translate(
'orcaCloudWorkspace.archivingDetail',
'It stops and stays browsable: PRs, last changes and files.'
'It goes to sleep and stays browsable: PRs, last changes and files.'
),
action: {
label: translate('orcaCloudWorkspace.undo', 'Undo'),
@@ -148,6 +152,22 @@ export function runArchiveCloudWorkspace(
})
}
/** Sidebar archive: the ordinary Sleep, then the control-plane archive, behind the Undo toast. */
export async function runArchiveCloudWorkspace(
workspaceId: string,
options: { name?: string | null; undoMs?: number } = {}
): Promise<void> {
// A Delete that starts while this runs destroys the sandbox; its sleep and archive then fail
// for a workspace that is going away, which is not worth an error toast.
const sleep = (id: string): Promise<readonly { completed: boolean }[] | void> =>
isCloudWorkspaceDeleting(id) ? Promise.resolve() : runSleepWorktree(id)
await runArchiveWithUndo(workspaceId, {
...options,
commit: () => archiveCloudWorkspace(workspaceId, { sleep }),
reportFailure: () => !isCloudWorkspaceDeleting(workspaceId)
})
}
/** Resolves true once unarchived and woken; a failure has already shown its toast. */
export async function runUnarchiveCloudWorkspace(workspaceId: string): Promise<boolean> {
const result = await unarchiveCloudWorkspace(workspaceId, {
@@ -58,7 +58,8 @@ export function restartCloudWorkspace(workspaceId: string): Promise<CloudWorkspa
export function archiveCloudWorkspace(
workspaceId: string,
deps: {
sleep: (workspaceId: string) => Promise<unknown>
/** The ordinary Sleep; a result whose workspaces did not all sleep stops the archive. */
sleep: (workspaceId: string) => Promise<readonly { completed: boolean }[] | void>
pullRequests?: HostedArchivePullRequest[]
}
): Promise<CloudWorkspaceResult<null>> {
@@ -67,7 +68,18 @@ export function archiveCloudWorkspace(
return Promise.resolve(unavailable())
}
return withPending(workspaceId, 'archive', async () => {
await deps.sleep(workspaceId)
const slept = await deps.sleep(workspaceId)
if (slept && !slept.every((result) => result.completed)) {
// Never archive a sandbox that is still running: it would keep using hours behind an "Archived" label.
return {
ok: false,
code: 'failed',
message: translate(
'auto.lib.orcaCloud.workspaceActions.archiveSleepFailed',
'It’s still running. Your files are safe.'
)
}
}
return bridge.archive({
workspaceId,
...(deps.pullRequests?.length ? { pullRequests: deps.pullRequests } : {})
@@ -104,6 +104,16 @@ describe('orca cloud workspace store', () => {
expect(getCloudWorkspaceSnapshot().pending.a).toBeUndefined()
})
it('does not archive when the sleep did not finish (the sandbox would keep running)', async () => {
const bridge = stubApi()
const result = await archiveCloudWorkspace('a', {
sleep: async () => [{ completed: false }]
})
expect(result).toMatchObject({ ok: false, code: 'failed' })
expect(bridge.archive).not.toHaveBeenCalled()
expect(getCloudWorkspaceSnapshot().pending.a).toBeUndefined()
})
it('unarchives, clears the archived status, then runs the wake path', async () => {
stubApi()
seedCloudWorkspaceSnapshot({