From a8179682e691f6b6eda09ddd74764b2cae3de839 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 23:08:50 -0800 Subject: [PATCH] feat(cli): always show cloud wake, sleep and --on cloud create progress MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit W10 wake-visibility P1s. stderr '- …' lines (NDJSON phase events with --progress json; --json defaults to none; stdout keeps only the result): - wake: 'Waking ...', one 'Still waking (Ns)…' line at 10 s, ' is awake (took Ns).', or, when the API answers still waking after its wait, ' is still waking. Check with: …' (exit 0, status waking kept in the result) - sleep: 'Putting to sleep...' / ' is asleep (took Ns).' - worktree create --on cloud: 'Still starting (Ns)…' at 10 s and 'Workspace is running (took Ns).' Lifecycle handler moved to cloud-lifecycle.ts; shared helper cloud-progress.ts. --- src/cli/cloud/cloud-handlers.ts | 20 +-- src/cli/cloud/cloud-lifecycle.ts | 71 +++++++++ src/cli/cloud/cloud-progress.test.ts | 175 ++++++++++++++++++++++ src/cli/cloud/cloud-progress.ts | 64 ++++++++ src/cli/cloud/cloud-specs.ts | 15 +- src/cli/cloud/worktree-create-on-cloud.ts | 36 ++--- 6 files changed, 342 insertions(+), 39 deletions(-) create mode 100644 src/cli/cloud/cloud-lifecycle.ts create mode 100644 src/cli/cloud/cloud-progress.test.ts create mode 100644 src/cli/cloud/cloud-progress.ts diff --git a/src/cli/cloud/cloud-handlers.ts b/src/cli/cloud/cloud-handlers.ts index 15755a02c1a..8ea221b5079 100644 --- a/src/cli/cloud/cloud-handlers.ts +++ b/src/cli/cloud/cloud-handlers.ts @@ -33,7 +33,6 @@ import { } from './cloud-format' import { DEFAULT_MESSAGE_WAIT_S, - MUTATE_TIMEOUT_MS, cloudClient, createCloudWorkspace, defaultCloudHandlerDeps, @@ -49,27 +48,14 @@ import { type CloudWorkspaceCreateInput } from './cloud-operations' +import { cloudLifecycleHandler, type CloudLifecycleAction } from './cloud-lifecycle' + export type { CloudHandlerDeps } from './cloud-operations' export function createCloudHandlers( getDeps: () => CloudHandlerDeps = defaultCloudHandlerDeps ): Record { - const mutate = - (action: 'sleep' | 'wake' | 'archive' | 'destroy'): CommandHandler => - async ({ flags, json }) => { - const deps = getDeps() - const api = cloudClient(deps) - const id = await resolveCloudWorkspaceId(api, getRequiredStringFlag(flags, 'workspace')) - const started = deps.now() - const result = await api.request<{ workspace: CloudWorkspace }>( - action === 'destroy' ? 'DELETE' : 'POST', - action === 'destroy' ? workspacePath(id) : workspacePath(id, `/${action}`), - { timeoutMs: MUTATE_TIMEOUT_MS } - ) - printCloudResult({ ...result, elapsedMs: deps.now() - started }, json, (value) => - formatCloudWorkspace(value) - ) - } + const mutate = (action: CloudLifecycleAction) => cloudLifecycleHandler(action, getDeps) return { 'cloud whoami': async ({ json }) => { diff --git a/src/cli/cloud/cloud-lifecycle.ts b/src/cli/cloud/cloud-lifecycle.ts new file mode 100644 index 00000000000..173bbd143c4 --- /dev/null +++ b/src/cli/cloud/cloud-lifecycle.ts @@ -0,0 +1,71 @@ +// Private build only: `orca cloud workspace sleep|wake|archive|destroy`. Wake and sleep show +// progress on stderr (see cloud-progress.ts) so a multi-second wait is never silent. +import type { CommandHandler } from '../dispatch' +import { getRequiredStringFlag } from '../flags' +import { formatCloudWorkspace, printCloudResult, type CloudWorkspace } from './cloud-format' +import { + MUTATE_TIMEOUT_MS, + cloudClient, + resolveCloudWorkspaceId, + workspacePath, + type CloudHandlerDeps +} from './cloud-operations' +import { cloudProgress, readCloudProgressMode } from './cloud-progress' + +export type CloudLifecycleAction = 'sleep' | 'wake' | 'archive' | 'destroy' + +export function cloudLifecycleHandler( + action: CloudLifecycleAction, + getDeps: () => CloudHandlerDeps +): CommandHandler { + return async ({ flags, json }) => { + const deps = getDeps() + const selector = getRequiredStringFlag(flags, 'workspace') + // Waking and sleeping take seconds: always show that something is happening (stderr). + const shown = action === 'wake' || action === 'sleep' + const progress = cloudProgress(shown ? readCloudProgressMode(flags, json) : 'none') + const api = cloudClient(deps) + const id = await resolveCloudWorkspaceId(api, selector) + if (action === 'wake') { + progress.phase('waking', `Waking ${selector}...`, { workspaceId: id }) + } else if (action === 'sleep') { + progress.phase('sleeping', `Putting ${selector} to sleep...`, { workspaceId: id }) + } + const started = deps.now() + const request = api.request<{ workspace: CloudWorkspace; state?: string }>( + action === 'destroy' ? 'DELETE' : 'POST', + action === 'destroy' ? workspacePath(id) : workspacePath(id, `/${action}`), + { timeoutMs: MUTATE_TIMEOUT_MS } + ) + const result = + action === 'wake' + ? await progress.track( + request, + (s) => `Still waking (${s}s). This is taking longer than usual; your files are safe.` + ) + : await request + const name = result.workspace.name || selector + // The API's wake waits ~30 s; past that it answers `waking` and keeps going in the background. + const stillWaking = + action === 'wake' && (result.state === 'waking' || result.workspace.status === 'waking') + if (stillWaking) { + result.workspace = { ...result.workspace, status: 'waking' } + progress.phase( + 'still-waking', + `${name} is still waking. Check with: orca cloud workspace show ${id}`, + { workspaceId: id } + ) + } else if (action === 'wake') { + progress.phase('awake', `${name} is awake (took ${progress.elapsedSeconds()}s).`, { + workspaceId: id + }) + } else if (action === 'sleep') { + progress.phase('asleep', `${name} is asleep (took ${progress.elapsedSeconds()}s).`, { + workspaceId: id + }) + } + printCloudResult({ ...result, elapsedMs: deps.now() - started }, json, (value) => + formatCloudWorkspace(value) + ) + } +} diff --git a/src/cli/cloud/cloud-progress.test.ts b/src/cli/cloud/cloud-progress.test.ts new file mode 100644 index 00000000000..85c2ba2ebb9 --- /dev/null +++ b/src/cli/cloud/cloud-progress.test.ts @@ -0,0 +1,175 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { HandlerContext } from '../dispatch' +import { nodeCloudCredentialFs } from './cloud-credentials' +import { createCloudHandlers } from './cloud-handlers' +import type { CloudHandlerDeps } from './cloud-operations' +import { createWorktreeOnCloud, type CloudOnDeps } from './worktree-create-on-cloud' + +let home: string +let stdout: string[] +let stderr: string[] + +beforeEach(() => { + vi.useFakeTimers({ now: 1_000_000 }) + home = mkdtempSync(join(tmpdir(), 'orca-cloud-progress-')) + stdout = [] + stderr = [] + vi.spyOn(console, 'log').mockImplementation((line: unknown) => void stdout.push(String(line))) + vi.spyOn(console, 'error').mockImplementation((line: unknown) => void stderr.push(String(line))) + vi.spyOn(process.stderr, 'write').mockImplementation((chunk: string | Uint8Array) => { + stderr.push(String(chunk).trimEnd()) + return true + }) +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + rmSync(home, { recursive: true, force: true }) +}) + +const workspace = (status: string) => ({ + id: 'sbx_ab12', + name: 'child', + status, + origin: 'api', + machineSize: 'standard', + archived: false +}) + +/** A fetch that answers after `delayMs` of (fake) time. */ +function slowFetch(delayMs: number, body: unknown, status = 200) { + return vi.fn( + () => + new Promise((resolve) => { + // ast-grep-ignore: test-no-real-time-wait -- fake timers drive this delay (vi.useFakeTimers in beforeEach) + setTimeout(() => resolve(Response.json(body, { status })), delayMs) + }) + ) +} + +function deps(fetchImpl: CloudHandlerDeps['fetch']): CloudOnDeps { + return { + env: { ORCA_CLOUD_TOKEN: 'orca_sk_x', ORCA_CLOUD_API_URL: 'https://cloud.test' }, + fetch: fetchImpl, + fs: nodeCloudCredentialFs, + home, + now: () => Date.now(), + sleep: async () => {}, + readStdin: async () => null, + originUrl: () => null + } +} + +function ctx(flags: Record, json = false): HandlerContext { + return { + flags: new Map(Object.entries(flags)), + cwd: home, + json, + // Cloud commands must never reach the Orca runtime. + get client(): never { + throw new Error('cloud commands must not use the runtime client') + } + } +} + +async function run(promise: Promise, advanceMs: number): Promise { + await vi.advanceTimersByTimeAsync(advanceMs) + return promise +} + +describe('orca cloud workspace wake progress', () => { + it('says it is waking, then awake with the time it took', async () => { + const handlers = createCloudHandlers(() => + deps(slowFetch(4800, { workspace: workspace('running'), state: 'running' })) + ) + await run(handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12' })), 5000) + expect(stderr).toEqual(['- Waking sbx_ab12...', '- child is awake (took 4.8s).']) + expect(stdout.join('\n')).toContain('status: running') + }) + + it('adds one reassurance line at 10 s', async () => { + const handlers = createCloudHandlers(() => + deps(slowFetch(14_000, { workspace: workspace('running'), state: 'running' })) + ) + await run(handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12' })), 15_000) + expect(stderr).toEqual([ + '- Waking sbx_ab12...', + '- Still waking (10s). This is taking longer than usual; your files are safe.', + '- child is awake (took 14.0s).' + ]) + }) + + it('exits 0 with status waking when the API is still waking after its wait', async () => { + const handlers = createCloudHandlers(() => + deps(slowFetch(30_000, { workspace: workspace('sleeping'), state: 'waking' })) + ) + await run(handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12' }, true)), 31_000) + expect(stderr).toEqual([]) // --json defaults progress to none + expect(JSON.parse(stdout.join(''))).toMatchObject({ + ok: true, + result: { state: 'waking', workspace: { status: 'waking' } } + }) + + stderr.length = 0 + await run(handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12' })), 31_000) + expect(stderr.at(-1)).toBe( + '- child is still waking. Check with: orca cloud workspace show sbx_ab12' + ) + }) + + it('writes NDJSON phase events with --progress json and keeps stdout to the result', async () => { + const handlers = createCloudHandlers(() => + deps(slowFetch(1000, { workspace: workspace('running'), state: 'running' })) + ) + await run( + handlers['cloud workspace wake'](ctx({ workspace: 'sbx_ab12', progress: 'json' }, true)), + 2000 + ) + expect(stderr.map((line) => JSON.parse(line).phase)).toEqual(['waking', 'awake']) + expect(JSON.parse(stderr[1])).toMatchObject({ + event: 'phase', + workspaceId: 'sbx_ab12', + elapsedMs: 1000 + }) + expect(JSON.parse(stdout.join('')).ok).toBe(true) + }) + + it('shows sleep too', async () => { + const handlers = createCloudHandlers(() => + deps(slowFetch(2000, { workspace: workspace('sleeping') })) + ) + await run(handlers['cloud workspace sleep'](ctx({ workspace: 'sbx_ab12' })), 3000) + expect(stderr).toEqual(['- Putting sbx_ab12 to sleep...', '- child is asleep (took 2.0s).']) + }) +}) + +describe('worktree create --on cloud progress', () => { + it('prints a 10 s line and the elapsed time when the workspace is up', async () => { + const created = slowFetch(12_000, { workspace: workspace('running') }, 201) + await run( + createWorktreeOnCloud(ctx({ on: 'cloud', name: 'child' }), () => deps(created)), + 13_000 + ) + expect(stderr).toEqual([ + '- Creating an Orca Cloud workspace...', + '- Still starting (10s). This is taking longer than usual; your files are safe.', + '- Workspace sbx_ab12 is running (took 12.0s).' + ]) + }) + + it('stays quiet before 10 s', async () => { + const created = slowFetch(6000, { workspace: workspace('running') }, 201) + await run( + createWorktreeOnCloud(ctx({ on: 'cloud', name: 'child' }), () => deps(created)), + 7000 + ) + expect(stderr).toEqual([ + '- Creating an Orca Cloud workspace...', + '- Workspace sbx_ab12 is running (took 6.0s).' + ]) + }) +}) diff --git a/src/cli/cloud/cloud-progress.ts b/src/cli/cloud/cloud-progress.ts new file mode 100644 index 00000000000..db9013e5b14 --- /dev/null +++ b/src/cli/cloud/cloud-progress.ts @@ -0,0 +1,64 @@ +// Private build only: progress lines on stderr for slow Orca Cloud calls (create, wake, sleep), so +// a wait is always visible. Text mode prints "- …" lines; json mode prints NDJSON phase events; +// stdout keeps only the result. No spinners: stderr is often not a TTY. +import { RuntimeClientError } from '../runtime/types' + +export type CloudProgressMode = 'text' | 'json' | 'none' + +/** Long waits get one reassurance line at this point. */ +export const CLOUD_SLOW_NOTICE_MS = 10_000 + +export function readCloudProgressMode( + flags: Map, + json: boolean +): CloudProgressMode { + const value = flags.get('progress') ?? (json ? 'none' : 'text') + if (value !== 'text' && value !== 'json' && value !== 'none') { + throw new RuntimeClientError( + 'invalid_argument', + '--progress must be one of: text, json, none', + { + field: 'progress' + } + ) + } + return value +} + +export type CloudProgress = { + phase: (name: string, text: string, extra?: Record) => void + /** Runs `work`; if it is still running after CLOUD_SLOW_NOTICE_MS, prints one `slow` line. */ + track: (work: Promise, slowText: (seconds: number) => string) => Promise + elapsedSeconds: () => string +} + +export function cloudProgress( + mode: CloudProgressMode, + now: () => number = Date.now +): CloudProgress { + const started = now() + const phase: CloudProgress['phase'] = (name, text, extra = {}) => { + if (mode === 'json') { + process.stderr.write( + `${JSON.stringify({ event: 'phase', phase: name, at: now(), elapsedMs: now() - started, ...extra })}\n` + ) + } else if (mode === 'text') { + console.error(`- ${text}`) + } + } + return { + phase, + elapsedSeconds: () => ((now() - started) / 1000).toFixed(1), + track: async (work, slowText) => { + const timer = setTimeout(() => { + phase('slow', slowText(Math.round((now() - started) / 1000))) + }, CLOUD_SLOW_NOTICE_MS) + timer.unref?.() + try { + return await work + } finally { + clearTimeout(timer) + } + } + } +} diff --git a/src/cli/cloud/cloud-specs.ts b/src/cli/cloud/cloud-specs.ts index f05ee64ecde..c1cf2ddd436 100644 --- a/src/cli/cloud/cloud-specs.ts +++ b/src/cli/cloud/cloud-specs.ts @@ -9,6 +9,8 @@ const WORKSPACE_ARG_NOTE = const JSON_NOTE = '--json prints { ok, schemaVersion: 1, result }; failures print { ok: false, error: { code, message, data } }.' +const PROGRESS_ACTIONS: ReadonlySet = new Set(['sleep', 'wake']) + const lifecycle = ( action: 'sleep' | 'wake' | 'archive' | 'destroy', summary: string, @@ -16,12 +18,21 @@ const lifecycle = ( ): CommandSpec => ({ path: ['cloud', 'workspace', action], summary, - usage: `orca cloud workspace ${action} [--json]`, - allowedFlags: [...LOCAL_COMMAND_FLAGS, 'workspace'], + usage: `orca cloud workspace ${action} ${PROGRESS_ACTIONS.has(action) ? ' [--progress text|json|none]' : ''} [--json]`, + allowedFlags: [ + ...LOCAL_COMMAND_FLAGS, + 'workspace', + ...(PROGRESS_ACTIONS.has(action) ? ['progress'] : []) + ], positionalArgs: ['workspace'], ...(action === 'destroy' ? { destructive: true } : {}), notes: [ ...notes, + ...(PROGRESS_ACTIONS.has(action) + ? [ + 'Progress goes to stderr as "- ..." lines (--progress json: NDJSON phase events; --json defaults to none). stdout carries only the result.' + ] + : []), WORKSPACE_ARG_NOTE, 'A workspace token cannot sleep, archive or destroy its own workspace.' ], diff --git a/src/cli/cloud/worktree-create-on-cloud.ts b/src/cli/cloud/worktree-create-on-cloud.ts index 46fc0693fe0..3a69959aa79 100644 --- a/src/cli/cloud/worktree-create-on-cloud.ts +++ b/src/cli/cloud/worktree-create-on-cloud.ts @@ -11,6 +11,7 @@ import type { HandlerContext } from '../dispatch' import { getOptionalStringFlag } from '../flags' import { RuntimeClientError } from '../runtime/types' import { formatCloudWorkspace, printCloudResult } from './cloud-format' +import { cloudProgress, readCloudProgressMode } from './cloud-progress' import { CLOUD_AGENTS, cloudClient, @@ -154,16 +155,7 @@ export async function createWorktreeOnCloud( field: 'agent' }) } - const progress = flags.get('progress') ?? (json ? 'none' : 'text') - if (progress !== 'text' && progress !== 'json' && progress !== 'none') { - throw new RuntimeClientError( - 'invalid_argument', - '--progress must be one of: text, json, none', - { - field: 'progress' - } - ) - } + const progress = readCloudProgressMode(flags, json) const deps = getDeps() const machineSize = getSizeFlag(flags) const ref = getOptionalStringFlag(flags, 'base-branch') @@ -195,16 +187,20 @@ export async function createWorktreeOnCloud( ...(machineSize ? { machineSize } : {}), ...(prompt && agent ? { message: { text: prompt, agent } } : {}) } - const phase = (name: string, text: string) => { - if (progress === 'json') { - process.stderr.write(`${JSON.stringify({ event: 'phase', phase: name, at: deps.now() })}\n`) - } else if (progress === 'text') { - console.error(`- ${text}`) - } - } - phase('create', `Creating an Orca Cloud workspace${repo ? ` from ${repo.url}` : ''}...`) - const created = await createCloudWorkspace(api, input, deps.now) - phase('ready', `Workspace ${created.workspace.id} is ${created.workspace.status}.`) + const progressLines = cloudProgress(progress) + progressLines.phase( + 'create', + `Creating an Orca Cloud workspace${repo ? ` from ${repo.url}` : ''}...` + ) + const created = await progressLines.track( + createCloudWorkspace(api, input, deps.now), + (s) => `Still starting (${s}s). This is taking longer than usual; your files are safe.` + ) + progressLines.phase( + 'ready', + `Workspace ${created.workspace.id} is ${created.workspace.status} (took ${progressLines.elapsedSeconds()}s).`, + { workspaceId: created.workspace.id } + ) printCloudResult( { ...created,