mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Merge pull request #93 from nwparker/cloud/lint-fix
fix(cloud-integration): lint + typecheck green on HEAD; premerge gate
This commit is contained in:
@@ -264,5 +264,19 @@
|
||||
"text": "text-[13px] leading-5",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/cloud-environment/cloud-environment-fixture-data.ts",
|
||||
"kind": "object-property:error",
|
||||
"text": "install_failed",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "src/renderer/src/components/cloud-environment/cloud-environment-fixture-data.ts",
|
||||
"kind": "object-property:error",
|
||||
"text": "canceled",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
}
|
||||
]
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Gate for merging into cloud/integration (no CI on nwparker/orca-private): run from your branch's clone.
|
||||
# Merges the current private/cloud/integration into a throwaway worktree with your branch, then requires
|
||||
# typecheck, the full lint suite (pre-commit hooks only lint staged files) and the tests your branch changed.
|
||||
set -euo pipefail
|
||||
branch=$(git rev-parse --abbrev-ref HEAD)
|
||||
git fetch -q private +cloud/integration:refs/remotes/private/cloud/integration
|
||||
dir=$(mktemp -d "${TMPDIR:-/tmp}/cloud-premerge-XXXX")
|
||||
trap 'git worktree remove --force "$dir" >/dev/null 2>&1 || true' EXIT
|
||||
git worktree add -q --detach "$dir" HEAD
|
||||
cd "$dir"
|
||||
git merge -q --no-edit private/cloud/integration
|
||||
pnpm install --frozen-lockfile >/dev/null
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
tests=$(git diff --name-only --diff-filter=AM private/cloud/integration...HEAD -- 'src/*.test.ts' 'src/*.test.tsx' | tr '\n' ' ')
|
||||
if [[ -n "$tests" ]]; then
|
||||
node config/scripts/native-build/node-addons/ensure-native-runtime.mjs --runtime=node >/dev/null
|
||||
npx vitest run --config config/vitest.config.ts $tests
|
||||
fi
|
||||
for app in $(git diff --name-only private/cloud/integration...HEAD -- cloud/apps | cut -d/ -f1-3 | sort -u); do
|
||||
(cd "$app" && npx vitest run)
|
||||
done
|
||||
echo "premerge OK: $branch merges cleanly into cloud/integration with typecheck, lint and tests green."
|
||||
@@ -27,6 +27,17 @@ function client(fetchImpl: typeof fetch, getAccessToken = async () => 'tok_secre
|
||||
})
|
||||
}
|
||||
|
||||
async function cloudApiErrorOf(promise: Promise<unknown>): Promise<CloudApiError> {
|
||||
const caught = await promise.then(
|
||||
() => null,
|
||||
(error: unknown) => error
|
||||
)
|
||||
if (!(caught instanceof CloudApiError)) {
|
||||
throw new Error(`expected a CloudApiError, got ${String(caught)}`)
|
||||
}
|
||||
return caught
|
||||
}
|
||||
|
||||
async function codeOf(promise: Promise<unknown>): Promise<string> {
|
||||
try {
|
||||
await promise
|
||||
@@ -41,45 +52,48 @@ async function codeOf(promise: Promise<unknown>): Promise<string> {
|
||||
|
||||
describe('createCloudApiClient', () => {
|
||||
it('sends the bearer token, JSON body and query, and validates the answer', async () => {
|
||||
const fetchImpl = vi.fn(async () =>
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
respond(200, { keys: [KEY], availableScopes: ['audit:read'] })
|
||||
)
|
||||
const keys = await client(fetchImpl as unknown as typeof fetch).listApiKeys()
|
||||
const keys = await client(fetchImpl).listApiKeys()
|
||||
expect(keys.keys[0]?.prefix).toBe('orca_sk_Ab3x')
|
||||
// Unknown scopes from a newer server are dropped, not fatal.
|
||||
expect(keys.keys[0]?.scopes).toEqual(['workspaces:read'])
|
||||
const [url, init] = fetchImpl.mock.calls[0] as unknown as [string, RequestInit]
|
||||
const [url, init] = fetchImpl.mock.calls[0] ?? []
|
||||
expect(url).toBe('https://cp.example.dev/v1/api-keys')
|
||||
expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok_secret')
|
||||
expect(init.redirect).toBe('error')
|
||||
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer tok_secret')
|
||||
expect(init?.redirect).toBe('error')
|
||||
|
||||
const created = vi.fn(async () =>
|
||||
const created = vi.fn<typeof fetch>(async () =>
|
||||
respond(201, { key: KEY, secret: `orca_sk_${'a'.repeat(32)}` })
|
||||
)
|
||||
await client(created as unknown as typeof fetch).createApiKey({
|
||||
await client(created).createApiKey({
|
||||
name: 'CI',
|
||||
scopes: ['workspaces:read']
|
||||
})
|
||||
const [, createInit] = created.mock.calls[0] ?? []
|
||||
expect(createInit?.method).toBe('POST')
|
||||
expect(JSON.parse(String(createInit?.body))).toEqual({
|
||||
name: 'CI',
|
||||
scopes: ['workspaces:read']
|
||||
})
|
||||
const [, createInit] = created.mock.calls[0] as unknown as [string, RequestInit]
|
||||
expect(createInit.method).toBe('POST')
|
||||
expect(JSON.parse(String(createInit.body))).toEqual({ name: 'CI', scopes: ['workspaces:read'] })
|
||||
|
||||
const runs = vi.fn(async () => respond(200, { runs: [], nextBefore: null }))
|
||||
await client(runs as unknown as typeof fetch).listRoutineRuns('rt/1', { limit: 20, before: 99 })
|
||||
expect((runs.mock.calls[0] as unknown as [string])[0]).toBe(
|
||||
const runs = vi.fn<typeof fetch>(async () => respond(200, { runs: [], nextBefore: null }))
|
||||
await client(runs).listRoutineRuns('rt/1', { limit: 20, before: 99 })
|
||||
expect(runs.mock.calls[0]?.[0]).toBe(
|
||||
'https://cp.example.dev/v1/routines/rt%2F1/runs?limit=20&before=99'
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a malformed answer as invalid-response', async () => {
|
||||
const fetchImpl = vi.fn(async () => respond(200, { keys: 'nope' }))
|
||||
expect(await codeOf(client(fetchImpl as unknown as typeof fetch).listApiKeys())).toBe(
|
||||
'invalid-response'
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => respond(200, { keys: 'nope' }))
|
||||
expect(await codeOf(client(fetchImpl).listApiKeys())).toBe('invalid-response')
|
||||
const badSecret = vi.fn<typeof fetch>(async () =>
|
||||
respond(201, { key: KEY, secret: 'not-a-key' })
|
||||
)
|
||||
const badSecret = vi.fn(async () => respond(201, { key: KEY, secret: 'not-a-key' }))
|
||||
expect(
|
||||
await codeOf(
|
||||
client(badSecret as unknown as typeof fetch).createApiKey({
|
||||
client(badSecret).createApiKey({
|
||||
name: 'x',
|
||||
scopes: ['audit:read']
|
||||
})
|
||||
@@ -88,51 +102,44 @@ describe('createCloudApiClient', () => {
|
||||
})
|
||||
|
||||
it('maps network and token failures without leaking the token', async () => {
|
||||
const offline = vi.fn(async () => {
|
||||
const offline = vi.fn<typeof fetch>(async () => {
|
||||
throw new TypeError('fetch failed tok_secret')
|
||||
})
|
||||
const error = await client(offline as unknown as typeof fetch)
|
||||
.me()
|
||||
.catch((caught: unknown) => caught)
|
||||
expect(error).toBeInstanceOf(CloudApiError)
|
||||
expect((error as CloudApiError).code).toBe('network')
|
||||
expect(String((error as CloudApiError).message)).not.toContain('tok_secret')
|
||||
const error = await cloudApiErrorOf(client(offline).me())
|
||||
expect(error.code).toBe('network')
|
||||
expect(error.message).not.toContain('tok_secret')
|
||||
|
||||
const noToken = client(vi.fn() as unknown as typeof fetch, async () => {
|
||||
const noToken = client(vi.fn<typeof fetch>(), async () => {
|
||||
throw new Error('signed out')
|
||||
})
|
||||
expect(await codeOf(noToken.me())).toBe('signed-out')
|
||||
})
|
||||
|
||||
it('treats a missing routines route as not-available but a missing routine as not-found', async () => {
|
||||
const missing = vi.fn(async () => respond(404, { error: 'not_found' }))
|
||||
const c = client(missing as unknown as typeof fetch)
|
||||
const missing = vi.fn<typeof fetch>(async () => respond(404, { error: 'not_found' }))
|
||||
const c = client(missing)
|
||||
expect(await codeOf(c.listRoutines())).toBe('not-available')
|
||||
expect(await codeOf(c.getRoutine('rt_1'))).toBe('not-found')
|
||||
})
|
||||
|
||||
it('carries retry-after on rate limits and accepts empty DELETE bodies', async () => {
|
||||
const limited = vi.fn(async () =>
|
||||
const limited = vi.fn<typeof fetch>(async () =>
|
||||
respond(429, { error: 'rate_limited' }, { 'retry-after': '7' })
|
||||
)
|
||||
const error = (await client(limited as unknown as typeof fetch)
|
||||
.listApiKeys()
|
||||
.catch((caught: unknown) => caught)) as CloudApiError
|
||||
const error = await cloudApiErrorOf(client(limited).listApiKeys())
|
||||
expect(error.code).toBe('rate-limited')
|
||||
expect(error.retryAfterSeconds).toBe(7)
|
||||
|
||||
const deleted = vi.fn(async () => new Response(null, { status: 200 }))
|
||||
await expect(
|
||||
client(deleted as unknown as typeof fetch).revokeApiKey('key_1')
|
||||
).resolves.toBeUndefined()
|
||||
const deleted = vi.fn<typeof fetch>(async () => new Response(null, { status: 200 }))
|
||||
await expect(client(deleted).revokeApiKey('key_1')).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('response hardening', () => {
|
||||
it('keeps a freshly minted secret even if the key metadata drifted', async () => {
|
||||
const secret = `orca_sk_${'b'.repeat(32)}`
|
||||
const fetchImpl = vi.fn(async () => respond(201, { key: { id: 7 }, secret }))
|
||||
const created = await client(fetchImpl as unknown as typeof fetch).createApiKey({
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => respond(201, { key: { id: 7 }, secret }))
|
||||
const created = await client(fetchImpl).createApiKey({
|
||||
name: 'x',
|
||||
scopes: ['workspaces:read']
|
||||
})
|
||||
@@ -154,9 +161,9 @@ describe('response hardening', () => {
|
||||
finishedAt: 2,
|
||||
durationMs: 1
|
||||
}
|
||||
const fetchImpl = vi.fn(async () => respond(202, { run }))
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => respond(202, { run }))
|
||||
// A bad link is dropped, never opened, and doesn't fail the whole response.
|
||||
const { run: parsed } = await client(fetchImpl as unknown as typeof fetch).runRoutine('rt_1')
|
||||
const { run: parsed } = await client(fetchImpl).runRoutine('rt_1')
|
||||
expect(parsed.result?.prUrl).toBeUndefined()
|
||||
expect(parsed.status).toBe('succeeded')
|
||||
})
|
||||
|
||||
@@ -61,10 +61,12 @@ function readServerError(body: unknown): { error?: string; reason?: string } {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return {}
|
||||
}
|
||||
const record = body as Record<string, unknown>
|
||||
const pick = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value.slice(0, MAX_DETAIL_CHARS) : undefined
|
||||
return { error: pick(record.error), reason: pick(record.reason) }
|
||||
return {
|
||||
error: pick('error' in body ? body.error : undefined),
|
||||
reason: pick('reason' in body ? body.reason : undefined)
|
||||
}
|
||||
}
|
||||
|
||||
/** Maps a non-2xx control-plane answer to a stable code the renderer can word. */
|
||||
|
||||
@@ -40,6 +40,7 @@ function call<A extends unknown[]>(
|
||||
}
|
||||
parsed.push(result.data)
|
||||
}
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: parsed[i] is schemas[i]'s output and schemas is typed per A[i]; TS cannot prove a tuple built in a loop.
|
||||
return callCloudApi((client) => run(client, ...(parsed as A)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function checkSetup(
|
||||
if (!script) {
|
||||
if (
|
||||
context.checkout.kind === 'checkout' &&
|
||||
hasEnvironmentBuildMarker(context.checkout.commonDir, context.root)
|
||||
(await hasEnvironmentBuildMarker(context.checkout.commonDir, context.root))
|
||||
) {
|
||||
return [
|
||||
check(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Queued prompts on disk: sealed with the OS keychain; without one they live in memory only.
|
||||
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import type { CloudQueuedPrompt } from '../../shared/hosted-sandbox/cloud-workspace-offline-api'
|
||||
import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope'
|
||||
import type { OfflineCacheCodec } from './cloud-offline-cache'
|
||||
@@ -13,38 +14,103 @@ export type StoredPrompt = CloudQueuedPrompt & {
|
||||
nextAttemptAt: number
|
||||
}
|
||||
|
||||
export function readSealedPrompts(path: string, codec: OfflineCacheCodec | null): StoredPrompt[] {
|
||||
// The sealed file is ours, but only its shape is checked here; a prompt that does not match is dropped.
|
||||
const StoredPromptSchema = z.looseObject({
|
||||
id: z.string(),
|
||||
clientOperationId: z.string(),
|
||||
workspaceId: z.string(),
|
||||
sessionId: z.string(),
|
||||
text: z.string(),
|
||||
state: z.enum(['queued', 'sending', 'delivered', 'failed', 'unconfirmed']),
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
failures: z.number(),
|
||||
nextAttemptAt: z.number(),
|
||||
error: z.string().optional()
|
||||
})
|
||||
const SealedQueueSchema = z.object({ version: z.literal(2), prompts: z.array(z.unknown()) })
|
||||
|
||||
export async function readSealedPrompts(
|
||||
path: string,
|
||||
codec: OfflineCacheCodec | null
|
||||
): Promise<StoredPrompt[]> {
|
||||
if (!codec) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(codec.decrypt(readFileSync(path))) as {
|
||||
version: 2
|
||||
prompts: StoredPrompt[]
|
||||
const parsed = SealedQueueSchema.safeParse(JSON.parse(codec.decrypt(await readFile(path))))
|
||||
if (!parsed.success) {
|
||||
return []
|
||||
}
|
||||
return parsed.version === 2 && Array.isArray(parsed.prompts) ? parsed.prompts : []
|
||||
return parsed.data.prompts.flatMap((raw) => {
|
||||
const prompt = StoredPromptSchema.safeParse(raw)
|
||||
return prompt.success ? [prompt.data] : []
|
||||
})
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSealedPrompts(
|
||||
export async function writeSealedPrompts(
|
||||
path: string,
|
||||
codec: OfflineCacheCodec | null,
|
||||
prompts: readonly StoredPrompt[]
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!codec) {
|
||||
return
|
||||
}
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
||||
const sealed = codec.encrypt(JSON.stringify({ version: 2, prompts }))
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 })
|
||||
const temp = `${path}.${process.pid}.tmp`
|
||||
writeFileSync(temp, codec.encrypt(JSON.stringify({ version: 2, prompts })), { mode: 0o600 })
|
||||
renameSync(temp, path)
|
||||
await writeFile(temp, sealed, { mode: 0o600 })
|
||||
await rename(temp, path)
|
||||
}
|
||||
|
||||
/** The first build kept the queue as plaintext JSON beside the sealed file; it is never read. */
|
||||
export function removeLegacyPlaintextQueue(path: string): void {
|
||||
rmSync(join(dirname(path), 'orca-cloud-queued-prompts.json'), { force: true })
|
||||
export function removeLegacyPlaintextQueue(path: string): Promise<void> {
|
||||
return rm(join(dirname(path), 'orca-cloud-queued-prompts.json'), { force: true })
|
||||
}
|
||||
|
||||
/** The sealed queue file: read once, then every write and removal in call order. */
|
||||
export function createSealedPromptDisk(
|
||||
path: string,
|
||||
codec: OfflineCacheCodec | null,
|
||||
log: (line: string) => void
|
||||
) {
|
||||
const load = (async () => {
|
||||
await removeLegacyPlaintextQueue(path).catch(() => undefined)
|
||||
return readSealedPrompts(path, codec)
|
||||
})()
|
||||
// Nothing is written before the sealed file has been read.
|
||||
let tail: Promise<unknown> = load
|
||||
function serial(task: () => Promise<void>): Promise<void> {
|
||||
const run = tail.then(task)
|
||||
tail = run.catch((error: unknown) =>
|
||||
log(`[orca-cloud] queued prompts write failed: ${String(error)}`)
|
||||
)
|
||||
return run
|
||||
}
|
||||
return {
|
||||
load,
|
||||
write: (prompts: readonly StoredPrompt[]) =>
|
||||
serial(() => writeSealedPrompts(path, codec, prompts)),
|
||||
remove: () =>
|
||||
serial(async () => {
|
||||
await removeLegacyPlaintextQueue(path)
|
||||
await rm(path, { force: true })
|
||||
}),
|
||||
flushed: () => serial(async () => {})
|
||||
}
|
||||
}
|
||||
|
||||
export function earliestOwedAttempt(prompts: readonly StoredPrompt[]): number | null {
|
||||
let earliest: number | null = null
|
||||
for (const prompt of prompts) {
|
||||
if (prompt.state === 'queued' || prompt.state === 'sending') {
|
||||
earliest = earliest === null ? prompt.nextAttemptAt : Math.min(earliest, prompt.nextAttemptAt)
|
||||
}
|
||||
}
|
||||
return earliest
|
||||
}
|
||||
|
||||
/** Refusals that mean "not now", not "never": the same operation is sent again. */
|
||||
@@ -87,11 +153,24 @@ export async function currentFence(
|
||||
? { refused: code }
|
||||
: null
|
||||
}
|
||||
const result = response.result as { ok: boolean; page?: { fence?: number }; fence?: number }
|
||||
const parsed = FenceResultSchema.safeParse(response.result)
|
||||
const result = parsed.success ? parsed.data : { ok: false }
|
||||
const fence = result.page?.fence ?? (result.ok ? undefined : result.fence)
|
||||
return typeof fence === 'number' ? fence : null
|
||||
}
|
||||
|
||||
const FenceResultSchema = z.looseObject({
|
||||
ok: z.boolean(),
|
||||
page: z.looseObject({ fence: z.number().optional() }).optional(),
|
||||
fence: z.number().optional()
|
||||
})
|
||||
|
||||
/** `agentSession.send` answer: delivered, or refused with a code. */
|
||||
export const SendResultSchema = z.looseObject({
|
||||
ok: z.boolean(),
|
||||
refusal: z.looseObject({ code: z.string().optional(), message: z.string().optional() }).optional()
|
||||
})
|
||||
|
||||
export type WorkspaceAvailability =
|
||||
| { kind: 'up'; environmentId: string }
|
||||
| { kind: 'asleep'; environmentId: string }
|
||||
@@ -133,4 +212,8 @@ export type CloudMessageQueue = {
|
||||
failPending(workspaceId: string, reason: string): void
|
||||
/** Sign-out / profile switch: forget everything. */
|
||||
clear(): void
|
||||
/** Resolves once every disk write requested so far has finished (shutdown, tests). */
|
||||
flushed(): Promise<void>
|
||||
/** Earliest background attempt still owed (ms epoch), or null when nothing is pending. */
|
||||
nextAttemptAt(): number | null
|
||||
}
|
||||
|
||||
@@ -18,18 +18,14 @@ import {
|
||||
import type { OfflineCacheCodec } from './cloud-offline-cache'
|
||||
|
||||
const SESSION = '0f8e7c1a-2b3d-4e5f-8a9b-0c1d2e3f4a5b'
|
||||
/** Fixed test epoch: operation ids and the host's admission window both read this clock. */
|
||||
const T0 = 1_800_000_000_000
|
||||
|
||||
const codec: OfflineCacheCodec = {
|
||||
encrypt: (plain) => Buffer.from(Buffer.from(plain, 'utf8').map((b) => b ^ 0x5a)),
|
||||
decrypt: (sealed) => Buffer.from(sealed.map((b) => b ^ 0x5a)).toString('utf8')
|
||||
}
|
||||
|
||||
type Envelope = {
|
||||
clientOperationId: string
|
||||
expectedRuntimeFence: number
|
||||
payloadFingerprint: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A host that admits operations with the real ledger rule (id format, age, replay by id) and
|
||||
* validates params with the real send schema.
|
||||
@@ -59,7 +55,7 @@ function realishHost(clock: () => number) {
|
||||
}
|
||||
}
|
||||
const parsed = SendParams.parse(params)
|
||||
const envelope = parsed.envelope as Envelope
|
||||
const envelope = parsed.envelope
|
||||
const decision = evaluateAgentSessionOperation({
|
||||
rows,
|
||||
callerKey: 'desktop',
|
||||
@@ -78,9 +74,10 @@ function realishHost(clock: () => number) {
|
||||
}
|
||||
if (decision.decision === 'admit') {
|
||||
rows.set(agentSessionOperationKey('desktop', envelope.clientOperationId), decision.row)
|
||||
const block = parsed.body.blocks[0]
|
||||
effects.push({
|
||||
text: (parsed.body.blocks[0] as { text: string }).text,
|
||||
fence: envelope.expectedRuntimeFence
|
||||
text: block?.type === 'text' ? block.text : '',
|
||||
fence: envelope.expectedRuntimeFence ?? 0
|
||||
})
|
||||
}
|
||||
if (loseNextReply) {
|
||||
@@ -113,7 +110,7 @@ function setup(
|
||||
clock?: { now: number }
|
||||
} = {}
|
||||
) {
|
||||
const clock = opts.clock ?? { now: Date.now() }
|
||||
const clock = opts.clock ?? { now: T0 }
|
||||
const path = opts.path ?? join(mkdtempSync(join(tmpdir(), 'orca-q-')), 'q.bin')
|
||||
const host = opts.host ?? realishHost(() => clock.now)
|
||||
let asleep = true
|
||||
@@ -132,14 +129,11 @@ function setup(
|
||||
call: host.call,
|
||||
log: () => {}
|
||||
})
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
return { queue, host, wake, path, clock, settle, sleep: () => (asleep = true) }
|
||||
return { queue, host, wake, path, clock, sleep: () => (asleep = true) }
|
||||
}
|
||||
|
||||
async function until(check: () => boolean) {
|
||||
for (let i = 0; i < 100 && !check(); i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||
}
|
||||
await vi.waitFor(() => expect(check()).toBe(true))
|
||||
}
|
||||
|
||||
describe('cloud message queue', () => {
|
||||
@@ -155,15 +149,18 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('re-mints a never-sent id before it ages out of the host admission window', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
const place = { current: { kind: 'asleep', environmentId: 'env' } as WorkspaceAvailability }
|
||||
const place: { current: WorkspaceAvailability } = {
|
||||
current: { kind: 'asleep', environmentId: 'env' }
|
||||
}
|
||||
const parked = setup({ clock, host, place: () => place.current })
|
||||
parked.wake.mockResolvedValueOnce(false)
|
||||
await parked.queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'a day later' })
|
||||
// The wake failed: the prompt waits, queued, for the VM to be up.
|
||||
await until(() => parked.wake.mock.calls.length === 1)
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
// Joins the in-flight pass (never wakes on its own).
|
||||
await parked.queue.drive('w')
|
||||
expect(parked.queue.list('w')[0]!.state).toBe('queued')
|
||||
clock.now += AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS + 60_000
|
||||
place.current = { kind: 'up', environmentId: 'env' }
|
||||
@@ -177,9 +174,10 @@ describe('cloud message queue', () => {
|
||||
first.wake.mockResolvedValueOnce(false)
|
||||
await first.queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'after restart' })
|
||||
await until(() => first.wake.mock.calls.length === 1)
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
await first.queue.drive('w')
|
||||
await first.queue.flushed()
|
||||
expect(readFileSync(first.path).toString('utf8')).not.toContain('after restart')
|
||||
const host = realishHost(() => Date.now())
|
||||
const host = realishHost(() => first.clock.now)
|
||||
let up = false
|
||||
const second = setup({
|
||||
path: first.path,
|
||||
@@ -187,6 +185,7 @@ describe('cloud message queue', () => {
|
||||
place: () =>
|
||||
up ? { kind: 'up', environmentId: 'env' } : { kind: 'asleep', environmentId: 'env' }
|
||||
})
|
||||
await second.queue.flushed()
|
||||
expect(second.queue.list('w').map((p) => p.state)).toEqual(['queued'])
|
||||
await second.queue.drive()
|
||||
expect(second.wake).not.toHaveBeenCalled()
|
||||
@@ -198,7 +197,7 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('is at most once when the reply is lost: the retry reuses the id and the host replays', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
const { queue, path } = setup({
|
||||
clock,
|
||||
@@ -208,6 +207,7 @@ describe('cloud message queue', () => {
|
||||
host.loseNextReply()
|
||||
await queue.enqueue({ workspaceId: 'w', sessionId: SESSION, text: 'once' })
|
||||
await until(() => queue.list('w')[0]!.state === 'sending')
|
||||
await queue.flushed()
|
||||
clock.now += 60 * 60_000
|
||||
const restarted = setup({
|
||||
path,
|
||||
@@ -222,7 +222,7 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('never wakes from the background, and stops after its failure budget', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
host.setHistoryFails(true)
|
||||
const { queue, wake } = setup({
|
||||
@@ -241,7 +241,7 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('backs off between background attempts', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
host.setHistoryFails(true)
|
||||
const { queue } = setup({ clock, host, place: () => ({ kind: 'up', environmentId: 'env' }) })
|
||||
@@ -280,7 +280,7 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('does not send a prompt cancelled or edited while its fence was being read', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
let release: () => void = () => {}
|
||||
const gate = new Promise<void>((resolve) => (release = resolve))
|
||||
@@ -304,7 +304,6 @@ describe('cloud message queue', () => {
|
||||
expect(queue.cancel(a.id)).toBe(true)
|
||||
release()
|
||||
await queue.drive('w')
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
expect(host.effects).toHaveLength(0)
|
||||
})
|
||||
|
||||
@@ -359,7 +358,7 @@ describe('cloud message queue', () => {
|
||||
})
|
||||
|
||||
it('does not resurrect a prompt a Sleep failed while its fence was being read', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
let release: () => void = () => {}
|
||||
const gate = new Promise<void>((resolve) => (release = resolve))
|
||||
@@ -382,13 +381,14 @@ describe('cloud message queue', () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
queue.failPending('w', 'The workspace was put to sleep before this was sent.')
|
||||
release()
|
||||
await new Promise((resolve) => setTimeout(resolve, 5))
|
||||
// Joins the pass that was waiting on the fence.
|
||||
await queue.drive('w')
|
||||
expect(host.effects).toHaveLength(0)
|
||||
expect(queue.list('w')[0]!.state).toBe('failed')
|
||||
})
|
||||
|
||||
it('ends a sent-but-unconfirmed prompt as unconfirmed, not failed, at its budget', async () => {
|
||||
const clock = { now: Date.now() }
|
||||
const clock = { now: T0 }
|
||||
const host = realishHost(() => clock.now)
|
||||
const lossy: CloudMessageQueueDeps['call'] = async (env, method, params, t) => {
|
||||
const answer = await host.call(env, method, params, t)
|
||||
@@ -430,9 +430,11 @@ describe('cloud message queue', () => {
|
||||
},
|
||||
log: () => {}
|
||||
})
|
||||
await queue.flushed()
|
||||
expect(existsSync(legacy)).toBe(false)
|
||||
writeFileSync(legacy, 'again')
|
||||
queue.clear()
|
||||
await queue.flushed()
|
||||
expect(existsSync(legacy)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
// Only the person queuing a prompt wakes a VM. Background retries deliver only to a VM that is
|
||||
// already up, never to one asleep, archived or manually disconnected, and stop after a budget.
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { rmSync } from 'node:fs'
|
||||
import { CLOUD_QUEUED_PROMPT_MAX_CHARS } from '../../shared/hosted-sandbox/cloud-workspace-offline-api'
|
||||
import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope'
|
||||
import { structuredAgentSessionMessageSendMutation } from '../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
@@ -21,12 +20,12 @@ import {
|
||||
import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation'
|
||||
import { SendParams } from '../../shared/rpc-contract/structured-agent-session-params'
|
||||
import {
|
||||
readSealedPrompts,
|
||||
createSealedPromptDisk,
|
||||
currentFence,
|
||||
earliestOwedAttempt,
|
||||
publicView,
|
||||
RETRYABLE_REFUSALS,
|
||||
removeLegacyPlaintextQueue,
|
||||
writeSealedPrompts,
|
||||
SendResultSchema,
|
||||
type CloudMessageQueue,
|
||||
type CloudMessageQueueDeps,
|
||||
type StoredPrompt
|
||||
@@ -52,26 +51,33 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
const log = deps.log ?? ((line: string) => console.error(line))
|
||||
const driving = new Map<string, Promise<void>>()
|
||||
const mintId = () => createStructuredAgentSessionOperationId(randomUUID, now())
|
||||
removeLegacyPlaintextQueue(deps.path)
|
||||
let prompts: StoredPrompt[] = readSealedPrompts(deps.path, deps.codec)
|
||||
let prompts: StoredPrompt[] = []
|
||||
// Bumped by clear() so a load still reading the old file cannot bring cleared prompts back.
|
||||
let generation = 0
|
||||
const disk = createSealedPromptDisk(deps.path, deps.codec, log)
|
||||
const loaded = disk.load.then((stored) => {
|
||||
prompts = generation === 0 ? [...stored, ...prompts] : prompts
|
||||
})
|
||||
|
||||
function save(): void {
|
||||
/** Resolves once the queue is on disk as of this call; rejects if that write failed. */
|
||||
function save(): Promise<void> {
|
||||
const cutoff = now() - DELIVERED_RETENTION_MS
|
||||
prompts = prompts.filter((prompt) => prompt.state !== 'delivered' || prompt.updatedAt >= cutoff)
|
||||
writeSealedPrompts(deps.path, deps.codec, prompts)
|
||||
return disk.write(prompts)
|
||||
}
|
||||
|
||||
function update(prompt: StoredPrompt, patch: Partial<StoredPrompt>): void {
|
||||
function update(prompt: StoredPrompt, patch: Partial<StoredPrompt>): Promise<void> {
|
||||
Object.assign(prompt, patch, { updatedAt: now() })
|
||||
save()
|
||||
const saved = save()
|
||||
deps.onChange?.(prompt.workspaceId)
|
||||
return saved
|
||||
}
|
||||
|
||||
function failOnce(prompt: StoredPrompt, error: string): void {
|
||||
const failures = prompt.failures + 1
|
||||
if (failures >= MAX_FAILURES) {
|
||||
// A prompt that reached `sending` may already be on the host: say so, so nobody re-sends it.
|
||||
update(
|
||||
void update(
|
||||
prompt,
|
||||
prompt.state === 'sending'
|
||||
? {
|
||||
@@ -83,7 +89,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
)
|
||||
return
|
||||
}
|
||||
update(prompt, {
|
||||
void update(prompt, {
|
||||
failures,
|
||||
nextAttemptAt: now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (failures - 1))
|
||||
})
|
||||
@@ -104,7 +110,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
prompt.state === 'queued' &&
|
||||
now() - mintedAt > AGENT_SESSION_MAX_NEW_OPERATION_AGE_MS - REMINT_MARGIN_MS
|
||||
) {
|
||||
update(prompt, { clientOperationId: mintId() })
|
||||
await update(prompt, { clientOperationId: mintId() })
|
||||
}
|
||||
const before = { id: prompt.clientOperationId, text: prompt.text, state: prompt.state }
|
||||
let fence: number | { refused: string } | null
|
||||
@@ -129,7 +135,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
return 'stop'
|
||||
}
|
||||
if (typeof fence !== 'number') {
|
||||
update(prompt, { state: 'failed', error: 'This chat is no longer on the workspace.' })
|
||||
await update(prompt, { state: 'failed', error: 'This chat is no longer on the workspace.' })
|
||||
return 'next'
|
||||
}
|
||||
const params = structuredAgentSessionMessageSendMutation({
|
||||
@@ -142,11 +148,11 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
})
|
||||
// The host's own schema: a prompt it would reject outright is failed here, never retried.
|
||||
if (!SendParams.safeParse(params).success) {
|
||||
update(prompt, { state: 'failed', error: 'This message cannot be sent to that chat.' })
|
||||
await update(prompt, { state: 'failed', error: 'This message cannot be sent to that chat.' })
|
||||
return 'next'
|
||||
}
|
||||
// Durable before the send: from here on, any retry resends this same operation id.
|
||||
update(prompt, { state: 'sending' })
|
||||
await update(prompt, { state: 'sending' })
|
||||
let response: RuntimeRpcResponse<unknown>
|
||||
try {
|
||||
response = await deps.call(environmentId, 'agentSession.send', params, SEND_TIMEOUT_MS)
|
||||
@@ -159,9 +165,10 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
failOnce(prompt, response.error.message.slice(0, 200))
|
||||
return 'stop'
|
||||
}
|
||||
const result = response.result as { ok: boolean; refusal?: { code?: string; message?: string } }
|
||||
const parsed = SendResultSchema.safeParse(response.result)
|
||||
const result = parsed.success ? parsed.data : { ok: false, refusal: undefined }
|
||||
if (result.ok) {
|
||||
update(prompt, { state: 'delivered', error: undefined })
|
||||
await update(prompt, { state: 'delivered', error: undefined })
|
||||
return 'next'
|
||||
}
|
||||
const code = result.refusal?.code ?? 'unknown'
|
||||
@@ -169,11 +176,12 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
failOnce(prompt, result.refusal?.message ?? code)
|
||||
return 'stop'
|
||||
}
|
||||
update(prompt, { state: 'failed', error: result.refusal?.message ?? code })
|
||||
await update(prompt, { state: 'failed', error: result.refusal?.message ?? code })
|
||||
return 'next'
|
||||
}
|
||||
|
||||
async function driveWorkspace(workspaceId: string, allowWake: boolean): Promise<void> {
|
||||
await loaded
|
||||
if (pendingOf(workspaceId).length === 0) {
|
||||
return
|
||||
}
|
||||
@@ -233,6 +241,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
if (!trimmed || trimmed.length > CLOUD_QUEUED_PROMPT_MAX_CHARS) {
|
||||
throw new Error('Prompt is empty or too long.')
|
||||
}
|
||||
await loaded
|
||||
const place = await deps.locate(workspaceId)
|
||||
if (place.kind === 'blocked') {
|
||||
throw new Error(place.reason)
|
||||
@@ -254,7 +263,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
nextAttemptAt: at
|
||||
}
|
||||
prompts.push(prompt)
|
||||
save()
|
||||
await save()
|
||||
deps.onChange?.(workspaceId)
|
||||
void run(workspaceId, true)
|
||||
return publicView(prompt)
|
||||
@@ -268,7 +277,7 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
return false
|
||||
}
|
||||
prompts = prompts.filter((p) => p !== prompt)
|
||||
save()
|
||||
void save()
|
||||
deps.onChange?.(prompt.workspaceId)
|
||||
return true
|
||||
},
|
||||
@@ -284,9 +293,11 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
return false
|
||||
}
|
||||
// Never sent, so a new text is a new operation; nothing on the host knows the old id.
|
||||
update(prompt, { text: trimmed, clientOperationId: mintId() })
|
||||
void update(prompt, { text: trimmed, clientOperationId: mintId() })
|
||||
return true
|
||||
},
|
||||
nextAttemptAt: () => earliestOwedAttempt(prompts),
|
||||
flushed: () => disk.flushed(),
|
||||
drive(workspaceId) {
|
||||
const ids = workspaceId
|
||||
? [workspaceId]
|
||||
@@ -309,15 +320,15 @@ export function createCloudMessageQueue(deps: CloudMessageQueueDeps): CloudMessa
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
save()
|
||||
void save()
|
||||
deps.onChange?.(workspaceId)
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
removeLegacyPlaintextQueue(deps.path)
|
||||
generation++
|
||||
const workspaces = new Set(prompts.map((p) => p.workspaceId))
|
||||
prompts = []
|
||||
rmSync(deps.path, { force: true })
|
||||
void disk.remove().catch(() => undefined)
|
||||
for (const workspaceId of workspaces) {
|
||||
deps.onChange?.(workspaceId)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createOwedWorkBeat } from './cloud-offline-beat'
|
||||
|
||||
const T0 = 1_800_000_000_000
|
||||
|
||||
describe('owed-work beat', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(T0)
|
||||
})
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('stays idle with nothing owed, and backs off while passes change nothing', async () => {
|
||||
let due: number | null = null
|
||||
const pass = vi.fn(async () => {})
|
||||
const beat = createOwedWorkBeat({
|
||||
nextDueAt: () => due,
|
||||
pass,
|
||||
baseMs: 1_000,
|
||||
maxBackoffSteps: 2
|
||||
})
|
||||
beat.poke()
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(pass).not.toHaveBeenCalled()
|
||||
|
||||
due = T0
|
||||
beat.poke()
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(pass).toHaveBeenCalledTimes(1)
|
||||
// Unchanged after that pass: the next waits 2 s, then 4 s (the cap).
|
||||
await vi.advanceTimersByTimeAsync(1_999)
|
||||
expect(pass).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(pass).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(4_000)
|
||||
expect(pass).toHaveBeenCalledTimes(3)
|
||||
await vi.advanceTimersByTimeAsync(4_000)
|
||||
expect(pass).toHaveBeenCalledTimes(4)
|
||||
|
||||
due = null
|
||||
await vi.advanceTimersByTimeAsync(4_000)
|
||||
const settled = pass.mock.calls.length
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(pass).toHaveBeenCalledTimes(settled)
|
||||
beat.dispose()
|
||||
})
|
||||
|
||||
it('waits for a later due attempt and stops on dispose', async () => {
|
||||
const pass = vi.fn(async () => {})
|
||||
const beat = createOwedWorkBeat({
|
||||
nextDueAt: () => T0 + 10_000,
|
||||
pass,
|
||||
baseMs: 1_000,
|
||||
maxBackoffSteps: 2
|
||||
})
|
||||
beat.poke()
|
||||
await vi.advanceTimersByTimeAsync(9_999)
|
||||
expect(pass).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(pass).toHaveBeenCalledTimes(1)
|
||||
beat.dispose()
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
expect(pass).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
// Background delivery for queued Orca Cloud prompts runs only while prompts are owed: at the next
|
||||
// due attempt, never sooner than the base cadence, doubling while a pass changes nothing.
|
||||
export type OwedWorkBeat = {
|
||||
/** Something changed (a prompt was queued or settled): arm at the base cadence again. */
|
||||
poke(): void
|
||||
/** Run a pass now (startup), then keep the cadence while work is owed. */
|
||||
runNow(): Promise<void>
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
export function createOwedWorkBeat(options: {
|
||||
/** Earliest owed attempt (ms epoch), or null when nothing is owed: the beat stops. */
|
||||
nextDueAt: () => number | null
|
||||
pass: () => Promise<void>
|
||||
baseMs: number
|
||||
maxBackoffSteps: number
|
||||
now?: () => number
|
||||
}): OwedWorkBeat {
|
||||
const now = options.now ?? Date.now
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let idlePasses = 0
|
||||
let disposed = false
|
||||
|
||||
function arm(): void {
|
||||
const due = options.nextDueAt()
|
||||
if (timer || disposed || due === null) {
|
||||
return
|
||||
}
|
||||
const idleDelay = options.baseMs * 2 ** Math.min(idlePasses, options.maxBackoffSteps)
|
||||
timer = setTimeout(() => void runNow(), Math.max(due - now(), idleDelay))
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
async function runNow(): Promise<void> {
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
const before = options.nextDueAt()
|
||||
await options.pass()
|
||||
idlePasses = options.nextDueAt() === before ? idlePasses + 1 : 0
|
||||
arm()
|
||||
}
|
||||
|
||||
return {
|
||||
poke() {
|
||||
idlePasses = 0
|
||||
arm()
|
||||
},
|
||||
runNow,
|
||||
dispose() {
|
||||
disposed = true
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// Types, limits and small helpers of the Orca Cloud offline cache (see cloud-offline-cache.ts).
|
||||
import { readdirSync, rmSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readdir, rm } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
|
||||
|
||||
/** Read-only methods whose answers stay meaningful while the VM sleeps. Nothing that mutates. */
|
||||
@@ -76,14 +78,15 @@ export type CloudOfflineCache = {
|
||||
params: unknown,
|
||||
response: RuntimeRpcSuccess<unknown>
|
||||
): void
|
||||
lookup(environmentId: string, method: string, params: unknown): OfflineCacheEntry | null
|
||||
entries(environmentId: string, method?: string): OfflineCacheEntry[]
|
||||
forget(environmentId: string): void
|
||||
lookup(environmentId: string, method: string, params: unknown): Promise<OfflineCacheEntry | null>
|
||||
entries(environmentId: string, method?: string): Promise<OfflineCacheEntry[]>
|
||||
forget(environmentId: string): Promise<void>
|
||||
/** Drop every environment not in `keep` (removed workspaces). */
|
||||
prune(keep: ReadonlySet<string>): void
|
||||
prune(keep: ReadonlySet<string>): Promise<void>
|
||||
/** Delete everything (sign-out, profile switch). */
|
||||
clear(): void
|
||||
flush(): void
|
||||
clear(): Promise<void>
|
||||
/** Writes pending changes; resolves once earlier records and file work have landed. */
|
||||
flush(): Promise<void>
|
||||
}
|
||||
|
||||
/** Key-order independent, so `{a,b}` and `{b,a}` hit the same entry. */
|
||||
@@ -105,14 +108,51 @@ export function stableKey(method: string, params: unknown): string {
|
||||
return `${method} ${JSON.stringify(sort(params ?? null))}`
|
||||
}
|
||||
|
||||
export function removeLegacyPlaintextFiles(root: string): void {
|
||||
export async function removeLegacyPlaintextFiles(root: string): Promise<void> {
|
||||
try {
|
||||
for (const name of readdirSync(root)) {
|
||||
for (const name of await readdir(root)) {
|
||||
if (name.endsWith('.json')) {
|
||||
rmSync(join(root, name), { force: true })
|
||||
await rm(join(root, name), { force: true })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No cache directory yet.
|
||||
}
|
||||
}
|
||||
|
||||
export const EnvironmentFileSchema = z.object({
|
||||
version: z.literal(2),
|
||||
environmentId: z.string(),
|
||||
updatedAt: z.number(),
|
||||
entries: z.record(
|
||||
z.string(),
|
||||
z.object({
|
||||
method: z.string(),
|
||||
params: z.unknown(),
|
||||
resultJson: z.string(),
|
||||
runtimeId: z.string(),
|
||||
at: z.number(),
|
||||
bytes: z.number()
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
export function fileName(environmentId: string): string {
|
||||
return `${createHash('sha256').update(environmentId).digest('hex').slice(0, 32)}.bin`
|
||||
}
|
||||
|
||||
export function decode(entry: StoredEntry): OfflineCacheEntry {
|
||||
const { resultJson, ...rest } = entry
|
||||
const result: unknown = JSON.parse(resultJson)
|
||||
return { ...rest, result }
|
||||
}
|
||||
|
||||
export const DISABLED_OFFLINE_CACHE: CloudOfflineCache = {
|
||||
record: () => {},
|
||||
lookup: async () => null,
|
||||
entries: async () => [],
|
||||
forget: async () => {},
|
||||
prune: async () => {},
|
||||
clear: async () => {},
|
||||
flush: async () => {}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import {
|
||||
archiveCheckoutsFromCache,
|
||||
buildOfflineSnapshot,
|
||||
stringParam,
|
||||
stripAnsi
|
||||
} from './cloud-offline-snapshot'
|
||||
|
||||
@@ -41,17 +42,17 @@ function setup(limits = {}) {
|
||||
}
|
||||
|
||||
describe('cloud offline cache', () => {
|
||||
it('keeps only allowlisted read-only methods', () => {
|
||||
it('keeps only allowlisted read-only methods', async () => {
|
||||
const { cache } = setup()
|
||||
cache.record('env', 'git.status', { worktree: 'id:w' }, ok({ entries: [] }))
|
||||
cache.record('env', 'agentSession.send', { sessionId: 's' }, ok({}))
|
||||
cache.record('env', 'git.commit', { worktree: 'id:w' }, ok({}))
|
||||
expect(cache.entries('env').map((e) => e.method)).toEqual(['git.status'])
|
||||
expect((await cache.entries('env')).map((e) => e.method)).toEqual(['git.status'])
|
||||
expect(OFFLINE_READ_METHODS.has('terminal.send')).toBe(false)
|
||||
expect(cache.lookup('env', 'agentSession.send', { sessionId: 's' })).toBeNull()
|
||||
expect(await cache.lookup('env', 'agentSession.send', { sessionId: 's' })).toBeNull()
|
||||
})
|
||||
|
||||
it('seals files at rest and reads them back after a reload', () => {
|
||||
it('seals files at rest and reads them back after a reload', async () => {
|
||||
const { root, cache } = setup()
|
||||
cache.record(
|
||||
'env',
|
||||
@@ -60,23 +61,27 @@ describe('cloud offline cache', () => {
|
||||
ok({ items: ['secret subject'] })
|
||||
)
|
||||
expect(stableKey('m', { a: 1, b: 2 })).toBe(stableKey('m', { b: 2, a: 1 }))
|
||||
await cache.flush()
|
||||
const [name] = readdirSync(root)
|
||||
expect(readFileSync(join(root, name!)).toString('utf8')).not.toContain('secret subject')
|
||||
const reloaded = createCloudOfflineCache({ root, codec: testCodec, flushDelayMs: 0 })
|
||||
expect(reloaded.lookup('env', 'git.history', { limit: 20, worktree: 'id:w' })?.result).toEqual({
|
||||
expect(
|
||||
(await reloaded.lookup('env', 'git.history', { limit: 20, worktree: 'id:w' }))?.result
|
||||
).toEqual({
|
||||
items: ['secret subject']
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps nothing when the OS cannot seal files', () => {
|
||||
it('keeps nothing when the OS cannot seal files', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-offline-'))
|
||||
const cache = createCloudOfflineCache({ root, codec: null, flushDelayMs: 0 })
|
||||
cache.record('env', 'git.status', {}, ok({ entries: [] }))
|
||||
expect(cache.entries('env')).toEqual([])
|
||||
expect(await cache.entries('env')).toEqual([])
|
||||
await cache.flush()
|
||||
expect(readdirSync(root)).toEqual([])
|
||||
})
|
||||
|
||||
it('does not re-serialize a key polled again within the interval', () => {
|
||||
it('does not re-serialize a key polled again within the interval', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-offline-'))
|
||||
let now = 0
|
||||
const cache = createCloudOfflineCache({
|
||||
@@ -88,27 +93,24 @@ describe('cloud offline cache', () => {
|
||||
cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['a'] } }))
|
||||
now = 1_000
|
||||
cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['b'] } }))
|
||||
expect(cache.lookup('env', 'terminal.read', { terminal: 't' })?.result).toEqual({
|
||||
expect((await cache.lookup('env', 'terminal.read', { terminal: 't' }))?.result).toEqual({
|
||||
terminal: { tail: ['a'] }
|
||||
})
|
||||
now = 6_000
|
||||
cache.record('env', 'terminal.read', { terminal: 't' }, ok({ terminal: { tail: ['c'] } }))
|
||||
expect(cache.lookup('env', 'terminal.read', { terminal: 't' })?.result).toEqual({
|
||||
expect((await cache.lookup('env', 'terminal.read', { terminal: 't' }))?.result).toEqual({
|
||||
terminal: { tail: ['c'] }
|
||||
})
|
||||
})
|
||||
|
||||
it('evicts the oldest entries past the per-workspace bound and refuses oversized answers', () => {
|
||||
it('evicts the oldest entries past the per-workspace bound and refuses oversized answers', async () => {
|
||||
const { cache, tick } = setup({ maxEntriesPerEnvironment: 3, maxEntryBytes: 200 })
|
||||
for (let i = 0; i < 5; i++) {
|
||||
tick()
|
||||
cache.record('env', 'terminal.read', { terminal: `t${i}` }, ok({ terminal: { tail: ['x'] } }))
|
||||
}
|
||||
expect(
|
||||
cache
|
||||
.entries('env')
|
||||
.map((e) => (e.params as { terminal: string }).terminal)
|
||||
.sort()
|
||||
(await cache.entries('env')).map((e) => stringParam(e.params, 'terminal')).sort()
|
||||
).toEqual(['t2', 't3', 't4'])
|
||||
cache.record(
|
||||
'env',
|
||||
@@ -116,50 +118,53 @@ describe('cloud offline cache', () => {
|
||||
{ terminal: 't4' },
|
||||
ok({ terminal: { tail: ['y'.repeat(500)] } })
|
||||
)
|
||||
expect(cache.lookup('env', 'terminal.read', { terminal: 't4' })).toBeNull()
|
||||
expect(await cache.lookup('env', 'terminal.read', { terminal: 't4' })).toBeNull()
|
||||
})
|
||||
|
||||
it('holds a bounded number of workspaces in memory and still reads evicted ones from disk', () => {
|
||||
it('holds a bounded number of workspaces in memory and still reads evicted ones from disk', async () => {
|
||||
const { cache, tick } = setup({ maxLoadedEnvironments: 2 })
|
||||
for (const env of ['a', 'b', 'c', 'd']) {
|
||||
tick()
|
||||
cache.record(env, 'git.status', { worktree: env }, ok({ branch: env }))
|
||||
}
|
||||
expect(cache.lookup('a', 'git.status', { worktree: 'a' })?.result).toEqual({ branch: 'a' })
|
||||
expect((await cache.lookup('a', 'git.status', { worktree: 'a' }))?.result).toEqual({
|
||||
branch: 'a'
|
||||
})
|
||||
})
|
||||
|
||||
it('evicts whole least-recent workspaces past the total bound, prunes removed ones, and clears on sign-out', () => {
|
||||
it('evicts whole least-recent workspaces past the total bound, prunes removed ones, and clears on sign-out', async () => {
|
||||
const { root, cache, tick } = setup({ maxTotalBytes: 900 })
|
||||
for (const env of ['a', 'b', 'c']) {
|
||||
tick(1000)
|
||||
cache.record(env, 'git.status', { worktree: env }, ok({ entries: ['z'.repeat(300)] }))
|
||||
}
|
||||
await cache.flush()
|
||||
expect(readdirSync(root).length).toBeLessThan(3)
|
||||
expect(cache.lookup('c', 'git.status', { worktree: 'c' })).not.toBeNull()
|
||||
cache.prune(new Set(['c']))
|
||||
expect(await cache.lookup('c', 'git.status', { worktree: 'c' })).not.toBeNull()
|
||||
await cache.prune(new Set(['c']))
|
||||
expect(readdirSync(root)).toHaveLength(1)
|
||||
cache.clear()
|
||||
await cache.clear()
|
||||
expect(existsSync(root)).toBe(false)
|
||||
expect(cache.lookup('c', 'git.status', { worktree: 'c' })).toBeNull()
|
||||
expect(await cache.lookup('c', 'git.status', { worktree: 'c' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('legacy plaintext cache files', () => {
|
||||
it('are removed whatever the codec', () => {
|
||||
it('are removed whatever the codec', async () => {
|
||||
for (const sealing of [testCodec, null]) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-offline-'))
|
||||
writeFileSync(
|
||||
join(root, 'abc.json'),
|
||||
'{"version":1,"entries":{"k":{"result":"old plaintext"}}}'
|
||||
)
|
||||
createCloudOfflineCache({ root, codec: sealing, flushDelayMs: 0 })
|
||||
await createCloudOfflineCache({ root, codec: sealing, flushDelayMs: 0 }).flush()
|
||||
expect(readdirSync(root)).toEqual([])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('offline snapshot', () => {
|
||||
it('builds chats, terminals and git state from cached answers', () => {
|
||||
it('builds chats, terminals and git state from cached answers', async () => {
|
||||
const { cache, tick } = setup()
|
||||
cache.record(
|
||||
'env',
|
||||
@@ -222,7 +227,7 @@ describe('offline snapshot', () => {
|
||||
}
|
||||
})
|
||||
)
|
||||
const snapshot = buildOfflineSnapshot(cache, 'env', 'w', true)
|
||||
const snapshot = await buildOfflineSnapshot(cache, 'env', 'w', true)
|
||||
expect(snapshot.asleep).toBe(true)
|
||||
expect(snapshot.terminals).toEqual([
|
||||
{ handle: 'h1', title: 'Dev server', lines: ['ready on :3000'], at: 1000 }
|
||||
@@ -237,7 +242,8 @@ describe('offline snapshot', () => {
|
||||
['assistant', 'Done.']
|
||||
])
|
||||
expect(snapshot.capturedAt).toBe(1001)
|
||||
const [checkout] = archiveCheckoutsFromCache(cache, 'env', '/vercel/sandbox/project')!
|
||||
const [checkout] =
|
||||
(await archiveCheckoutsFromCache(cache, 'env', '/vercel/sandbox/project')) ?? []
|
||||
expect(checkout).toMatchObject({
|
||||
branch: 'feat',
|
||||
head: 'abcdef1',
|
||||
@@ -245,7 +251,7 @@ describe('offline snapshot', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('strips terminal escapes', () => {
|
||||
it('strips terminal escapes', async () => {
|
||||
expect(stripAnsi('\u001b]0;title\u0007a\u001b[1;31mb\u001b[0m\rc')).toBe('abc')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,28 +3,21 @@
|
||||
// servers; Orca keeps them on the VM (end-to-end encrypted), so the only copy outside the VM is
|
||||
// this one, on the user's own disk, sealed with the OS keychain. Without a keychain nothing is kept.
|
||||
// Bounded per workspace, in total, and in memory; one file per environment.
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
decode,
|
||||
DEFAULT_OFFLINE_CACHE_LIMITS,
|
||||
DISABLED_OFFLINE_CACHE,
|
||||
EnvironmentFileSchema,
|
||||
fileName,
|
||||
OFFLINE_READ_METHODS,
|
||||
removeLegacyPlaintextFiles,
|
||||
stableKey,
|
||||
type CloudOfflineCache,
|
||||
type EnvironmentFile,
|
||||
type OfflineCacheCodec,
|
||||
type OfflineCacheEntry,
|
||||
type OfflineCacheLimits,
|
||||
type StoredEntry
|
||||
type OfflineCacheLimits
|
||||
} from './cloud-offline-cache-types'
|
||||
|
||||
export {
|
||||
@@ -37,90 +30,98 @@ export {
|
||||
type OfflineCacheLimits
|
||||
} from './cloud-offline-cache-types'
|
||||
|
||||
function fileName(environmentId: string): string {
|
||||
return `${createHash('sha256').update(environmentId).digest('hex').slice(0, 32)}.bin`
|
||||
}
|
||||
|
||||
function decode(entry: StoredEntry): OfflineCacheEntry {
|
||||
const { resultJson, ...rest } = entry
|
||||
return { ...rest, result: JSON.parse(resultJson) as unknown }
|
||||
}
|
||||
|
||||
const DISABLED: CloudOfflineCache = {
|
||||
record: () => {},
|
||||
lookup: () => null,
|
||||
entries: () => [],
|
||||
forget: () => {},
|
||||
prune: () => {},
|
||||
clear: () => {},
|
||||
flush: () => {}
|
||||
}
|
||||
|
||||
export function createCloudOfflineCache(options: {
|
||||
root: string
|
||||
/** Null: the OS cannot seal files, so nothing is cached. */
|
||||
codec: OfflineCacheCodec | null
|
||||
limits?: Partial<OfflineCacheLimits>
|
||||
now?: () => number
|
||||
/** Write delay; 0 writes synchronously (tests). */
|
||||
/** Write delay; 0 writes as soon as a record lands (tests). */
|
||||
flushDelayMs?: number
|
||||
}): CloudOfflineCache {
|
||||
const codec = options.codec
|
||||
// All file work runs one task at a time, in call order, off the main thread's sync fs path.
|
||||
let io: Promise<unknown> = Promise.resolve()
|
||||
function serial<T>(task: () => Promise<T>): Promise<T> {
|
||||
const run = io.then(task, task)
|
||||
io = run.catch(() => undefined)
|
||||
return run
|
||||
}
|
||||
// Plaintext v1 files from the first build are never read; remove them whatever the codec.
|
||||
removeLegacyPlaintextFiles(options.root)
|
||||
const legacyRemoved = serial(() => removeLegacyPlaintextFiles(options.root))
|
||||
const codec = options.codec
|
||||
if (!codec) {
|
||||
return DISABLED
|
||||
return { ...DISABLED_OFFLINE_CACHE, flush: () => legacyRemoved }
|
||||
}
|
||||
const limits = { ...DEFAULT_OFFLINE_CACHE_LIMITS, ...options.limits }
|
||||
const now = options.now ?? Date.now
|
||||
const flushDelayMs = options.flushDelayMs ?? 1_000
|
||||
// Map insertion order is the LRU order: a touched environment is re-inserted at the end.
|
||||
const loaded = new Map<string, EnvironmentFile>()
|
||||
const loading = new Map<string, Promise<EnvironmentFile>>()
|
||||
const dirty = new Set<string>()
|
||||
// Bumped by forget/prune/clear so a read that started before them is not cached afterwards.
|
||||
let generation = 0
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const pathOf = (environmentId: string) => join(options.root, fileName(environmentId))
|
||||
|
||||
function write(environmentId: string): void {
|
||||
const file = loaded.get(environmentId)
|
||||
if (!file) {
|
||||
return
|
||||
}
|
||||
mkdirSync(options.root, { recursive: true, mode: 0o700 })
|
||||
const target = pathOf(environmentId)
|
||||
const temp = `${target}.${process.pid}.tmp`
|
||||
writeFileSync(temp, codec!.encrypt(JSON.stringify(file)), { mode: 0o600 })
|
||||
renameSync(temp, target)
|
||||
function write(file: EnvironmentFile): Promise<void> {
|
||||
const serialized = codec!.encrypt(JSON.stringify(file))
|
||||
return serial(async () => {
|
||||
await mkdir(options.root, { recursive: true, mode: 0o700 })
|
||||
const target = pathOf(file.environmentId)
|
||||
const temp = `${target}.${process.pid}.tmp`
|
||||
await writeFile(temp, serialized, { mode: 0o600 })
|
||||
await rename(temp, target)
|
||||
})
|
||||
}
|
||||
|
||||
function load(environmentId: string): EnvironmentFile {
|
||||
const hit = loaded.get(environmentId)
|
||||
if (hit) {
|
||||
loaded.delete(environmentId)
|
||||
loaded.set(environmentId, hit)
|
||||
return hit
|
||||
}
|
||||
let file: EnvironmentFile = { version: 2, environmentId, updatedAt: 0, entries: {} }
|
||||
async function readFromDisk(environmentId: string): Promise<EnvironmentFile> {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
codec!.decrypt(readFileSync(pathOf(environmentId)))
|
||||
) as EnvironmentFile
|
||||
if (parsed.version === 2 && parsed.environmentId === environmentId && parsed.entries) {
|
||||
file = parsed
|
||||
const parsed = EnvironmentFileSchema.safeParse(
|
||||
JSON.parse(codec!.decrypt(await readFile(pathOf(environmentId))))
|
||||
)
|
||||
if (parsed.success && parsed.data.environmentId === environmentId) {
|
||||
return parsed.data
|
||||
}
|
||||
} catch {
|
||||
// Missing, unreadable or sealed by another keychain: start empty. A cache is never a source of truth.
|
||||
}
|
||||
loaded.set(environmentId, file)
|
||||
while (loaded.size > limits.maxLoadedEnvironments) {
|
||||
const oldest = loaded.keys().next().value!
|
||||
if (dirty.has(oldest)) {
|
||||
write(oldest)
|
||||
dirty.delete(oldest)
|
||||
}
|
||||
loaded.delete(oldest)
|
||||
return { version: 2, environmentId, updatedAt: 0, entries: {} }
|
||||
}
|
||||
|
||||
function load(environmentId: string): Promise<EnvironmentFile> {
|
||||
const hit = loaded.get(environmentId)
|
||||
if (hit) {
|
||||
loaded.delete(environmentId)
|
||||
loaded.set(environmentId, hit)
|
||||
return Promise.resolve(hit)
|
||||
}
|
||||
return file
|
||||
const pending = loading.get(environmentId)
|
||||
if (pending) {
|
||||
return pending
|
||||
}
|
||||
const startedAt = generation
|
||||
const reading = serial(() => readFromDisk(environmentId)).then((file) => {
|
||||
loading.delete(environmentId)
|
||||
const raced = loaded.get(environmentId)
|
||||
if (raced || startedAt !== generation) {
|
||||
return raced ?? file
|
||||
}
|
||||
loaded.set(environmentId, file)
|
||||
while (loaded.size > limits.maxLoadedEnvironments) {
|
||||
const oldest = loaded.keys().next().value!
|
||||
const evicted = loaded.get(oldest)
|
||||
if (evicted && dirty.has(oldest)) {
|
||||
dirty.delete(oldest)
|
||||
void write(evicted).catch(logWriteFailure)
|
||||
}
|
||||
loaded.delete(oldest)
|
||||
}
|
||||
return file
|
||||
})
|
||||
loading.set(environmentId, reading)
|
||||
return reading
|
||||
}
|
||||
|
||||
function evictWithin(file: EnvironmentFile): void {
|
||||
@@ -138,15 +139,16 @@ export function createCloudOfflineCache(options: {
|
||||
}
|
||||
|
||||
/** Whole environments go least-recently-written first once the total passes its bound. */
|
||||
function evictTotal(): void {
|
||||
async function evictTotal(): Promise<void> {
|
||||
let files: { name: string; size: number; mtime: number }[]
|
||||
try {
|
||||
files = readdirSync(options.root)
|
||||
.filter((name) => name.endsWith('.bin'))
|
||||
.map((name) => {
|
||||
const stat = statSync(join(options.root, name))
|
||||
return { name, size: stat.size, mtime: stat.mtimeMs }
|
||||
const names = (await readdir(options.root)).filter((name) => name.endsWith('.bin'))
|
||||
files = await Promise.all(
|
||||
names.map(async (name) => {
|
||||
const info = await stat(join(options.root, name))
|
||||
return { name, size: info.size, mtime: info.mtimeMs }
|
||||
})
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
@@ -155,7 +157,7 @@ export function createCloudOfflineCache(options: {
|
||||
if (total <= limits.maxTotalBytes) {
|
||||
break
|
||||
}
|
||||
rmSync(join(options.root, file.name), { force: true })
|
||||
await rm(join(options.root, file.name), { force: true })
|
||||
for (const environmentId of loaded.keys()) {
|
||||
if (fileName(environmentId) === file.name) {
|
||||
loaded.delete(environmentId)
|
||||
@@ -165,30 +167,33 @@ export function createCloudOfflineCache(options: {
|
||||
}
|
||||
}
|
||||
|
||||
function flush(): void {
|
||||
function logWriteFailure(error: unknown): void {
|
||||
console.error(`[orca-cloud] offline cache write failed: ${String(error)}`)
|
||||
}
|
||||
|
||||
// Records apply after their environment loads; flush waits for those still landing.
|
||||
const applying = new Set<Promise<void>>()
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
for (const environmentId of dirty) {
|
||||
try {
|
||||
write(environmentId)
|
||||
} catch (error) {
|
||||
console.error(`[orca-cloud] offline cache write failed: ${String(error)}`)
|
||||
}
|
||||
}
|
||||
await Promise.all(applying)
|
||||
const files = [...dirty].flatMap((environmentId) => loaded.get(environmentId) ?? [])
|
||||
dirty.clear()
|
||||
evictTotal()
|
||||
await Promise.all(files.map((file) => write(file).catch(logWriteFailure)))
|
||||
await serial(evictTotal)
|
||||
}
|
||||
|
||||
function markDirty(environmentId: string): void {
|
||||
dirty.add(environmentId)
|
||||
if (flushDelayMs === 0) {
|
||||
flush()
|
||||
void flush()
|
||||
return
|
||||
}
|
||||
if (!timer) {
|
||||
timer = setTimeout(flush, flushDelayMs)
|
||||
timer = setTimeout(() => void flush(), flushDelayMs)
|
||||
timer.unref?.()
|
||||
}
|
||||
}
|
||||
@@ -198,81 +203,86 @@ export function createCloudOfflineCache(options: {
|
||||
if (!OFFLINE_READ_METHODS.has(method)) {
|
||||
return
|
||||
}
|
||||
const file = load(environmentId)
|
||||
const key = stableKey(method, params)
|
||||
const existing = file.entries[key]
|
||||
const at = now()
|
||||
if (existing && at - existing.at < limits.minRecordIntervalMs) {
|
||||
return
|
||||
}
|
||||
const resultJson = JSON.stringify(response.result ?? null)
|
||||
const bytes = resultJson.length + key.length
|
||||
if (bytes > limits.maxEntryBytes) {
|
||||
// Too big to keep; don't serve an older, smaller answer as if it were current either.
|
||||
if (existing) {
|
||||
delete file.entries[key]
|
||||
markDirty(environmentId)
|
||||
const applied = load(environmentId).then((file) => {
|
||||
const key = stableKey(method, params)
|
||||
const existing = file.entries[key]
|
||||
if (existing && at - existing.at < limits.minRecordIntervalMs) {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
file.entries[key] = {
|
||||
method,
|
||||
params: params ?? null,
|
||||
resultJson,
|
||||
runtimeId: response._meta.runtimeId,
|
||||
at,
|
||||
bytes
|
||||
}
|
||||
file.updatedAt = at
|
||||
evictWithin(file)
|
||||
markDirty(environmentId)
|
||||
const resultJson = JSON.stringify(response.result ?? null)
|
||||
const bytes = resultJson.length + key.length
|
||||
if (bytes > limits.maxEntryBytes) {
|
||||
// Too big to keep; don't serve an older, smaller answer as if it were current either.
|
||||
if (existing) {
|
||||
delete file.entries[key]
|
||||
markDirty(environmentId)
|
||||
}
|
||||
return
|
||||
}
|
||||
file.entries[key] = {
|
||||
method,
|
||||
params: params ?? null,
|
||||
resultJson,
|
||||
runtimeId: response._meta.runtimeId,
|
||||
at,
|
||||
bytes
|
||||
}
|
||||
file.updatedAt = at
|
||||
evictWithin(file)
|
||||
markDirty(environmentId)
|
||||
})
|
||||
applying.add(applied)
|
||||
void applied.finally(() => applying.delete(applied))
|
||||
},
|
||||
lookup(environmentId, method, params) {
|
||||
async lookup(environmentId, method, params) {
|
||||
if (!OFFLINE_READ_METHODS.has(method)) {
|
||||
return null
|
||||
}
|
||||
const entry = load(environmentId).entries[stableKey(method, params)]
|
||||
await Promise.all(applying)
|
||||
const entry = (await load(environmentId)).entries[stableKey(method, params)]
|
||||
return entry ? decode(entry) : null
|
||||
},
|
||||
entries(environmentId, method) {
|
||||
return Object.values(load(environmentId).entries)
|
||||
async entries(environmentId, method) {
|
||||
await Promise.all(applying)
|
||||
return Object.values((await load(environmentId)).entries)
|
||||
.filter((entry) => method === undefined || entry.method === method)
|
||||
.sort((a, b) => b.at - a.at)
|
||||
.map(decode)
|
||||
},
|
||||
forget(environmentId) {
|
||||
generation++
|
||||
loaded.delete(environmentId)
|
||||
dirty.delete(environmentId)
|
||||
rmSync(pathOf(environmentId), { force: true })
|
||||
return serial(() => rm(pathOf(environmentId), { force: true }))
|
||||
},
|
||||
prune(keep) {
|
||||
const keepFiles = new Set([...keep].map(fileName))
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(options.root)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const name of names) {
|
||||
if (!keepFiles.has(name)) {
|
||||
rmSync(join(options.root, name), { force: true })
|
||||
}
|
||||
}
|
||||
generation++
|
||||
for (const environmentId of loaded.keys()) {
|
||||
if (!keep.has(environmentId)) {
|
||||
loaded.delete(environmentId)
|
||||
dirty.delete(environmentId)
|
||||
}
|
||||
}
|
||||
const keepFiles = new Set([...keep].map(fileName))
|
||||
return serial(async () => {
|
||||
const names = await readdir(options.root).catch(() => [])
|
||||
for (const name of names) {
|
||||
if (!keepFiles.has(name)) {
|
||||
await rm(join(options.root, name), { force: true })
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
clear() {
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
generation++
|
||||
loaded.clear()
|
||||
dirty.clear()
|
||||
rmSync(options.root, { recursive: true, force: true })
|
||||
return serial(() => rm(options.root, { recursive: true, force: true }))
|
||||
},
|
||||
flush
|
||||
}
|
||||
|
||||
@@ -26,9 +26,15 @@ import {
|
||||
type CloudOfflineCache,
|
||||
type OfflineCacheCodec
|
||||
} from './cloud-offline-cache'
|
||||
import { createOwedWorkBeat } from './cloud-offline-beat'
|
||||
import { setCloudOfflineReset } from './cloud-offline-reset'
|
||||
import { safeStorageCodec, setCloudOfflineObserver } from './cloud-offline-seam'
|
||||
import { archiveCheckoutsFromCache, buildOfflineSnapshot } from './cloud-offline-snapshot'
|
||||
import {
|
||||
archiveCheckoutsFromCache,
|
||||
buildOfflineSnapshot,
|
||||
stringParam,
|
||||
terminalHandlesOf
|
||||
} from './cloud-offline-snapshot'
|
||||
import { getHostedWorkspaceService, setArchiveCheckoutsProvider } from './hosted-workspace-service'
|
||||
|
||||
type CloudRuntimeInfo = {
|
||||
@@ -40,6 +46,9 @@ type CloudRuntimeInfo = {
|
||||
|
||||
const CAPTURE_BUDGET_MS = 8_000
|
||||
const MAX_CAPTURED_TERMINALS = 12
|
||||
/** Background delivery cadence while prompts are owed; doubles while nothing moves. */
|
||||
const BEAT_MS = 30_000
|
||||
const MAX_BEAT_BACKOFF_STEPS = 4
|
||||
|
||||
export type CloudOfflineService = {
|
||||
cache: CloudOfflineCache
|
||||
@@ -155,9 +164,8 @@ export function installCloudOfflineService(deps: {
|
||||
// Chats the window has read stay current: refresh their tail pages.
|
||||
const sessions = [
|
||||
...new Set(
|
||||
cache
|
||||
.entries(env, 'agentSession.history')
|
||||
.map((entry) => (entry.params as { sessionId?: string } | null)?.sessionId)
|
||||
(await cache.entries(env, 'agentSession.history'))
|
||||
.map((entry) => stringParam(entry.params, 'sessionId'))
|
||||
.filter((id): id is string => typeof id === 'string')
|
||||
)
|
||||
].slice(0, 20)
|
||||
@@ -174,15 +182,11 @@ export function installCloudOfflineService(deps: {
|
||||
)
|
||||
)
|
||||
])
|
||||
const terminals = (
|
||||
(list as { terminals?: { handle: string }[] } | null)?.terminals ?? []
|
||||
).slice(0, MAX_CAPTURED_TERMINALS)
|
||||
const handles = terminalHandlesOf(list).slice(0, MAX_CAPTURED_TERMINALS)
|
||||
await Promise.all(
|
||||
terminals.map((terminal) =>
|
||||
readInto(env, 'terminal.read', { terminal: terminal.handle, limit: 400 }, deadline)
|
||||
)
|
||||
handles.map((terminal) => readInto(env, 'terminal.read', { terminal, limit: 400 }, deadline))
|
||||
)
|
||||
cache.flush()
|
||||
await cache.flush()
|
||||
}
|
||||
|
||||
async function locate(workspaceId: string): Promise<WorkspaceAvailability> {
|
||||
@@ -218,23 +222,43 @@ export function installCloudOfflineService(deps: {
|
||||
return opening === 'up'
|
||||
},
|
||||
call: deps.call,
|
||||
onChange: (workspaceId) => broadcast(CH.queuedPromptsChanged, { workspaceId }),
|
||||
onChange: (workspaceId) => {
|
||||
broadcast(CH.queuedPromptsChanged, { workspaceId })
|
||||
beat.poke()
|
||||
},
|
||||
log
|
||||
})
|
||||
|
||||
// Background: deliver to VMs already up (never wakes) and drop removed workspaces, only while
|
||||
// prompts are owed. A live answer from a workspace (it is up) delivers its prompts at once.
|
||||
const beat = createOwedWorkBeat({
|
||||
nextDueAt: () => queue.nextAttemptAt(),
|
||||
pass: async () => {
|
||||
invalidate()
|
||||
await queue.drive()
|
||||
void cache.prune(new Set(runtimes().byEnvironment.keys()))
|
||||
},
|
||||
baseMs: BEAT_MS,
|
||||
maxBackoffSteps: MAX_BEAT_BACKOFF_STEPS
|
||||
})
|
||||
|
||||
setCloudOfflineObserver((environmentId, method, params, response) => {
|
||||
if (response.ok && runtimes().byEnvironment.has(environmentId)) {
|
||||
const info = runtimes().byEnvironment.get(environmentId)
|
||||
if (response.ok && info) {
|
||||
cache.record(environmentId, method, params, response)
|
||||
if (queue.nextAttemptAt() !== null) {
|
||||
void queue.drive(info.workspaceId)
|
||||
}
|
||||
}
|
||||
})
|
||||
setCloudOfflineReset(() => {
|
||||
cache.clear()
|
||||
void cache.clear()
|
||||
queue.clear()
|
||||
})
|
||||
setArchiveCheckoutsProvider(async (workspaceId) => {
|
||||
const info = runtimes().byWorkspace.get(workspaceId)
|
||||
return info
|
||||
? archiveCheckoutsFromCache(
|
||||
? await archiveCheckoutsFromCache(
|
||||
cache,
|
||||
info.environmentId,
|
||||
info.projectRoot ?? '/vercel/sandbox/project'
|
||||
@@ -247,11 +271,11 @@ export function installCloudOfflineService(deps: {
|
||||
}
|
||||
ipcMain.handle(
|
||||
CH.getSnapshot,
|
||||
(_event, args: { workspaceId: string }): CloudOfflineSnapshot | null => {
|
||||
async (_event, args: { workspaceId: string }): Promise<CloudOfflineSnapshot | null> => {
|
||||
invalidate()
|
||||
const info = runtimes().byWorkspace.get(args.workspaceId)
|
||||
return info
|
||||
? buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep)
|
||||
? await buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep)
|
||||
: null
|
||||
}
|
||||
)
|
||||
@@ -273,14 +297,8 @@ export function installCloudOfflineService(deps: {
|
||||
queue.edit(args.id, args.text)
|
||||
)
|
||||
|
||||
// Background: deliver to VMs that are already up (never wakes), and drop removed workspaces.
|
||||
const beat = setInterval(() => {
|
||||
invalidate()
|
||||
void queue.drive()
|
||||
cache.prune(new Set(runtimes().byEnvironment.keys()))
|
||||
}, 30_000)
|
||||
beat.unref?.()
|
||||
const startup = setTimeout(() => void queue.drive(), 5_000)
|
||||
// Startup: deliver what survived a restart (never wakes), and drop removed workspaces.
|
||||
const startup = setTimeout(() => void beat.runNow(), 5_000)
|
||||
startup.unref?.()
|
||||
|
||||
return {
|
||||
@@ -288,9 +306,10 @@ export function installCloudOfflineService(deps: {
|
||||
queue,
|
||||
capture,
|
||||
dispose() {
|
||||
clearInterval(beat)
|
||||
beat.dispose()
|
||||
clearTimeout(startup)
|
||||
cache.flush()
|
||||
void cache.flush()
|
||||
void queue.flushed()
|
||||
setCloudOfflineObserver(null)
|
||||
setCloudOfflineReset(null)
|
||||
setArchiveCheckoutsProvider(null)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Turns cached RPC answers into what the asleep view shows, and into archive git metadata.
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
CloudOfflineChat,
|
||||
CloudOfflineChatMessage,
|
||||
@@ -26,40 +27,98 @@ export function stripAnsi(text: string): string {
|
||||
return text.replace(ANSI, '').replace(/\r(?!\n)/g, '')
|
||||
}
|
||||
|
||||
type HistoryResult = {
|
||||
ok?: boolean
|
||||
page?: {
|
||||
sessionId?: string
|
||||
items?: {
|
||||
itemId: string
|
||||
observedAt: number
|
||||
body: { kind: string; role?: string; blocks?: { type: string; text?: string }[] }
|
||||
}[]
|
||||
}
|
||||
// Cached answers came from the VM: parse leniently, and a malformed piece is skipped, never trusted.
|
||||
const Text = z.string()
|
||||
const ChatItemSchema = z.looseObject({
|
||||
itemId: Text,
|
||||
observedAt: z.number(),
|
||||
body: z.looseObject({
|
||||
kind: Text,
|
||||
role: Text.optional(),
|
||||
blocks: z.array(z.looseObject({ type: Text, text: z.unknown().optional() })).optional()
|
||||
})
|
||||
})
|
||||
const HistoryResultSchema = z.looseObject({
|
||||
page: z
|
||||
.looseObject({ sessionId: Text.optional(), items: z.array(z.unknown()).optional() })
|
||||
.optional()
|
||||
})
|
||||
const TerminalListSchema = z.looseObject({
|
||||
terminals: z
|
||||
.array(
|
||||
z.looseObject({
|
||||
handle: Text,
|
||||
title: Text.nullable().optional(),
|
||||
paneTitle: Text.optional()
|
||||
})
|
||||
)
|
||||
.catch([])
|
||||
.optional()
|
||||
})
|
||||
// `terminal.read` answers `{terminal: RuntimeTerminalRead}`.
|
||||
const TerminalReadSchema = z.looseObject({
|
||||
terminal: z.looseObject({ handle: Text.optional(), tail: z.array(Text).optional() }).optional()
|
||||
})
|
||||
const StatusResultSchema = z.looseObject({
|
||||
entries: z
|
||||
.array(z.looseObject({ path: Text, status: Text, area: Text }))
|
||||
.catch([])
|
||||
.optional(),
|
||||
head: Text.optional().catch(undefined),
|
||||
branch: Text.optional().catch(undefined)
|
||||
})
|
||||
const HistoryItemsSchema = z.looseObject({
|
||||
items: z
|
||||
.array(
|
||||
z.looseObject({
|
||||
id: Text,
|
||||
subject: Text,
|
||||
author: Text.optional(),
|
||||
timestamp: z.number().optional()
|
||||
})
|
||||
)
|
||||
.catch([])
|
||||
.optional()
|
||||
})
|
||||
const ParamsSchema = z.record(z.string(), z.unknown())
|
||||
|
||||
/** A string field of a cached call's params, if it has one. */
|
||||
export function stringParam(params: unknown, key: string): string | undefined {
|
||||
const parsed = ParamsSchema.safeParse(params)
|
||||
const value = parsed.success ? parsed.data[key] : undefined
|
||||
return typeof value === 'string' ? value : undefined
|
||||
}
|
||||
|
||||
/** Terminal handles from a cached `terminal.list` answer. */
|
||||
export function terminalHandlesOf(result: unknown): string[] {
|
||||
const parsed = TerminalListSchema.safeParse(result)
|
||||
return parsed.success ? (parsed.data.terminals ?? []).map((terminal) => terminal.handle) : []
|
||||
}
|
||||
|
||||
function chatOf(entry: OfflineCacheEntry): CloudOfflineChat | null {
|
||||
const result = entry.result as HistoryResult
|
||||
const sessionId =
|
||||
result?.page?.sessionId ?? (entry.params as { sessionId?: string } | null)?.sessionId
|
||||
if (!sessionId || !Array.isArray(result?.page?.items)) {
|
||||
const parsed = HistoryResultSchema.safeParse(entry.result)
|
||||
const page = parsed.success ? parsed.data.page : undefined
|
||||
const sessionId = page?.sessionId ?? stringParam(entry.params, 'sessionId')
|
||||
if (!sessionId || !Array.isArray(page?.items)) {
|
||||
return null
|
||||
}
|
||||
const messages: CloudOfflineChatMessage[] = []
|
||||
for (const item of result.page.items) {
|
||||
if (item.body?.kind !== 'message' || !Array.isArray(item.body.blocks)) {
|
||||
for (const raw of page.items) {
|
||||
const item = ChatItemSchema.safeParse(raw)
|
||||
if (!item.success || item.data.body.kind !== 'message' || !item.data.body.blocks) {
|
||||
continue
|
||||
}
|
||||
const text = item.body.blocks
|
||||
.filter((block) => block.type === 'text' && typeof block.text === 'string')
|
||||
.map((block) => block.text)
|
||||
const text = item.data.body.blocks
|
||||
.flatMap((block) =>
|
||||
block.type === 'text' && typeof block.text === 'string' ? [block.text] : []
|
||||
)
|
||||
.join('\n')
|
||||
.trim()
|
||||
const role = item.body.role
|
||||
const role = item.data.body.role
|
||||
if (!text || (role !== 'user' && role !== 'assistant' && role !== 'system')) {
|
||||
continue
|
||||
}
|
||||
messages.push({ itemId: item.itemId, role, text, at: item.observedAt })
|
||||
messages.push({ itemId: item.data.itemId, role, text, at: item.data.observedAt })
|
||||
}
|
||||
return { sessionId, at: entry.at, messages: messages.slice(-MAX_MESSAGES) }
|
||||
}
|
||||
@@ -68,7 +127,7 @@ function chatOf(entry: OfflineCacheEntry): CloudOfflineChat | null {
|
||||
function chatsOf(entries: OfflineCacheEntry[]): CloudOfflineChat[] {
|
||||
const bySession = new Map<string, CloudOfflineChat>()
|
||||
for (const entry of entries) {
|
||||
const direction = (entry.params as { direction?: string } | null)?.direction
|
||||
const direction = stringParam(entry.params, 'direction')
|
||||
if (direction && direction !== 'tail') {
|
||||
continue
|
||||
}
|
||||
@@ -85,17 +144,15 @@ function chatsOf(entries: OfflineCacheEntry[]): CloudOfflineChat[] {
|
||||
return [...bySession.values()].sort((a, b) => b.at - a.at)
|
||||
}
|
||||
|
||||
function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineTerminal[] {
|
||||
async function terminalsOf(
|
||||
cache: CloudOfflineCache,
|
||||
environmentId: string
|
||||
): Promise<CloudOfflineTerminal[]> {
|
||||
// Every listing contributes titles (a filtered listing can be empty); newest first wins.
|
||||
const titles = new Map<string, string | null>()
|
||||
for (const list of cache.entries(environmentId, 'terminal.list')) {
|
||||
const listed =
|
||||
(
|
||||
list.result as {
|
||||
terminals?: { handle: string; title: string | null; paneTitle?: string }[]
|
||||
} | null
|
||||
)?.terminals ?? []
|
||||
for (const terminal of listed) {
|
||||
for (const list of await cache.entries(environmentId, 'terminal.list')) {
|
||||
const parsed = TerminalListSchema.safeParse(list.result)
|
||||
for (const terminal of parsed.success ? (parsed.data.terminals ?? []) : []) {
|
||||
if (!titles.has(terminal.handle)) {
|
||||
titles.set(terminal.handle, terminal.paneTitle ?? terminal.title ?? null)
|
||||
}
|
||||
@@ -103,12 +160,11 @@ function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOffl
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
const terminals: CloudOfflineTerminal[] = []
|
||||
for (const entry of cache.entries(environmentId, 'terminal.read')) {
|
||||
// `terminal.read` answers `{terminal: RuntimeTerminalRead}`.
|
||||
const wrapped = entry.result as { terminal?: { handle?: string; tail?: string[] } } | null
|
||||
const result = wrapped?.terminal
|
||||
const handle = result?.handle ?? (entry.params as { terminal?: string } | null)?.terminal
|
||||
if (!handle || seen.has(handle) || !Array.isArray(result?.tail)) {
|
||||
for (const entry of await cache.entries(environmentId, 'terminal.read')) {
|
||||
const parsed = TerminalReadSchema.safeParse(entry.result)
|
||||
const result = parsed.success ? parsed.data.terminal : undefined
|
||||
const handle = result?.handle ?? stringParam(entry.params, 'terminal')
|
||||
if (!handle || seen.has(handle) || !result?.tail) {
|
||||
continue
|
||||
}
|
||||
seen.add(handle)
|
||||
@@ -122,22 +178,19 @@ function terminalsOf(cache: CloudOfflineCache, environmentId: string): CloudOffl
|
||||
return terminals
|
||||
}
|
||||
|
||||
type StatusResult = {
|
||||
entries?: { path: string; status: string; area: string }[]
|
||||
head?: string
|
||||
branch?: string
|
||||
}
|
||||
type HistoryItems = {
|
||||
items?: { id: string; subject: string; author?: string; timestamp?: number }[]
|
||||
}
|
||||
|
||||
function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit | null {
|
||||
const status = cache.entries(environmentId, 'git.status')[0]
|
||||
const history = cache.entries(environmentId, 'git.history')[0]
|
||||
async function gitOf(
|
||||
cache: CloudOfflineCache,
|
||||
environmentId: string
|
||||
): Promise<CloudOfflineGit | null> {
|
||||
const status = (await cache.entries(environmentId, 'git.status'))[0]
|
||||
const history = (await cache.entries(environmentId, 'git.history'))[0]
|
||||
if (!status && !history) {
|
||||
return null
|
||||
}
|
||||
const statusResult = (status?.result ?? {}) as StatusResult
|
||||
const parsedStatus = StatusResultSchema.safeParse(status?.result ?? {})
|
||||
const statusResult = parsedStatus.success ? parsedStatus.data : {}
|
||||
const parsedHistory = HistoryItemsSchema.safeParse(history?.result ?? {})
|
||||
const items = parsedHistory.success ? (parsedHistory.data.items ?? []) : []
|
||||
const entries = statusResult.entries ?? []
|
||||
return {
|
||||
branch: statusResult.branch?.replace(/^refs\/heads\//, '') ?? null,
|
||||
@@ -146,7 +199,7 @@ function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit
|
||||
.slice(0, MAX_CHANGES)
|
||||
.map(({ path, status: s, area }) => ({ path, status: s, area })),
|
||||
changeCount: entries.length,
|
||||
commits: (((history?.result ?? {}) as HistoryItems).items ?? []).slice(0, 20).map((item) => ({
|
||||
commits: items.slice(0, 20).map((item) => ({
|
||||
id: item.id,
|
||||
subject: item.subject,
|
||||
author: item.author ?? null,
|
||||
@@ -156,15 +209,15 @@ function gitOf(cache: CloudOfflineCache, environmentId: string): CloudOfflineGit
|
||||
}
|
||||
}
|
||||
|
||||
export function buildOfflineSnapshot(
|
||||
export async function buildOfflineSnapshot(
|
||||
cache: CloudOfflineCache,
|
||||
environmentId: string,
|
||||
workspaceId: string,
|
||||
asleep: boolean
|
||||
): CloudOfflineSnapshot {
|
||||
const git = gitOf(cache, environmentId)
|
||||
const terminals = terminalsOf(cache, environmentId)
|
||||
const chats = chatsOf(cache.entries(environmentId, 'agentSession.history'))
|
||||
): Promise<CloudOfflineSnapshot> {
|
||||
const git = await gitOf(cache, environmentId)
|
||||
const terminals = await terminalsOf(cache, environmentId)
|
||||
const chats = chatsOf(await cache.entries(environmentId, 'agentSession.history'))
|
||||
const times = [git?.at ?? 0, ...terminals.map((t) => t.at), ...chats.map((c) => c.at)].filter(
|
||||
(t) => t > 0
|
||||
)
|
||||
@@ -188,12 +241,12 @@ const STATUS_LETTER: Record<string, string> = {
|
||||
}
|
||||
|
||||
/** Archive metadata from the cache, for archiving a VM that is already asleep. */
|
||||
export function archiveCheckoutsFromCache(
|
||||
export async function archiveCheckoutsFromCache(
|
||||
cache: CloudOfflineCache,
|
||||
environmentId: string,
|
||||
projectRoot: string
|
||||
): HostedArchiveCheckout[] | null {
|
||||
const git = gitOf(cache, environmentId)
|
||||
): Promise<HostedArchiveCheckout[] | null> {
|
||||
const git = await gitOf(cache, environmentId)
|
||||
if (!git || (!git.branch && !git.head)) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
// prepare: pack in the VM → download in chunks → fetch the branch into the local repo.
|
||||
// finish (after the window created the local worktree): apply staged/unstaged diffs, untracked
|
||||
// files, and install Claude/Codex sessions remapped to the new path so native resume works.
|
||||
import { execFile } from 'node:child_process'
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { cp, lstat, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'
|
||||
import { join, relative } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { z } from 'zod'
|
||||
import { gitExecFileAsync } from '../git/command-runner/git-exec-file'
|
||||
import {
|
||||
CLOUD_TRANSFER_DIR,
|
||||
CLOUD_TRANSFER_LOG,
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
} from '../../shared/hosted-sandbox/cloud-transfer-pack'
|
||||
import type { RuntimeCall } from './hosted-agent-auto-resume'
|
||||
|
||||
const run = promisify(execFile)
|
||||
const CHUNK_BYTES = 512 * 1024
|
||||
const PACK_TIMEOUT_MS = 10 * 60_000
|
||||
|
||||
@@ -36,10 +35,33 @@ export type Prepared = {
|
||||
}
|
||||
|
||||
async function git(cwd: string, args: string[]): Promise<string> {
|
||||
const { stdout } = await run('git', args, { cwd, maxBuffer: 64 * 1024 * 1024 })
|
||||
const { stdout } = await gitExecFileAsync(args, {
|
||||
cwd,
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
// Fetching a large bundle can outlast the default read deadline.
|
||||
timeout: PACK_TIMEOUT_MS
|
||||
})
|
||||
return stdout.trim()
|
||||
}
|
||||
|
||||
// orcad RPC replies, validated instead of trusted: the VM side is not this process.
|
||||
const TerminalCreatedSchema = z.looseObject({
|
||||
terminal: z.union([z.string(), z.looseObject({ handle: z.string().optional() })]).optional()
|
||||
})
|
||||
const FileStatSchema = z.looseObject({ size: z.number().optional() })
|
||||
const FileChunkSchema = z.looseObject({
|
||||
contentBase64: z.string(),
|
||||
bytesRead: z.number().optional(),
|
||||
eof: z.boolean().optional()
|
||||
})
|
||||
|
||||
async function readChunk(
|
||||
call: RuntimeCall,
|
||||
params: { worktree: string; relativePath: string; offset: number; length: number }
|
||||
): Promise<z.infer<typeof FileChunkSchema>> {
|
||||
return FileChunkSchema.parse(await call('files.readChunk', params))
|
||||
}
|
||||
|
||||
export async function fileSize(path: string): Promise<number> {
|
||||
return stat(path)
|
||||
.then((s) => s.size)
|
||||
@@ -48,6 +70,14 @@ export async function fileSize(path: string): Promise<number> {
|
||||
|
||||
export type WorktreeRow = { id?: unknown; path?: unknown }
|
||||
|
||||
/** `worktree.list` reply: rows stay loose and pickCloudWorktree checks their fields. */
|
||||
export const WorktreeListingSchema = z.looseObject({
|
||||
worktrees: z
|
||||
.array(z.looseObject({ id: z.unknown(), path: z.unknown() }))
|
||||
.optional()
|
||||
.catch(undefined)
|
||||
})
|
||||
|
||||
/** The orcad-side worktree for this workspace: its id, else the VM project root, else the only one. */
|
||||
export function pickCloudWorktree(
|
||||
rows: WorktreeRow[],
|
||||
@@ -75,14 +105,16 @@ async function runInCloud(
|
||||
commandLine: string,
|
||||
title: string
|
||||
): Promise<void> {
|
||||
const created = (await call('terminal.create', {
|
||||
worktree,
|
||||
command: commandLine,
|
||||
title,
|
||||
presentation: 'background',
|
||||
focus: false,
|
||||
activate: false
|
||||
})) as { terminal?: { handle?: string } | string }
|
||||
const created = TerminalCreatedSchema.parse(
|
||||
await call('terminal.create', {
|
||||
worktree,
|
||||
command: commandLine,
|
||||
title,
|
||||
presentation: 'background',
|
||||
focus: false,
|
||||
activate: false
|
||||
})
|
||||
)
|
||||
const handle = typeof created.terminal === 'string' ? created.terminal : created.terminal?.handle
|
||||
if (!handle) {
|
||||
throw new Error('Could not run a command in the cloud workspace.')
|
||||
@@ -127,16 +159,9 @@ async function readCloudTail(
|
||||
worktree: string,
|
||||
relativePath: string
|
||||
): Promise<string> {
|
||||
const stat = (await call('files.stat', { worktree, relativePath })) as { size?: number }
|
||||
const stat = FileStatSchema.parse(await call('files.stat', { worktree, relativePath }))
|
||||
const offset = Math.max(0, (stat.size ?? 0) - 8192)
|
||||
const page = (await call('files.readChunk', {
|
||||
worktree,
|
||||
relativePath,
|
||||
offset,
|
||||
length: 8192
|
||||
})) as {
|
||||
contentBase64: string
|
||||
}
|
||||
const page = await readChunk(call, { worktree, relativePath, offset, length: 8192 })
|
||||
return Buffer.from(page.contentBase64, 'base64').toString('utf8')
|
||||
}
|
||||
|
||||
@@ -155,14 +180,7 @@ async function readCloudText(
|
||||
worktree: string,
|
||||
relativePath: string
|
||||
): Promise<string> {
|
||||
const page = (await call('files.readChunk', {
|
||||
worktree,
|
||||
relativePath,
|
||||
offset: 0,
|
||||
length: CHUNK_BYTES
|
||||
})) as {
|
||||
contentBase64: string
|
||||
}
|
||||
const page = await readChunk(call, { worktree, relativePath, offset: 0, length: CHUNK_BYTES })
|
||||
return Buffer.from(page.contentBase64, 'base64').toString('utf8')
|
||||
}
|
||||
|
||||
@@ -178,16 +196,7 @@ export async function downloadCloudFile(
|
||||
let offset = 0
|
||||
try {
|
||||
for (;;) {
|
||||
const page = (await call('files.readChunk', {
|
||||
worktree,
|
||||
relativePath,
|
||||
offset,
|
||||
length: CHUNK_BYTES
|
||||
})) as {
|
||||
contentBase64: string
|
||||
bytesRead: number
|
||||
eof: boolean
|
||||
}
|
||||
const page = await readChunk(call, { worktree, relativePath, offset, length: CHUNK_BYTES })
|
||||
const bytes = Buffer.from(page.contentBase64, 'base64')
|
||||
if (!out.write(bytes)) {
|
||||
await new Promise<void>((resolve) => out.once('drain', () => resolve()))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
@@ -128,9 +128,12 @@ describe('cloud transfer housekeeping', () => {
|
||||
mkdirSync(join(root, 'abandoned'))
|
||||
writeFileSync(join(root, 'abandoned', 'transfer.tar'), 'x')
|
||||
mkdirSync(join(root, 'kept', 'unapplied'), { recursive: true })
|
||||
expect(await sweepCloudTransfers(root, Date.now())).toBe(1)
|
||||
expect(await sweepCloudTransfers(root, Date.now() + 31 * 86_400_000)).toBe(1)
|
||||
expect(await sweepCloudTransfers(join(root, 'missing'), Date.now())).toBe(0)
|
||||
// Fixed times: the leftovers were written at T0; the sweep runs a minute and a month later.
|
||||
const T0 = 1_800_000_000_000
|
||||
utimesSync(join(root, 'kept', 'unapplied'), T0 / 1000, T0 / 1000)
|
||||
expect(await sweepCloudTransfers(root, T0 + 60_000)).toBe(1)
|
||||
expect(await sweepCloudTransfers(root, T0 + 31 * 86_400_000)).toBe(1)
|
||||
expect(await sweepCloudTransfers(join(root, 'missing'), T0)).toBe(0)
|
||||
})
|
||||
|
||||
it('installs only session transcripts, never other files from the project folder', async () => {
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
packInCloud,
|
||||
pickCloudWorktree,
|
||||
type Prepared,
|
||||
type WorktreeRow
|
||||
WorktreeListingSchema
|
||||
} from './cloud-transfer-steps'
|
||||
import { createHostedRuntimeEnvironmentCall } from './hosted-runtime-environment-call'
|
||||
import { findCloudRuntime } from './hosted-workspace-service'
|
||||
@@ -112,7 +112,7 @@ export function installCloudTransferHandlers(deps: {
|
||||
let selector: string | null = null
|
||||
try {
|
||||
step('packing')
|
||||
const listing = (await call('worktree.list', {})) as { worktrees?: WorktreeRow[] }
|
||||
const listing = WorktreeListingSchema.parse(await call('worktree.list', {}))
|
||||
const connection = runtime.recipeResult
|
||||
? getEphemeralVmRecipeResultConnection(runtime.recipeResult)
|
||||
: null
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createHostedEnvironmentBuildFollowers,
|
||||
type HostedEnvironmentBuildFollowers
|
||||
@@ -143,9 +143,14 @@ describe('createHostedEnvironmentBuildFollowers', () => {
|
||||
// Let both watches finish before reading, so both buffers filled up.
|
||||
await followers.poll(client, ENV_ID, BUILD_ID, 0, 0)
|
||||
await followers.poll(client, ENV_ID, other, 0, 0)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
const a = await followers.poll(client, ENV_ID, BUILD_ID, 0, 0)
|
||||
const b = await followers.poll(client, ENV_ID, other, 0, 0)
|
||||
const [a, b] = await vi.waitFor(async () => {
|
||||
const both = await Promise.all([
|
||||
followers!.poll(client, ENV_ID, BUILD_ID, 0, 0),
|
||||
followers!.poll(client, ENV_ID, other, 0, 0)
|
||||
])
|
||||
expect(both.every((result) => result.done)).toBe(true)
|
||||
return both
|
||||
})
|
||||
const total = [...a.chunks, ...b.chunks].reduce((sum, entry) => sum + entry.data.length, 0)
|
||||
expect(total).toBeLessThanOrEqual(500)
|
||||
expect(a.truncated || b.truncated).toBe(true)
|
||||
|
||||
@@ -124,16 +124,17 @@ export function createHostedEnvironmentBuildFollowers(
|
||||
}
|
||||
|
||||
// Followers whose CLI went away keep streaming until swept, so sweep on a slow beat too.
|
||||
let sweeper: ReturnType<typeof setInterval> | null = null
|
||||
// Runs only while followers exist and stops once the last one is swept.
|
||||
let sweeper: ReturnType<typeof setTimeout> | null = null
|
||||
const ensureSweeper = (): void => {
|
||||
if (sweeper) {
|
||||
return
|
||||
}
|
||||
sweeper = setInterval(() => {
|
||||
sweeper = setTimeout(() => {
|
||||
sweeper = null
|
||||
sweep()
|
||||
if (followers.size === 0 && sweeper) {
|
||||
clearInterval(sweeper)
|
||||
sweeper = null
|
||||
if (followers.size > 0) {
|
||||
ensureSweeper()
|
||||
}
|
||||
}, ABANDONED_AFTER_MS / 2)
|
||||
sweeper.unref?.()
|
||||
@@ -269,7 +270,7 @@ export function createHostedEnvironmentBuildFollowers(
|
||||
},
|
||||
dispose() {
|
||||
if (sweeper) {
|
||||
clearInterval(sweeper)
|
||||
clearTimeout(sweeper)
|
||||
sweeper = null
|
||||
}
|
||||
// Deleting the current key while iterating a Map is safe.
|
||||
|
||||
@@ -267,6 +267,7 @@ describe('watchHostedEnvironmentBuild', () => {
|
||||
},
|
||||
// Six heartbeats 15 ms apart span three idle windows of 30 ms without a single log line.
|
||||
async pull(controller) {
|
||||
// ast-grep-ignore: test-no-real-time-wait -- the heartbeats must arrive in real time to straddle the stream's idle window.
|
||||
await new Promise((resolve) => setTimeout(resolve, 15))
|
||||
if (beats++ < 6) {
|
||||
controller.enqueue(encoder.encode(line({ type: 'heartbeat', at: beats })))
|
||||
|
||||
@@ -2,8 +2,28 @@
|
||||
// opening request is held to its caller's pairing as of before that wake, then to the pairing the
|
||||
// wake made; any other change still refuses it.
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments'
|
||||
|
||||
const BEFORE = { id: 'env-vm', pairingRevision: 1, runtimeId: 'before', createdAt: 0 }
|
||||
const BEFORE: KnownRuntimeEnvironment = {
|
||||
id: 'env-vm',
|
||||
name: 'VM',
|
||||
pairingRevision: 1,
|
||||
runtimeId: 'before',
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastUsedAt: null,
|
||||
endpoints: [
|
||||
{
|
||||
id: 'ep',
|
||||
kind: 'websocket',
|
||||
label: 'VM',
|
||||
endpoint: 'ws://vm.test',
|
||||
deviceToken: 'token',
|
||||
publicKeyB64: 'key'
|
||||
}
|
||||
],
|
||||
preferredEndpointId: 'ep'
|
||||
}
|
||||
const AFTER_WAKE = { id: 'env-vm', pairingRevision: 2, runtimeId: 'after', createdAt: 0 }
|
||||
|
||||
type Prepared = {
|
||||
@@ -73,7 +93,7 @@ describe('a fenced request that waited through a wake already in flight', () =>
|
||||
undefined,
|
||||
{ pairingRevision, runtimeId: 'before' },
|
||||
undefined,
|
||||
{ before: BEFORE as never, wokenPairingRevision }
|
||||
{ before: BEFORE, wokenPairingRevision }
|
||||
)
|
||||
|
||||
it('passes the pre-wake fence and then expects the pairing that wake made', async () => {
|
||||
|
||||
@@ -91,7 +91,9 @@ export class RuntimeRepositoryHooksCommands {
|
||||
hooks,
|
||||
mayNeedUpdate: has && !hooks && hasUnrecognizedOrcaYamlKeys(repo.path),
|
||||
// Dependencies come from an Orca Cloud environment build: no setup-script nudge.
|
||||
...(isEnvironmentBuildCheckout(repo.path) ? { environmentProvisioned: true as const } : {})
|
||||
...((await isEnvironmentBuildCheckout(repo.path))
|
||||
? { environmentProvisioned: true as const }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
OrcadDiskUsageParamsSchema
|
||||
} from '../../../../../shared/orcad-disk-usage'
|
||||
import type { Repo } from '../../../../../shared/repo-types'
|
||||
import {
|
||||
getRepoExecutionHostId,
|
||||
getRepoRoutingConnectionId,
|
||||
LOCAL_EXECUTION_HOST_ID
|
||||
} from '../../../../../shared/execution-host'
|
||||
import { readOrcadDiskUsage } from '../../../../orcad/orcad-disk-usage'
|
||||
|
||||
/** Workspace root first so it leads the result; then local repo checkouts and $HOME. */
|
||||
@@ -17,8 +22,8 @@ export function orcadDiskUsageProbePaths(args: {
|
||||
const repoPaths = args.repos
|
||||
.filter(
|
||||
(repo) =>
|
||||
!repo.connectionId &&
|
||||
(!repo.executionHostId || repo.executionHostId === 'local') &&
|
||||
getRepoRoutingConnectionId(repo) === null &&
|
||||
getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID &&
|
||||
isAbsolute(repo.path)
|
||||
)
|
||||
.map((repo) => repo.path)
|
||||
|
||||
@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest'
|
||||
import { hasEnvironmentBuildMarker, isEnvironmentBuildCheckout } from './environment-build-checkout'
|
||||
|
||||
describe('environment build checkout marker', () => {
|
||||
it('recognises a built primary checkout and its linked worktrees, and nothing else', () => {
|
||||
it('recognises a built primary checkout and its linked worktrees, and nothing else', async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-env-build-'))
|
||||
const primary = join(root, 'repo')
|
||||
const commonDir = join(primary, '.git')
|
||||
@@ -14,12 +14,12 @@ describe('environment build checkout marker', () => {
|
||||
mkdirSync(worktree)
|
||||
writeFileSync(join(worktree, '.git'), `gitdir: ${join(commonDir, 'worktrees', 'wt')}\n`)
|
||||
writeFileSync(join(commonDir, 'worktrees', 'wt', 'commondir'), '../..\n')
|
||||
expect(isEnvironmentBuildCheckout(primary)).toBe(false)
|
||||
expect(isEnvironmentBuildCheckout(worktree)).toBe(false)
|
||||
expect(await isEnvironmentBuildCheckout(primary)).toBe(false)
|
||||
expect(await isEnvironmentBuildCheckout(worktree)).toBe(false)
|
||||
writeFileSync(join(commonDir, 'orca-env-deps'), 'node_modules\n')
|
||||
expect(isEnvironmentBuildCheckout(primary)).toBe(true)
|
||||
expect(isEnvironmentBuildCheckout(worktree)).toBe(true)
|
||||
expect(hasEnvironmentBuildMarker('.git', primary)).toBe(true)
|
||||
expect(isEnvironmentBuildCheckout(join(root, 'missing'))).toBe(false)
|
||||
expect(await isEnvironmentBuildCheckout(primary)).toBe(true)
|
||||
expect(await isEnvironmentBuildCheckout(worktree)).toBe(true)
|
||||
expect(await hasEnvironmentBuildMarker('.git', primary)).toBe(true)
|
||||
expect(await isEnvironmentBuildCheckout(join(root, 'missing'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,39 +2,47 @@
|
||||
// repo's dependencies once and leave `<git common dir>/orca-env-deps` behind; every workspace created
|
||||
// from the build gets those folders. Such a checkout needs no per-workspace setup script, so Orca
|
||||
// does not nudge for one.
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs'
|
||||
import { access, readFile, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, join, resolve } from 'node:path'
|
||||
|
||||
const MARKER = 'orca-env-deps'
|
||||
|
||||
/** The git common dir of `repoPath` (primary checkout or linked worktree), or null. Sync and cheap. */
|
||||
function gitCommonDir(repoPath: string): string | null {
|
||||
/** The git common dir of `repoPath` (primary checkout or linked worktree), or null. */
|
||||
async function gitCommonDir(repoPath: string): Promise<string | null> {
|
||||
const dotGit = join(repoPath, '.git')
|
||||
try {
|
||||
const stat = statSync(dotGit)
|
||||
if (stat.isDirectory()) {
|
||||
if ((await stat(dotGit)).isDirectory()) {
|
||||
return dotGit
|
||||
}
|
||||
// A linked worktree: `.git` is a file naming its gitdir, which names the common dir.
|
||||
const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, 'utf8'))?.[1]?.trim()
|
||||
const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim()
|
||||
if (!pointer) {
|
||||
return null
|
||||
}
|
||||
const gitDir = isAbsolute(pointer) ? pointer : resolve(repoPath, pointer)
|
||||
const common = readFileSync(join(gitDir, 'commondir'), 'utf8').trim()
|
||||
const common = (await readFile(join(gitDir, 'commondir'), 'utf8')).trim()
|
||||
return isAbsolute(common) ? common : resolve(gitDir, common)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function isEnvironmentBuildCheckout(repoPath: string): boolean {
|
||||
const common = gitCommonDir(repoPath)
|
||||
return common !== null && existsSync(join(common, MARKER))
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function isEnvironmentBuildCheckout(repoPath: string): Promise<boolean> {
|
||||
const common = await gitCommonDir(repoPath)
|
||||
return common !== null && (await exists(join(common, MARKER)))
|
||||
}
|
||||
|
||||
/** Same check from a known common dir (the environment doctor already has it). */
|
||||
export function hasEnvironmentBuildMarker(commonDir: string, root: string): boolean {
|
||||
export function hasEnvironmentBuildMarker(commonDir: string, root: string): Promise<boolean> {
|
||||
const dir = isAbsolute(commonDir) ? commonDir : resolve(root, commonDir)
|
||||
return existsSync(join(dir, MARKER))
|
||||
return exists(join(dir, MARKER))
|
||||
}
|
||||
|
||||
@@ -103,10 +103,7 @@ export function BuildHistoryList({
|
||||
: ''}
|
||||
</span>
|
||||
{build.active ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="h-4 border-status-success-border bg-status-success-background px-1.5 text-[10px] font-semibold tracking-wide text-status-success uppercase"
|
||||
>
|
||||
<Badge variant="statusActive">
|
||||
{t('cloudEnvironment.history.active', 'Active')}
|
||||
</Badge>
|
||||
) : null}
|
||||
@@ -186,17 +183,19 @@ function ActivateButton({
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const button = (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={busy || !build.activatable}
|
||||
onClick={() => onActivate(build)}
|
||||
className="opacity-80 group-hover/build:opacity-100 focus-visible:opacity-100"
|
||||
>
|
||||
{busy ? <Loader2 className="animate-spin motion-reduce:animate-none" /> : <RotateCcw />}
|
||||
{t('cloudEnvironment.history.use', 'Use this build')}
|
||||
</Button>
|
||||
// Quiet until the row is hovered or the button focused; the wrapper owns the fade, not Button.
|
||||
<span className="inline-flex opacity-80 group-hover/build:opacity-100 focus-within:opacity-100">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={busy || !build.activatable}
|
||||
onClick={() => onActivate(build)}
|
||||
>
|
||||
{busy ? <Loader2 className="animate-spin motion-reduce:animate-none" /> : <RotateCcw />}
|
||||
{t('cloudEnvironment.history.use', 'Use this build')}
|
||||
</Button>
|
||||
</span>
|
||||
)
|
||||
return (
|
||||
<DisabledReason
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AlertTriangle, ChevronRight } from 'lucide-react'
|
||||
import { getBuiltinTheme } from '@/lib/terminal-theme'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useTranslate, type Translate } from '@/i18n/use-translate'
|
||||
import { getIntlLocale } from '@/i18n/i18n'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
import { FOCUS_RING } from '../orca-cloud/cloud-focus'
|
||||
@@ -106,7 +107,7 @@ export const LogLineRow = memo(function LogLineRow({
|
||||
<div
|
||||
className={cn(
|
||||
'group/line flex min-h-5 gap-3 px-3 leading-5 hover:bg-foreground/[0.04]',
|
||||
line.kind === 'error' && 'bg-destructive/10 text-destructive dark:text-red-300',
|
||||
line.kind === 'error' && 'bg-destructive/10 text-destructive',
|
||||
line.kind === 'warning' && 'text-status-warning-text'
|
||||
)}
|
||||
>
|
||||
@@ -179,7 +180,7 @@ export function StepHeaderRow({
|
||||
className="text-[11px] tabular-nums text-muted-foreground"
|
||||
title={t('cloudEnvironment.log.lineCountTitle', 'Lines of output')}
|
||||
>
|
||||
{lineCount.toLocaleString()}
|
||||
{lineCount.toLocaleString(getIntlLocale())}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="w-16 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
|
||||
@@ -257,7 +258,7 @@ export function FailureSummary({
|
||||
const reason = onShowError ? null : buildErrorCopy(build.error, t)
|
||||
return (
|
||||
<InlineError
|
||||
className="rounded-none border-x-0 border-t-0"
|
||||
layout="strip-top"
|
||||
title={summary.headline}
|
||||
detail={
|
||||
reason ? (
|
||||
@@ -297,7 +298,7 @@ export function LogFooter({
|
||||
return (
|
||||
<InlineError
|
||||
tone="neutral"
|
||||
className="rounded-none border-x-0 border-b-0"
|
||||
layout="strip-bottom"
|
||||
title={t('cloudEnvironment.log.lostStatic', 'Lost connection to the build log.')}
|
||||
detail={
|
||||
streamState === 'reconnecting'
|
||||
|
||||
@@ -410,13 +410,13 @@ export const BuildLogViewer = memo(function BuildLogViewer({
|
||||
</div>
|
||||
</div>
|
||||
{running && !scroll.following && scroll.awayFromBottom && rowCount > 0 ? (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center">
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="secondary"
|
||||
variant="secondary-floating"
|
||||
onClick={jumpToLatest}
|
||||
className="pointer-events-auto rounded-full shadow-md motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1"
|
||||
className="pointer-events-auto"
|
||||
>
|
||||
<ArrowDown />
|
||||
{scroll.unseen > 0
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { StepStatus } from './build-steps'
|
||||
import type { EnvironmentBuildStatus } from './cloud-environment-types'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
|
||||
|
||||
export function stepStatusFromBuild(status: EnvironmentBuildStatus): StepStatus {
|
||||
if (status === 'starting' || status === 'running' || status === 'snapshotting') {
|
||||
@@ -37,11 +38,11 @@ export function BuildStatusIcon({
|
||||
<>
|
||||
<Loader2
|
||||
aria-hidden
|
||||
className={cn(base, 'animate-spin text-sky-600 motion-reduce:hidden dark:text-sky-400')}
|
||||
className={cn(base, 'animate-spin text-callout-note motion-reduce:hidden')}
|
||||
/>
|
||||
<CircleDot
|
||||
aria-hidden
|
||||
className={cn(base, 'hidden text-sky-600 motion-reduce:block dark:text-sky-400')}
|
||||
className={cn(base, 'hidden text-callout-note motion-reduce:block')}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
@@ -68,8 +69,8 @@ export function useNow(enabled: boolean, intervalMs = 1000): number {
|
||||
return
|
||||
}
|
||||
setNow(Date.now())
|
||||
const timer = window.setInterval(() => setNow(Date.now()), intervalMs)
|
||||
return () => window.clearInterval(timer)
|
||||
// An elapsed-time clock: hidden windows skip ticks and catch up when shown.
|
||||
return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs })
|
||||
}, [enabled, intervalMs])
|
||||
return now
|
||||
}
|
||||
|
||||
@@ -306,7 +306,7 @@ export function CloudEnvironmentSkeleton(): React.JSX.Element {
|
||||
</div>
|
||||
<Skeleton className="h-8 w-28" />
|
||||
</div>
|
||||
<Skeleton className="h-48 w-full rounded-lg" />
|
||||
<Skeleton shape="card" className="h-48 w-full" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
|
||||
@@ -121,7 +121,7 @@ export function EnvironmentForm({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="max-w-72">
|
||||
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
|
||||
<DropdownMenuLabel variant="hint">
|
||||
{t(
|
||||
'cloudEnvironment.form.importHint',
|
||||
'Reads Conductor and dev container setup from a local project.'
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { getIntlLocale } from '@/i18n/i18n'
|
||||
import { normalizeRepoInput, repoDisplayName, repoKey } from './cloud-environment-copy'
|
||||
import type { EnvironmentDraft } from './cloud-environment-types'
|
||||
import { MAX_INSTALL_SCRIPT_CHARS } from './environment-draft'
|
||||
@@ -118,7 +119,9 @@ export function RepoListEditor({
|
||||
aria-label={t('cloudEnvironment.form.branchAria', 'Branch for {{repo}}', {
|
||||
repo: name
|
||||
})}
|
||||
className="h-7 pl-7 font-mono text-xs md:text-xs"
|
||||
variant="code"
|
||||
adornment="leading"
|
||||
className="h-7"
|
||||
onChange={(event) => {
|
||||
const next = [...repos]
|
||||
next[index] = {
|
||||
@@ -159,7 +162,8 @@ export function RepoListEditor({
|
||||
)}
|
||||
aria-invalid={error ? true : undefined}
|
||||
aria-describedby={error ? `${inputId}-error` : undefined}
|
||||
className="h-8 font-mono text-[13px] md:text-[13px]"
|
||||
variant="code-body"
|
||||
className="h-8"
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
@@ -194,14 +198,13 @@ export function RepoListEditor({
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
className="font-mono"
|
||||
onClick={() => add(suggestion.slug)}
|
||||
aria-label={t('cloudEnvironment.form.addSuggestion', 'Add {{repo}}', {
|
||||
repo: suggestion.slug
|
||||
})}
|
||||
>
|
||||
<Plus />
|
||||
{suggestion.slug}
|
||||
<span className="font-mono">{suggestion.slug}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
@@ -322,7 +325,8 @@ export function InstallScriptEditor({
|
||||
readOnly && 'hidden'
|
||||
)}
|
||||
>
|
||||
{value.length.toLocaleString()} / {MAX_INSTALL_SCRIPT_CHARS.toLocaleString()}
|
||||
{value.length.toLocaleString(getIntlLocale())} /{' '}
|
||||
{MAX_INSTALL_SCRIPT_CHARS.toLocaleString(getIntlLocale())}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useId, useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { SettingsSegmentedControl } from '@/components/settings/form-controls/SettingsFormControls'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { MAX_ENV_VAR_NAMES, parseEnvVarNames } from './environment-draft'
|
||||
import type { EnvironmentMachineSize } from './cloud-environment-types'
|
||||
@@ -127,6 +128,9 @@ export function EnvVarChipEditor({
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (isImeOwnedKeyboardEvent(event)) {
|
||||
return
|
||||
}
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
commit(value)
|
||||
|
||||
@@ -8,7 +8,7 @@ export const BUILD_STEPS: readonly EnvironmentBuildStep[] = [
|
||||
'record',
|
||||
'snapshot'
|
||||
]
|
||||
const SCRIPT_STEPS = new Set<EnvironmentBuildStep>(['clone', 'install', 'record'])
|
||||
const SCRIPT_STEP_LIST: readonly EnvironmentBuildStep[] = ['clone', 'install', 'record']
|
||||
|
||||
export type LogLineKind = 'plain' | 'warning' | 'error' | 'orca-error'
|
||||
|
||||
@@ -35,9 +35,8 @@ const ERROR_LINE =
|
||||
const WARNING_LINE = /\b(?:warn|warning|deprecated)\b|WARN\b|^W: /i
|
||||
|
||||
export function parseStepMarker(plain: string): EnvironmentBuildStep | null {
|
||||
const match = STEP_MARKER.exec(plain.trim())
|
||||
const step = match?.[1] as EnvironmentBuildStep | undefined
|
||||
return step && SCRIPT_STEPS.has(step) ? step : null
|
||||
const marker = STEP_MARKER.exec(plain.trim())?.[1]
|
||||
return SCRIPT_STEP_LIST.find((step) => step === marker) ?? null
|
||||
}
|
||||
|
||||
/** Heuristic highlighting; Orca's own `::orca-error::` lines win over everything. */
|
||||
|
||||
@@ -8,9 +8,13 @@ import {
|
||||
} from './cloud-environment-copy'
|
||||
import type { EnvironmentStaleness } from './cloud-environment-types'
|
||||
import { parseEnvVarNames } from './environment-draft'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
|
||||
const t = (_key: string, fallback: string, options?: Record<string, unknown>): string =>
|
||||
fallback.replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(options?.[name] ?? ''))
|
||||
const t: Translate = (_key, fallback, options) =>
|
||||
fallback.replace(/\{\{(\w+)\}\}/g, (_, name: string) => {
|
||||
const value: unknown = options?.[name]
|
||||
return value === undefined || value === null ? '' : String(value)
|
||||
})
|
||||
|
||||
function staleness(overrides: Partial<EnvironmentStaleness>): EnvironmentStaleness {
|
||||
return {
|
||||
@@ -51,7 +55,7 @@ describe('stalenessBannerCopy', () => {
|
||||
]
|
||||
}),
|
||||
6,
|
||||
t as never
|
||||
t
|
||||
)
|
||||
expect(copy).toEqual({
|
||||
tone: 'prominent',
|
||||
@@ -62,7 +66,7 @@ describe('stalenessBannerCopy', () => {
|
||||
|
||||
it('reports config changes', () => {
|
||||
expect(
|
||||
stalenessBannerCopy(staleness({ recommendation: 'config_changed' }), 6, t as never)?.message
|
||||
stalenessBannerCopy(staleness({ recommendation: 'config_changed' }), 6, t)?.message
|
||||
).toBe('You changed the environment since build #6')
|
||||
})
|
||||
|
||||
@@ -73,7 +77,7 @@ describe('stalenessBannerCopy', () => {
|
||||
repos: [{ ...staleness({}).repos[0], aheadBy: 12 }]
|
||||
}),
|
||||
6,
|
||||
t as never
|
||||
t
|
||||
)
|
||||
expect(many).toEqual({
|
||||
tone: 'subtle',
|
||||
@@ -87,31 +91,29 @@ describe('stalenessBannerCopy', () => {
|
||||
repos: [{ ...staleness({}).repos[0], aheadBy: 1 }]
|
||||
}),
|
||||
6,
|
||||
((key: string, fallback: string, options?: Record<string, unknown>) => {
|
||||
(key, fallback, options) => {
|
||||
seen.push(options ?? {})
|
||||
return t(key, fallback, options)
|
||||
}) as never
|
||||
}
|
||||
)
|
||||
expect(seen[0]).toMatchObject({ count: 1 })
|
||||
})
|
||||
|
||||
it('is subtle when Orca updated the base image', () => {
|
||||
const copy = stalenessBannerCopy(staleness({ recommendation: 'image_updated' }), 6, t as never)
|
||||
const copy = stalenessBannerCopy(staleness({ recommendation: 'image_updated' }), 6, t)
|
||||
expect(copy).toEqual({
|
||||
tone: 'subtle',
|
||||
rebuild: true,
|
||||
message: 'Orca’s base image was updated since build #6 — rebuild to pick it up'
|
||||
})
|
||||
const flagged = stalenessBannerCopy(staleness({ imageUpdated: true }), 6, t as never)
|
||||
const flagged = stalenessBannerCopy(staleness({ imageUpdated: true }), 6, t)
|
||||
expect(flagged?.tone).toBe('subtle')
|
||||
})
|
||||
|
||||
it('says nothing when up to date, unknown or never built', () => {
|
||||
expect(stalenessBannerCopy(staleness({}), 6, t as never)).toBeNull()
|
||||
expect(stalenessBannerCopy(staleness({ recommendation: 'unknown' }), 6, t as never)).toBeNull()
|
||||
expect(
|
||||
stalenessBannerCopy(staleness({ recommendation: 'deps_changed' }), null, t as never)
|
||||
).toBeNull()
|
||||
expect(stalenessBannerCopy(staleness({}), 6, t)).toBeNull()
|
||||
expect(stalenessBannerCopy(staleness({ recommendation: 'unknown' }), 6, t)).toBeNull()
|
||||
expect(stalenessBannerCopy(staleness({ recommendation: 'deps_changed' }), null, t)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -138,18 +140,16 @@ describe('env var names', () => {
|
||||
|
||||
describe('build failure copy', () => {
|
||||
it('never implies a failed build replaced the active one', () => {
|
||||
expect(failedBuildSummary(7, 'install', 6, t as never)).toEqual({
|
||||
expect(failedBuildSummary(7, 'install', 6, t)).toEqual({
|
||||
headline: 'Build #7 failed at Run install script.',
|
||||
consequence: 'New workspaces still start from build #6.'
|
||||
})
|
||||
expect(failedBuildSummary(3, null, null, t as never)).toEqual({
|
||||
expect(failedBuildSummary(3, null, null, t)).toEqual({
|
||||
headline: 'Build #3 failed.',
|
||||
consequence: 'New workspaces start without a prebuilt environment until a build succeeds.'
|
||||
})
|
||||
expect(buildErrorCopy('exit_2', t as never)).toBe(
|
||||
'The install script stopped at a failing command.'
|
||||
)
|
||||
expect(buildErrorCopy('provider_503', t as never)).not.toMatch(/503|provider/)
|
||||
expect(buildErrorCopy(null, t as never)).toBeNull()
|
||||
expect(buildErrorCopy('exit_2', t)).toBe('The install script stopped at a failing command.')
|
||||
expect(buildErrorCopy('provider_503', t)).not.toMatch(/503|provider/)
|
||||
expect(buildErrorCopy(null, t)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sampleBuild } from './cloud-environment-fixture-data'
|
||||
import { mergeBuildsByRecency, settledEnvironmentsApi } from './environment-api-safety'
|
||||
import type { EnvironmentsApi } from './cloud-environment-types'
|
||||
|
||||
describe('mergeBuildsByRecency', () => {
|
||||
it('keeps the further-along view of a build but takes `active` from the fetch', () => {
|
||||
@@ -31,9 +30,16 @@ describe('mergeBuildsByRecency', () => {
|
||||
|
||||
describe('settledEnvironmentsApi', () => {
|
||||
it('turns a rejected call into an error result', async () => {
|
||||
const gone = (): Promise<never> => Promise.reject(new Error('ipc gone'))
|
||||
const api = settledEnvironmentsApi({
|
||||
get: () => Promise.reject(new Error('ipc gone'))
|
||||
} as unknown as EnvironmentsApi)
|
||||
list: gone,
|
||||
get: gone,
|
||||
create: gone,
|
||||
update: gone,
|
||||
startBuild: gone,
|
||||
cancelBuild: gone,
|
||||
activateBuild: gone
|
||||
})
|
||||
await expect(api.get('env_1')).resolves.toEqual({
|
||||
ok: false,
|
||||
error: { code: 'unavailable', message: 'ipc gone' }
|
||||
|
||||
@@ -16,12 +16,12 @@ function settle<T>(promise: Promise<EnvironmentResult<T>>): Promise<EnvironmentR
|
||||
}
|
||||
|
||||
/** The calls the settings panel makes, each guaranteed to resolve. */
|
||||
export function settledEnvironmentsApi(
|
||||
api: EnvironmentsApi
|
||||
): Pick<
|
||||
type SettledCalls = Pick<
|
||||
EnvironmentsApi,
|
||||
'list' | 'get' | 'create' | 'update' | 'startBuild' | 'cancelBuild' | 'activateBuild'
|
||||
> {
|
||||
>
|
||||
|
||||
export function settledEnvironmentsApi(api: SettledCalls): SettledCalls {
|
||||
return {
|
||||
list: () => settle(api.list()),
|
||||
get: (envId) => settle(api.get(envId)),
|
||||
|
||||
@@ -56,7 +56,7 @@ export function useBuildLogStream(
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- one buffer per build; reconnects reuse it.
|
||||
const buffer = useMemo(() => new BuildLogBuffer(), [envId, buildId])
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- the router lives as long as its buffer.
|
||||
// The router lives as long as its buffer.
|
||||
const router = useMemo(() => new LogReplayRouter(buffer), [buffer])
|
||||
const [status, setStatus] = useState<StreamStatus>({
|
||||
key: null,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { draftFromEnvironment, draftPatch, upsertBuild } from './environment-dra
|
||||
import { useEnvironmentStaleness } from './use-environment-staleness'
|
||||
import { idleActions, type ActionState } from './environment-action-state'
|
||||
import { mergeBuildsByRecency, settledEnvironmentsApi } from './environment-api-safety'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
|
||||
|
||||
/** Builds advance server-side; while one runs, re-read the history this often (the log streams). */
|
||||
const IN_PROGRESS_POLL_MS = 8_000
|
||||
@@ -105,12 +106,15 @@ export function useCloudEnvironment(rawApi: EnvironmentsApi) {
|
||||
if (!envId || !anyInProgress) {
|
||||
return
|
||||
}
|
||||
const timer = window.setInterval(() => {
|
||||
if (reading.current === 0) {
|
||||
void readDetail(envId, { background: true })
|
||||
}
|
||||
}, IN_PROGRESS_POLL_MS)
|
||||
return () => window.clearInterval(timer)
|
||||
// Paused while the window is hidden; the build stream still pushes live status.
|
||||
return installWindowVisibilityInterval({
|
||||
run: () => {
|
||||
if (reading.current === 0) {
|
||||
void readDetail(envId, { background: true })
|
||||
}
|
||||
},
|
||||
intervalMs: IN_PROGRESS_POLL_MS
|
||||
})
|
||||
}, [envId, anyInProgress, readDetail])
|
||||
|
||||
const applyBuild = useCallback((build: EnvironmentBuildView) => {
|
||||
|
||||
@@ -146,19 +146,20 @@ export function CloudRemoteDesktopToast({
|
||||
<InlineError
|
||||
title={copy.title}
|
||||
detail={copy.detail}
|
||||
className={copy.action ? 'pr-9 pb-11' : 'pr-9'}
|
||||
layout="toast"
|
||||
action={
|
||||
copy.action ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
onClick={() => onAction(copy.action!)}
|
||||
>
|
||||
{actionLabel(t, copy.action)}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
{copy.action ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
className="absolute bottom-2.5 left-10"
|
||||
onClick={() => onAction(copy.action!)}
|
||||
>
|
||||
{actionLabel(t, copy.action)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
|
||||
@@ -62,9 +62,13 @@ function MakePrivateBody({
|
||||
return (
|
||||
<DialogDescription>
|
||||
{connected.length > 0
|
||||
? t('auto.components.cloudWorkspaces.makePrivateDisconnects', '{{names}} will be disconnected.', {
|
||||
names
|
||||
})
|
||||
? t(
|
||||
'auto.components.cloudWorkspaces.makePrivateDisconnects',
|
||||
'{{names}} will be disconnected.',
|
||||
{
|
||||
names
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'auto.components.cloudWorkspaces.makePrivateNobody',
|
||||
'No teammates are connected right now. Only the owner will be able to open it.'
|
||||
|
||||
@@ -182,15 +182,23 @@ export function CloudWorkspaceRow({
|
||||
onClick={() => actions.open(w)}
|
||||
aria-label={
|
||||
w.ownerUserId === selfId
|
||||
? t('auto.components.cloudWorkspaces.rowLabelOwnedByYou', '{{title}}, {{status}}, owned by you', {
|
||||
title,
|
||||
status
|
||||
})
|
||||
: t('auto.components.cloudWorkspaces.rowLabel', '{{value0}}, {{value1}}, owned by {{value2}}', {
|
||||
value0: title,
|
||||
value1: status,
|
||||
value2: ownerName
|
||||
})
|
||||
? t(
|
||||
'auto.components.cloudWorkspaces.rowLabelOwnedByYou',
|
||||
'{{title}}, {{status}}, owned by you',
|
||||
{
|
||||
title,
|
||||
status
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'auto.components.cloudWorkspaces.rowLabel',
|
||||
'{{value0}}, {{value1}}, owned by {{value2}}',
|
||||
{
|
||||
value0: title,
|
||||
value1: status,
|
||||
value2: ownerName
|
||||
}
|
||||
)
|
||||
}
|
||||
aria-describedby={descriptionId}
|
||||
className="flex min-w-0 flex-1 cursor-default items-center gap-3 rounded-lg py-2 pl-3 text-left outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-focus-ring"
|
||||
@@ -224,10 +232,17 @@ export function CloudWorkspaceRow({
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
{w.ownerUserId === selfId
|
||||
? t('auto.components.cloudWorkspaces.privateTooltipYou', 'Private — only you can see it')
|
||||
: t('auto.components.cloudWorkspaces.privateTooltip', 'Private — only {{name}} can open it', {
|
||||
name: ownerName
|
||||
})}
|
||||
? t(
|
||||
'auto.components.cloudWorkspaces.privateTooltipYou',
|
||||
'Private — only you can see it'
|
||||
)
|
||||
: t(
|
||||
'auto.components.cloudWorkspaces.privateTooltip',
|
||||
'Private — only {{name}} can open it',
|
||||
{
|
||||
name: ownerName
|
||||
}
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -22,7 +22,11 @@ import { refreshCloudMessageSenders } from '@/lib/cloud-message-sender'
|
||||
import { describeError } from './cloud-workspace-errors'
|
||||
import { focusCloudChat } from './cloud-chat-focus'
|
||||
import { frontCloudChat } from './cloud-workspace-links'
|
||||
import { cloudWorkspaceTitle, copyCloudWorkspaceLink, openCloudWorkspace } from './open-cloud-workspace'
|
||||
import {
|
||||
cloudWorkspaceTitle,
|
||||
copyCloudWorkspaceLink,
|
||||
openCloudWorkspace
|
||||
} from './open-cloud-workspace'
|
||||
import { useCloudWorkspaces, useCloudWorkspacesAvailable } from './use-cloud-workspaces'
|
||||
|
||||
const INITIAL_FILTERS: CloudWorkspacesFilters = {
|
||||
|
||||
@@ -65,7 +65,10 @@ export function describeInlineError(
|
||||
t: Translate = translate
|
||||
): string {
|
||||
if (error === 'unauthorized') {
|
||||
return t('auto.components.cloudWorkspaces.errorUnauthorizedInline', 'Your Orca Cloud session expired.')
|
||||
return t(
|
||||
'auto.components.cloudWorkspaces.errorUnauthorizedInline',
|
||||
'Your Orca Cloud session expired.'
|
||||
)
|
||||
}
|
||||
if (error === 'timeout' || error === 'unavailable' || error === 'provider_unavailable') {
|
||||
return t(
|
||||
@@ -87,5 +90,8 @@ export function describeInlineError(
|
||||
) {
|
||||
return describeError(error, reason, t)
|
||||
}
|
||||
return t('auto.components.cloudWorkspaces.errorUnknownInline', 'Something went wrong. Nothing was changed.')
|
||||
return t(
|
||||
'auto.components.cloudWorkspaces.errorUnknownInline',
|
||||
'Something went wrong. Nothing was changed.'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -193,15 +193,16 @@ describe('RunTargetCombobox', () => {
|
||||
function deferBilling(): (value: unknown) => void {
|
||||
let answer!: (value: unknown) => void
|
||||
const previous = window.api
|
||||
window.api = {
|
||||
// jsdom's window is the global object, so this stubs window.api for this test only.
|
||||
vi.stubGlobal('api', {
|
||||
...previous,
|
||||
orcaProfiles: {
|
||||
...previous?.orcaProfiles,
|
||||
billingStatus: vi.fn(() => new Promise((resolve) => (answer = resolve)))
|
||||
}
|
||||
} as never
|
||||
})
|
||||
onTestFinished(() => {
|
||||
window.api = previous
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
return (value) => answer(value)
|
||||
}
|
||||
|
||||
@@ -70,12 +70,13 @@ export function useRunTargetOrcaCloud({
|
||||
const [pending, setPending] = useState(false)
|
||||
const pickToken = useRef(0)
|
||||
const openRef = useRef(open)
|
||||
// Closing (another pick, Escape, outside click) abandons a held pick; counted, not reset, so the
|
||||
// waiting pick can tell even if the picker reopened before billing answered.
|
||||
const closings = useRef(0)
|
||||
useEffect(() => {
|
||||
openRef.current = open
|
||||
if (!open) {
|
||||
// Closing (another pick, Escape, outside click) abandons a held pick.
|
||||
pickToken.current += 1
|
||||
setPending(false)
|
||||
closings.current += 1
|
||||
}
|
||||
}, [open])
|
||||
useEffect(
|
||||
@@ -106,16 +107,20 @@ export function useRunTargetOrcaCloud({
|
||||
return
|
||||
}
|
||||
const token = ++pickToken.current
|
||||
const closingsAtPick = closings.current
|
||||
setPending(true)
|
||||
void waitForOrcaCloudAccess(PICK_WAIT_MS).then((resolved) => {
|
||||
if (token !== pickToken.current || !openRef.current) {
|
||||
if (token !== pickToken.current) {
|
||||
return
|
||||
}
|
||||
setPending(false)
|
||||
pickFor(resolved, recipe)
|
||||
if (closingsAtPick === closings.current && openRef.current) {
|
||||
pickFor(resolved, recipe)
|
||||
}
|
||||
})
|
||||
},
|
||||
[access, pickFor]
|
||||
)
|
||||
return { access, pending, runBlockedAction, select }
|
||||
// A closed picker shows no busy row even while an abandoned wait is still settling.
|
||||
return { access, pending: pending && open, runBlockedAction, select }
|
||||
}
|
||||
|
||||
@@ -220,8 +220,8 @@ export function CloudArchivedWorkspaceView({
|
||||
action={
|
||||
<Button
|
||||
size="sm"
|
||||
aria-disabled={unarchiving}
|
||||
className={cn(unarchiving && 'opacity-60')}
|
||||
variant="default-held"
|
||||
aria-disabled={unarchiving || undefined}
|
||||
onClick={() => {
|
||||
if (!unarchiving) {
|
||||
onUnarchive()
|
||||
|
||||
@@ -42,7 +42,9 @@ function TerminalSkeleton({ still }: { still: boolean }): React.JSX.Element {
|
||||
<span key={index} className="flex h-3 items-center gap-2">
|
||||
<span className="w-2 leading-none">{line.prompt ? '$' : ''}</span>
|
||||
<Skeleton
|
||||
className={cn('h-2 rounded-sm', still ? 'animate-none' : '[animation-duration:2.4s]')}
|
||||
shape="small"
|
||||
motion={still ? 'still' : 'slow'}
|
||||
className="h-2"
|
||||
style={{ width: `${line.width}%`, animationDelay: `${index * 140}ms` }}
|
||||
/>
|
||||
</span>
|
||||
@@ -161,8 +163,8 @@ export function CloudWakingOverlay({
|
||||
</div>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="-mt-1 -mr-1 text-muted-foreground"
|
||||
variant="quiet"
|
||||
className="-mt-1 -mr-1"
|
||||
aria-label={t('orcaCloudWorkspace.dismiss', 'Dismiss')}
|
||||
onClick={onDismiss}
|
||||
>
|
||||
|
||||
@@ -121,7 +121,8 @@ function CloudWorkspaceMarkInner({
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={10}
|
||||
className={cn('w-72 p-3', FOCUS_RING)}
|
||||
focusRing
|
||||
className="w-72"
|
||||
aria-label={label}
|
||||
tabIndex={-1}
|
||||
onPointerEnter={() => clearTimer()}
|
||||
@@ -136,13 +137,15 @@ function CloudWorkspaceMarkInner({
|
||||
}}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<CloudWorkspaceStatusPanel
|
||||
workspaceId={workspaceId}
|
||||
state={view.state}
|
||||
entry={view.entry}
|
||||
pending={view.pending}
|
||||
actions={actions}
|
||||
/>
|
||||
<div className="p-3">
|
||||
<CloudWorkspaceStatusPanel
|
||||
workspaceId={workspaceId}
|
||||
state={view.state}
|
||||
entry={view.entry}
|
||||
pending={view.pending}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
|
||||
@@ -58,8 +58,8 @@ export function CloudWorkspaceNotice({
|
||||
{onDismiss ? (
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="-mt-1 -mr-1 text-muted-foreground"
|
||||
variant="quiet"
|
||||
className="-mt-1 -mr-1"
|
||||
aria-label={t('orcaCloudWorkspace.dismiss', 'Dismiss')}
|
||||
onClick={onDismiss}
|
||||
>
|
||||
|
||||
@@ -77,9 +77,9 @@ function MeterSkeleton(): React.JSX.Element {
|
||||
<div className="flex flex-col gap-1.5" aria-hidden="true">
|
||||
{Array.from({ length: METER_ROWS }, (_, row) => (
|
||||
<div key={row} className="grid grid-cols-[4.5rem_1fr_auto] items-center gap-2">
|
||||
<Skeleton className="h-3 w-10 rounded" />
|
||||
<Skeleton className="h-1 rounded-full animate-none" />
|
||||
<Skeleton className="h-3 w-20 rounded" />
|
||||
<Skeleton shape="small" className="h-3 w-10" />
|
||||
<Skeleton shape="circle" motion="still" className="h-1" />
|
||||
<Skeleton shape="small" className="h-3 w-20" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -200,7 +200,7 @@ export function CloudWorkspaceStatusPanel({
|
||||
retryLabel={t('orcaCloudWorkspace.retry', 'Retry')}
|
||||
retrying={entry?.loading}
|
||||
onRetry={() => void refreshCloudWorkspaceStatus(workspaceId)}
|
||||
className="text-xs"
|
||||
density="compact"
|
||||
/>
|
||||
) : firstLoad ? (
|
||||
<div
|
||||
@@ -286,8 +286,7 @@ export function CloudWorkspaceStatusPanel({
|
||||
{canArchive && !restarting ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground"
|
||||
variant="quiet"
|
||||
{...busyProps(pending === 'archive', anyBusy, actions.onArchive)}
|
||||
>
|
||||
{pending === 'archive' ? <Loader2 className="animate-spin" /> : <Archive />}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { returnFocusToWorkspace } from './cloud-focus-return'
|
||||
|
||||
const body = {} as HTMLElement
|
||||
// Identity is all the helper compares, so plain objects stand in for DOM nodes.
|
||||
const body = {}
|
||||
|
||||
describe('returnFocusToWorkspace (waking overlay → null)', () => {
|
||||
it('gives focus back to the active tab when the cover took it with it to <body>', () => {
|
||||
@@ -17,7 +18,7 @@ describe('returnFocusToWorkspace (waking overlay → null)', () => {
|
||||
|
||||
it('never steals focus the user moved elsewhere, and needs an active tab', () => {
|
||||
const focusTab = vi.fn()
|
||||
const sidebarButton = {} as Element
|
||||
const sidebarButton = {}
|
||||
expect(returnFocusToWorkspace('tab-1', focusTab, { activeElement: sidebarButton, body })).toBe(
|
||||
false
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
export function returnFocusToWorkspace(
|
||||
activeTabId: string | null | undefined,
|
||||
focusTab: (tabId: string) => void,
|
||||
doc: Pick<Document, 'activeElement' | 'body'> = document
|
||||
doc: { activeElement: object | null; body: object | null } = document
|
||||
): boolean {
|
||||
if (doc.activeElement && doc.activeElement !== doc.body) {
|
||||
return false
|
||||
|
||||
@@ -40,7 +40,7 @@ function QueuedPromptRow({
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
aria-label={t('components.orcaCloud.offline.editQueued', 'Edit queued message')}
|
||||
className="min-h-16 text-sm"
|
||||
variant="compact"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="xs" variant="ghost" onClick={() => setEditing(false)}>
|
||||
@@ -237,14 +237,15 @@ export function ChatPanel({
|
||||
}}
|
||||
placeholder={t('components.orcaCloud.offline.composerPlaceholder', 'Message the agent')}
|
||||
aria-label={t('components.orcaCloud.offline.composerLabel', 'Message to queue')}
|
||||
className="min-h-14 resize-none border-0 bg-transparent p-1 text-sm shadow-none focus-visible:ring-0 dark:bg-transparent"
|
||||
variant="bare"
|
||||
className="min-h-14"
|
||||
/>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="default-held"
|
||||
aria-disabled={!draft.trim() || busy || undefined}
|
||||
aria-busy={busy || undefined}
|
||||
className="aria-disabled:cursor-default aria-disabled:bg-muted aria-disabled:text-muted-foreground aria-disabled:hover:bg-muted"
|
||||
onClick={send}
|
||||
>
|
||||
{busy ? <Loader2 className="motion-safe:animate-spin" /> : null}
|
||||
|
||||
@@ -101,7 +101,7 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J
|
||||
) : null}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="chat" className="flex min-h-0 flex-1 flex-col pt-3">
|
||||
<TabsContent value="chat" className="mt-3 flex min-h-0 flex-1 flex-col">
|
||||
<ChatPanel
|
||||
chats={snapshot.chats}
|
||||
queued={props.queued}
|
||||
@@ -110,72 +110,70 @@ export function CloudWorkspaceOfflineView(props: CloudOfflineViewProps): React.J
|
||||
onEdit={props.onEdit}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="terminals"
|
||||
className="min-h-0 flex-1 overflow-y-auto scrollbar-sleek pt-3"
|
||||
>
|
||||
{snapshot.terminals.length === 0 ? (
|
||||
<p className="max-w-[60ch] py-4 text-sm text-muted-foreground">
|
||||
{t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')}
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{snapshot.terminals.map((terminal) => {
|
||||
const title = terminal.title ?? terminal.handle
|
||||
return (
|
||||
<figure
|
||||
key={terminal.handle}
|
||||
className="overflow-hidden rounded-lg border border-border"
|
||||
>
|
||||
<figcaption className="flex items-center gap-2 border-b border-border bg-muted/40 px-3 py-1.5 text-xs text-muted-foreground">
|
||||
<SquareTerminal className="size-3.5" aria-hidden="true" />
|
||||
<span className="truncate">{title}</span>
|
||||
<span className="ml-auto">
|
||||
{t('components.orcaCloud.offline.readOnly', 'Read-only')}
|
||||
</span>
|
||||
</figcaption>
|
||||
<pre
|
||||
className="max-h-72 overflow-auto scrollbar-sleek bg-background px-3 py-2 font-mono text-xs leading-5 text-foreground/90"
|
||||
tabIndex={0}
|
||||
aria-label={t(
|
||||
'components.orcaCloud.offline.terminalOutput',
|
||||
'Saved output of {{title}}',
|
||||
{ title }
|
||||
)}
|
||||
// Like a live terminal, open at the latest output.
|
||||
ref={scrollToEnd}
|
||||
<TabsContent value="terminals" className="mt-3 flex min-h-0 flex-1 flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto scrollbar-sleek">
|
||||
{snapshot.terminals.length === 0 ? (
|
||||
<p className="max-w-[60ch] py-4 text-sm text-muted-foreground">
|
||||
{t('components.orcaCloud.offline.noTerminals', 'No terminal output was saved.')}
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{snapshot.terminals.map((terminal) => {
|
||||
const title = terminal.title ?? terminal.handle
|
||||
return (
|
||||
<figure
|
||||
key={terminal.handle}
|
||||
className="overflow-hidden rounded-lg border border-border"
|
||||
>
|
||||
{terminal.lines.join('\n')}
|
||||
</pre>
|
||||
</figure>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<figcaption className="flex items-center gap-2 border-b border-border bg-muted/40 px-3 py-1.5 text-xs text-muted-foreground">
|
||||
<SquareTerminal className="size-3.5" aria-hidden="true" />
|
||||
<span className="truncate">{title}</span>
|
||||
<span className="ml-auto">
|
||||
{t('components.orcaCloud.offline.readOnly', 'Read-only')}
|
||||
</span>
|
||||
</figcaption>
|
||||
<pre
|
||||
className="max-h-72 overflow-auto scrollbar-sleek bg-background px-3 py-2 font-mono text-xs leading-5 text-foreground/90"
|
||||
tabIndex={0}
|
||||
aria-label={t(
|
||||
'components.orcaCloud.offline.terminalOutput',
|
||||
'Saved output of {{title}}',
|
||||
{ title }
|
||||
)}
|
||||
// Like a live terminal, open at the latest output.
|
||||
ref={scrollToEnd}
|
||||
>
|
||||
{terminal.lines.join('\n')}
|
||||
</pre>
|
||||
</figure>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="changes"
|
||||
className="min-h-0 flex-1 overflow-y-auto scrollbar-sleek pt-3"
|
||||
>
|
||||
{snapshot.git ? (
|
||||
<CloudGitChanges
|
||||
now={now}
|
||||
data={{
|
||||
branch: snapshot.git.branch,
|
||||
changes: snapshot.git.changes,
|
||||
changeCount: snapshot.git.changeCount,
|
||||
commits: snapshot.git.commits.map((commit) => ({
|
||||
sha: commit.id,
|
||||
subject: commit.subject,
|
||||
at: commit.at
|
||||
}))
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="max-w-[60ch] py-4 text-sm text-muted-foreground">
|
||||
{t('components.orcaCloud.offline.noGit', 'No source control state was saved.')}
|
||||
</p>
|
||||
)}
|
||||
<TabsContent value="changes" className="mt-3 flex min-h-0 flex-1 flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto scrollbar-sleek">
|
||||
{snapshot.git ? (
|
||||
<CloudGitChanges
|
||||
now={now}
|
||||
data={{
|
||||
branch: snapshot.git.branch,
|
||||
changes: snapshot.git.changes,
|
||||
changeCount: snapshot.git.changeCount,
|
||||
commits: snapshot.git.commits.map((commit) => ({
|
||||
sha: commit.id,
|
||||
subject: commit.subject,
|
||||
at: commit.at
|
||||
}))
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="max-w-[60ch] py-4 text-sm text-muted-foreground">
|
||||
{t('components.orcaCloud.offline.noGit', 'No source control state was saved.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { formatCountdown, scopesForPreset } from './cloud-api-format'
|
||||
import { CloudApiErrorNotice } from './cloud-api-parts'
|
||||
import { OneTimeSecret, OneTimeSecretDoneButton } from './OneTimeSecret'
|
||||
import { ScopeSummary } from './ScopeSummary'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
|
||||
|
||||
/** "Approve an app": a one-time code an MCP client's consent page accepts instead of an API key. */
|
||||
export function ApproveAppDialog({
|
||||
@@ -54,8 +55,8 @@ export function ApproveAppDialog({
|
||||
if (!approval || nowForFixture !== undefined) {
|
||||
return
|
||||
}
|
||||
const timer = setInterval(() => setNow(Date.now()), 1000)
|
||||
return () => clearInterval(timer)
|
||||
// Countdown clock; paused while the window is hidden and caught up when it shows again.
|
||||
return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 })
|
||||
}, [approval, nowForFixture])
|
||||
|
||||
const remaining = approval ? approval.expiresAt - now : 0
|
||||
|
||||
@@ -158,7 +158,9 @@ export function RoutineRow({
|
||||
{where ? <span className="text-muted-foreground"> · {where}</span> : null}
|
||||
<span className="text-muted-foreground">
|
||||
{' · '}
|
||||
{routine.agent === 'codex' ? 'Codex' : 'Claude Code'}
|
||||
{routine.agent === 'codex'
|
||||
? t('auto.components.settings.cloudRoutines.agentCodex', 'Codex')
|
||||
: t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code')}
|
||||
</span>
|
||||
</p>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
|
||||
@@ -268,7 +268,15 @@ function FormStep({
|
||||
id={`${ids}-expiry`}
|
||||
label={t('auto.components.settings.cloudApi.create.expiry', 'Expires')}
|
||||
>
|
||||
<Select value={expiry} onValueChange={(next) => setExpiry(next as Expiry)}>
|
||||
<Select
|
||||
value={expiry}
|
||||
onValueChange={(next) => {
|
||||
const option = EXPIRY_OPTIONS.find((value) => value === next)
|
||||
if (option) {
|
||||
setExpiry(option)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id={`${ids}-expiry`} className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
|
||||
@@ -91,8 +91,14 @@ export function RoutineAgentSection({
|
||||
equalWidth
|
||||
ariaLabelledBy={`${ids}-agent`}
|
||||
options={[
|
||||
{ value: 'claude', label: 'Claude Code' },
|
||||
{ value: 'codex', label: 'Codex' }
|
||||
{
|
||||
value: 'claude',
|
||||
label: t('auto.components.settings.cloudRoutines.agentClaude', 'Claude Code')
|
||||
},
|
||||
{
|
||||
value: 'codex',
|
||||
label: t('auto.components.settings.cloudRoutines.agentCodex', 'Codex')
|
||||
}
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -34,6 +34,7 @@ import { RoutineAgentSection, routineFieldError as fieldError } from './RoutineA
|
||||
import { WebhookTriggerInfo, WebhookUrlStep } from './RoutineWebhookParts'
|
||||
import {
|
||||
emptyRoutineDraft,
|
||||
isRoutineDraftField,
|
||||
routineDraftFromRoutine,
|
||||
routinePatchFromInput,
|
||||
withCurrentProject,
|
||||
@@ -204,7 +205,9 @@ function EditorForm({
|
||||
setErrors((current) => {
|
||||
const next = { ...current }
|
||||
for (const key of Object.keys(patch)) {
|
||||
delete next[key as RoutineDraftField]
|
||||
if (isRoutineDraftField(key)) {
|
||||
delete next[key]
|
||||
}
|
||||
}
|
||||
if ('projectId' in patch) {
|
||||
delete next.source
|
||||
|
||||
@@ -13,6 +13,7 @@ import { cloudApiErrorCopy, routineRunTriggerLabel } from './cloud-api-copy'
|
||||
import { formatAbsoluteTime, formatRelativeFromNow, formatRunDuration } from './cloud-api-format'
|
||||
import { CloudApiErrorNotice, RoutineRunStatusPill } from './cloud-api-parts'
|
||||
import { isActiveRunStatus } from './routine-run-status'
|
||||
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
|
||||
|
||||
export type LoadRoutineRuns = (
|
||||
routineId: string,
|
||||
@@ -122,11 +123,18 @@ export function RoutineRunHistory({
|
||||
return
|
||||
}
|
||||
// In-flight runs: refetch every few seconds and tick the elapsed clock every second.
|
||||
const poll = setInterval(() => void load(), POLL_MS)
|
||||
const tick = setInterval(() => setNow(Date.now()), 1000)
|
||||
// Both pause while the window is hidden; showing it again refetches and catches the clock up.
|
||||
const stopPoll = installWindowVisibilityInterval({
|
||||
run: () => void load(),
|
||||
intervalMs: POLL_MS
|
||||
})
|
||||
const stopTick = installWindowVisibilityInterval({
|
||||
run: () => setNow(Date.now()),
|
||||
intervalMs: 1000
|
||||
})
|
||||
return () => {
|
||||
clearInterval(poll)
|
||||
clearInterval(tick)
|
||||
stopPoll()
|
||||
stopTick()
|
||||
}
|
||||
}, [active, fixedNow, load])
|
||||
|
||||
|
||||
@@ -133,7 +133,10 @@ export function RoutineSourceSection({
|
||||
value={draft.repoUrl}
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
placeholder="https://github.com/acme/api"
|
||||
placeholder={t(
|
||||
'auto.components.settings.cloudRoutines.editor.repoUrlPlaceholder',
|
||||
'https://github.com/acme/api'
|
||||
)}
|
||||
aria-invalid={Boolean(errors.repoUrl)}
|
||||
aria-describedby={errors.repoUrl ? `${ids}-repo-error` : undefined}
|
||||
onChange={(event) => update({ repoUrl: event.target.value })}
|
||||
|
||||
@@ -33,9 +33,9 @@ import {
|
||||
} from './cloud-api-format'
|
||||
import { FormField } from './cloud-api-parts'
|
||||
import {
|
||||
isRoutineSchedulePreset,
|
||||
routineDraftCron,
|
||||
type RoutineDraft,
|
||||
type RoutineSchedulePreset,
|
||||
type RoutineTriggerKind
|
||||
} from './routine-draft'
|
||||
import { SettingsSegmentedControl } from '../form-controls/SettingsFormControls'
|
||||
@@ -75,8 +75,10 @@ export function RoutineScheduleFields({
|
||||
>
|
||||
<Select
|
||||
value={draft.schedulePreset}
|
||||
onValueChange={(value) => {
|
||||
const preset = value as RoutineSchedulePreset
|
||||
onValueChange={(preset) => {
|
||||
if (!isRoutineSchedulePreset(preset)) {
|
||||
return
|
||||
}
|
||||
update({
|
||||
schedulePreset: preset,
|
||||
// Seed custom cron from the preset so switching never starts from a blank field.
|
||||
@@ -288,7 +290,10 @@ export function RoutineGithubFields({
|
||||
<Input
|
||||
id={`${ids}-labels`}
|
||||
value={draft.labels}
|
||||
placeholder="orca, needs-review"
|
||||
placeholder={t(
|
||||
'auto.components.settings.cloudRoutines.editor.labelsPlaceholder',
|
||||
'orca, needs-review'
|
||||
)}
|
||||
onChange={(event) => update({ labels: event.target.value })}
|
||||
/>
|
||||
</FormField>
|
||||
@@ -304,7 +309,10 @@ export function RoutineGithubFields({
|
||||
<Input
|
||||
id={`${ids}-authors`}
|
||||
value={draft.authors}
|
||||
placeholder="octocat, dependabot[bot]"
|
||||
placeholder={t(
|
||||
'auto.components.settings.cloudRoutines.editor.authorsPlaceholder',
|
||||
'octocat, dependabot[bot]'
|
||||
)}
|
||||
onChange={(event) => update({ authors: event.target.value })}
|
||||
/>
|
||||
</FormField>
|
||||
@@ -319,7 +327,10 @@ export function RoutineGithubFields({
|
||||
<Input
|
||||
id={`${ids}-branches`}
|
||||
value={draft.baseBranches}
|
||||
placeholder="main"
|
||||
placeholder={t(
|
||||
'auto.components.settings.cloudRoutines.editor.branchesPlaceholder',
|
||||
'main'
|
||||
)}
|
||||
onChange={(event) => update({ baseBranches: event.target.value })}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
@@ -135,10 +135,8 @@ export function localTimeZone(): string {
|
||||
export function timeZoneOptions(local: string = localTimeZone()): string[] {
|
||||
let zones: string[] = []
|
||||
try {
|
||||
zones =
|
||||
(Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.(
|
||||
'timeZone'
|
||||
) ?? []
|
||||
// Older runtimes lack supportedValuesOf; fall back to the guaranteed zones below.
|
||||
zones = typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : []
|
||||
} catch {
|
||||
zones = []
|
||||
}
|
||||
|
||||
@@ -16,7 +16,12 @@ import {
|
||||
type RoutineTriggerInput
|
||||
} from '../../../../../shared/cloud-api/cloud-api-types'
|
||||
|
||||
export type RoutineSchedulePreset = 'hourly' | 'daily' | 'weekdays' | 'weekly' | 'custom'
|
||||
const ROUTINE_SCHEDULE_PRESETS = ['hourly', 'daily', 'weekdays', 'weekly', 'custom'] as const
|
||||
export type RoutineSchedulePreset = (typeof ROUTINE_SCHEDULE_PRESETS)[number]
|
||||
|
||||
export function isRoutineSchedulePreset(value: string): value is RoutineSchedulePreset {
|
||||
return ROUTINE_SCHEDULE_PRESETS.some((preset) => preset === value)
|
||||
}
|
||||
export type RoutineTriggerKind = RoutineTriggerInput['kind']
|
||||
|
||||
export type RoutineDraft = {
|
||||
@@ -43,14 +48,20 @@ export type RoutineDraft = {
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export type RoutineDraftField =
|
||||
| 'name'
|
||||
| 'source'
|
||||
| 'repoUrl'
|
||||
| 'customCron'
|
||||
| 'githubEvents'
|
||||
| 'prompt'
|
||||
| 'maxRuntimeMinutes'
|
||||
const ROUTINE_DRAFT_FIELDS = [
|
||||
'name',
|
||||
'source',
|
||||
'repoUrl',
|
||||
'customCron',
|
||||
'githubEvents',
|
||||
'prompt',
|
||||
'maxRuntimeMinutes'
|
||||
] as const
|
||||
export type RoutineDraftField = (typeof ROUTINE_DRAFT_FIELDS)[number]
|
||||
|
||||
export function isRoutineDraftField(value: string): value is RoutineDraftField {
|
||||
return ROUTINE_DRAFT_FIELDS.some((field) => field === value)
|
||||
}
|
||||
|
||||
export const DEFAULT_ROUTINE_MAX_RUNTIME_MINUTES = 30
|
||||
|
||||
@@ -267,9 +278,7 @@ export function routinePatchFromInput(routine: Routine, input: RoutineInput): Ro
|
||||
patch.repo = input.repo
|
||||
}
|
||||
}
|
||||
const { urlHint: _hint, ...currentTrigger } = routine.trigger as RoutineTriggerInput & {
|
||||
urlHint?: unknown
|
||||
}
|
||||
const currentTrigger = triggerAsInput(routine.trigger)
|
||||
if (!same(input.trigger, currentTrigger)) {
|
||||
patch.trigger = input.trigger
|
||||
}
|
||||
@@ -301,3 +310,8 @@ export function withCurrentProject(
|
||||
? [...projects, { id: projectId, name: fallbackName, repo: null }]
|
||||
: projects
|
||||
}
|
||||
|
||||
/** The trigger as the editor would send it: webhook triggers drop the server's URL hint. */
|
||||
function triggerAsInput(trigger: Routine['trigger']): RoutineTriggerInput {
|
||||
return trigger.kind === 'webhook' ? { kind: 'webhook' } : trigger
|
||||
}
|
||||
|
||||
@@ -233,12 +233,14 @@ export function CloudSecretsPasteEnv({
|
||||
t('cloudSecrets.paste.ready', '{{count}} ready', { count }),
|
||||
blocked > 0
|
||||
? t('cloudSecrets.paste.blocked', '{{count}} need a fix and will be skipped', {
|
||||
count: blocked
|
||||
count: blocked,
|
||||
defaultValue_one: '{{count}} needs a fix and will be skipped'
|
||||
})
|
||||
: null,
|
||||
duplicates > 0
|
||||
? t('cloudSecrets.paste.duplicates', '{{count}} duplicates ignored', {
|
||||
count: duplicates
|
||||
count: duplicates,
|
||||
defaultValue_one: '{{count}} duplicate ignored'
|
||||
})
|
||||
: null
|
||||
]
|
||||
@@ -326,7 +328,10 @@ export function CloudSecretsPasteEnv({
|
||||
onClick={() => void save()}
|
||||
>
|
||||
{saving ? <Loader2 className="animate-spin" /> : null}
|
||||
{t('cloudSecrets.paste.save', 'Save {{count}} secrets', { count })}
|
||||
{t('cloudSecrets.paste.save', 'Save {{count}} secrets', {
|
||||
count,
|
||||
defaultValue_one: 'Save {{count}} secret'
|
||||
})}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -84,7 +84,8 @@ export function SecretValueInput({
|
||||
autoFocus={pastedMultiline}
|
||||
variant="code"
|
||||
value={t('cloudSecrets.value.lines', 'Multi-line value · {{count}} lines', {
|
||||
count: lines
|
||||
count: lines,
|
||||
defaultValue_one: 'Multi-line value · {{count}} line'
|
||||
})}
|
||||
aria-invalid={invalid || undefined}
|
||||
aria-describedby={describedBy}
|
||||
|
||||
@@ -24,6 +24,9 @@ const badgeVariants = cva(
|
||||
/** A task label inside a dense reference row's metadata line. */
|
||||
// Quiet outline tag beside a row label (e.g. a plan requirement).
|
||||
tag: 'border-border px-1.5 py-0 text-2xs text-muted-foreground',
|
||||
/** Small uppercase success chip marking the live item in a list (e.g. the active build). */
|
||||
statusActive:
|
||||
'h-4 border-status-success-border bg-status-success-background px-1.5 text-[10px] font-semibold tracking-wide text-status-success uppercase',
|
||||
referenceLabel: 'h-3.5 border-border px-1 py-0 text-3xs font-normal text-muted-foreground',
|
||||
/** An uppercase kind label set before a banner title; takes its color from the parent. */
|
||||
paneLabel:
|
||||
|
||||
@@ -23,10 +23,14 @@ const buttonVariants = cva(
|
||||
variants: {
|
||||
variant: {
|
||||
default: `bg-primary text-primary-foreground hover:bg-primary/90 ${pressClasses} ${disabledSolidClasses}`,
|
||||
// Primary that stays focusable while unavailable (aria-disabled): reads muted like disabled.
|
||||
'default-held': `bg-primary text-primary-foreground hover:bg-primary/90 ${pressClasses} ${disabledSolidClasses} aria-disabled:cursor-default aria-disabled:bg-muted aria-disabled:text-muted-foreground aria-disabled:hover:bg-muted`,
|
||||
destructive: `bg-destructive text-white hover:bg-destructive/90 ${pressClasses} dark:bg-destructive/60 dark:disabled:bg-muted dark:aria-disabled:not-aria-busy:bg-muted ${disabledSolidClasses}`,
|
||||
outline: `${outlineButtonClasses} ${pressClasses}`,
|
||||
'orchestration-tab': `${outlineButtonClasses} border-(--crew-border) bg-(--crew-surface) text-card-foreground shadow-floating dark:border-(--crew-border) dark:bg-(--crew-surface) dark:hover:bg-accent dark:hover:text-accent-foreground`,
|
||||
secondary: `bg-secondary text-secondary-foreground hover:bg-secondary/80 ${pressClasses}`,
|
||||
/** Secondary pill floating over scrolling content (e.g. "Jump to latest"). */
|
||||
'secondary-floating': `rounded-full bg-secondary text-secondary-foreground shadow-md hover:bg-secondary/80 ${pressClasses}`,
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
|
||||
// Secondary text action that only takes the foreground colour on hover.
|
||||
quiet:
|
||||
|
||||
@@ -184,16 +184,20 @@ function DropdownMenuRadioItem({
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
/** 'hint': a sentence of help text at the top of a menu rather than a section heading. */
|
||||
variant?: 'default' | 'hint'
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
'px-2.5 pt-[5px] pb-[3px] text-2xs font-semibold text-muted-foreground data-[inset]:pl-8',
|
||||
'px-2.5 pt-[5px] pb-[3px] text-muted-foreground data-[inset]:pl-8',
|
||||
variant === 'hint' ? 'text-xs font-normal' : 'text-2xs font-semibold',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -16,6 +16,9 @@ type InlineErrorProps = {
|
||||
retrying?: boolean
|
||||
/** 'compact' for narrow panels (sidebar sections): tighter padding, xs text. */
|
||||
density?: 'default' | 'compact'
|
||||
/** 'toast' leaves room for the toast's own dismiss button and puts the action under the text.
|
||||
* 'strip-top' / 'strip-bottom' run edge to edge at the top or bottom of a framed panel. */
|
||||
layout?: 'inline' | 'toast' | 'strip-top' | 'strip-bottom'
|
||||
/** A next step other than retry (e.g. "Sign in"), rendered inside the box after the text.
|
||||
* Pass an outline xs Button with a short verb-first label; never a primary button. */
|
||||
action?: React.ReactNode
|
||||
@@ -35,6 +38,7 @@ function InlineError({
|
||||
onRetry,
|
||||
retrying = false,
|
||||
density = 'default',
|
||||
layout = 'inline',
|
||||
action,
|
||||
className
|
||||
}: InlineErrorProps): React.JSX.Element {
|
||||
@@ -46,8 +50,14 @@ function InlineError({
|
||||
className={cn(
|
||||
// Wraps so a narrow box (e.g. a hint under a half-width field) puts its button under the text
|
||||
// instead of squeezing the text to one word per line.
|
||||
'flex flex-wrap rounded-lg border',
|
||||
'flex flex-wrap border',
|
||||
layout === 'strip-top'
|
||||
? 'rounded-none border-x-0 border-t-0'
|
||||
: layout === 'strip-bottom'
|
||||
? 'rounded-none border-x-0 border-b-0'
|
||||
: 'rounded-lg',
|
||||
density === 'compact' ? 'gap-2 px-2.5 py-2 text-xs' : 'gap-3 px-3 py-2.5 text-sm',
|
||||
layout === 'toast' && 'pr-9',
|
||||
detail ? 'items-start' : 'items-center',
|
||||
tone === 'error'
|
||||
? 'border-destructive/15 bg-destructive/5 dark:border-destructive/25'
|
||||
@@ -77,7 +87,17 @@ function InlineError({
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{action ? <div className="ms-auto flex shrink-0 items-center gap-2">{action}</div> : null}
|
||||
{action ? (
|
||||
<div
|
||||
className={cn(
|
||||
'flex shrink-0 items-center gap-2',
|
||||
// Under the text, aligned with the title (icon width + gap).
|
||||
layout === 'toast' ? 'basis-full ps-7' : 'ms-auto'
|
||||
)}
|
||||
>
|
||||
{action}
|
||||
</div>
|
||||
) : null}
|
||||
{onRetry && retryLabel ? (
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -8,7 +8,9 @@ const inputVariants = cva('', {
|
||||
variants: {
|
||||
variant: {
|
||||
default: '',
|
||||
code: 'font-mono text-xs md:text-xs'
|
||||
code: 'font-mono text-xs md:text-xs',
|
||||
/** Monospace at the body size, for a primary field that takes a path or slug. */
|
||||
'code-body': 'font-mono text-[13px] md:text-[13px]'
|
||||
},
|
||||
surface: {
|
||||
default: '',
|
||||
@@ -22,7 +24,9 @@ const inputVariants = cva('', {
|
||||
// Reserves room for an icon button absolutely positioned inside the field's right edge.
|
||||
adornment: {
|
||||
none: '',
|
||||
trailing: 'pr-8'
|
||||
trailing: 'pr-8',
|
||||
// Reserves room for a decorative icon absolutely positioned inside the field's left edge.
|
||||
leading: 'pl-7'
|
||||
}
|
||||
},
|
||||
defaultVariants: { variant: 'default', density: 'default', adornment: 'none' }
|
||||
|
||||
@@ -112,6 +112,7 @@ function PopoverContent({
|
||||
sideOffset = 4,
|
||||
wheelScroll = false,
|
||||
portalContainer,
|
||||
focusRing = false,
|
||||
style,
|
||||
onWheel,
|
||||
onWheelCapture,
|
||||
@@ -120,6 +121,8 @@ function PopoverContent({
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content> & {
|
||||
portalContainer?: HTMLElement | null
|
||||
wheelScroll?: boolean
|
||||
/** For a popover that takes focus itself (tabIndex -1): show the app focus outline on it. */
|
||||
focusRing?: boolean
|
||||
}) {
|
||||
const container = usePortalContainer(portalContainer)
|
||||
const handleConsumerWheel = React.useCallback(
|
||||
@@ -170,6 +173,8 @@ function PopoverContent({
|
||||
className={cn(
|
||||
'z-[60] overflow-hidden rounded-md border border-black/14 bg-floating-surface text-popover-foreground shadow-[0_16px_36px_rgba(0,0,0,0.24),inset_0_1px_0_rgba(255,255,255,0.14)] backdrop-blur-2xl outline-none dark:border-white/14 dark:shadow-[0_20px_44px_rgba(0,0,0,0.42),inset_0_1px_0_rgba(255,255,255,0.04)] data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
|
||||
wheelScroll && 'popover-wheel-scroll',
|
||||
focusRing &&
|
||||
'focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-focus-ring',
|
||||
className
|
||||
)}
|
||||
ref={focusScopeRef}
|
||||
|
||||
@@ -6,20 +6,37 @@ import { cn } from '@/lib/utils'
|
||||
* stays visible on white cards; the pulse stops under reduced motion. It is aria-hidden, so mark the
|
||||
* loading container aria-busy or give it sr-only "Loading…" text.
|
||||
*/
|
||||
const SKELETON_SHAPES = {
|
||||
rounded: 'rounded-md',
|
||||
/** Thin lines (terminal rows, labels) that read better with a tighter corner. */
|
||||
small: 'rounded-sm',
|
||||
circle: 'rounded-full',
|
||||
/** Large blocks (a panel or log area) that match a card's corner. */
|
||||
card: 'rounded-lg'
|
||||
} as const
|
||||
|
||||
const SKELETON_MOTION = {
|
||||
pulse: 'motion-safe:animate-pulse',
|
||||
/** A slower breath for long waits, so the placeholder doesn't feel frantic. */
|
||||
slow: 'motion-safe:animate-pulse [animation-duration:2.4s]',
|
||||
/** Static: a bar standing in for a value that is not loading (e.g. an empty meter). */
|
||||
still: ''
|
||||
} as const
|
||||
|
||||
function Skeleton({
|
||||
className,
|
||||
shape = 'rounded',
|
||||
motion = 'pulse',
|
||||
...props
|
||||
}: React.ComponentProps<'div'> & { shape?: 'rounded' | 'circle' }): React.JSX.Element {
|
||||
}: React.ComponentProps<'div'> & {
|
||||
shape?: keyof typeof SKELETON_SHAPES
|
||||
motion?: keyof typeof SKELETON_MOTION
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
aria-hidden
|
||||
className={cn(
|
||||
shape === 'circle' ? 'rounded-full' : 'rounded-md',
|
||||
'bg-skeleton motion-safe:animate-pulse',
|
||||
className
|
||||
)}
|
||||
className={cn(SKELETON_SHAPES[shape], 'bg-skeleton', SKELETON_MOTION[motion], className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -9,6 +9,10 @@ const textareaVariants = cva('', {
|
||||
variant: {
|
||||
default: '',
|
||||
code: 'font-mono',
|
||||
// Body-size text at every width (the default steps up to text-base below md).
|
||||
compact: 'text-sm md:text-sm',
|
||||
// Borderless field inside a composer card that draws its own frame and focus.
|
||||
bare: 'resize-none border-0 bg-transparent p-1 text-sm shadow-none md:text-sm focus-visible:ring-0 dark:bg-transparent',
|
||||
cell: 'h-full min-h-0 resize-none rounded-none border-0 px-2 py-0 font-mono text-xs shadow-none md:text-xs focus-visible:ring-1 focus-visible:ring-inset',
|
||||
composite:
|
||||
'resize-none rounded-none border-0 p-0 font-mono text-xs leading-5 shadow-none md:text-xs focus-visible:ring-0 dark:bg-transparent'
|
||||
|
||||
+4
@@ -1444,14 +1444,18 @@
|
||||
},
|
||||
"cloudSecrets": {
|
||||
"paste": {
|
||||
"blocked": "{{count}} need a fix and will be skipped",
|
||||
"blocked_one": "{{count}} needs a fix and will be skipped",
|
||||
"blocked_other": "{{count}} need a fix and will be skipped",
|
||||
"duplicates": "{{count}} duplicates ignored",
|
||||
"duplicates_one": "{{count}} duplicate ignored",
|
||||
"duplicates_other": "{{count}} duplicates ignored",
|
||||
"save": "Save {{count}} secrets",
|
||||
"save_one": "Save {{count}} secret",
|
||||
"save_other": "Save {{count}} secrets"
|
||||
},
|
||||
"value": {
|
||||
"lines": "Multi-line value · {{count}} lines",
|
||||
"lines_one": "Multi-line value · {{count}} line",
|
||||
"lines_other": "Multi-line value · {{count}} lines"
|
||||
}
|
||||
|
||||
@@ -2189,6 +2189,11 @@
|
||||
"leftovers": "Some changes did not apply cleanly; they were saved to {{dir}}.",
|
||||
"summary": "Branch {{branch}} with your uncommitted changes and agent chats ({{count}}). The cloud workspace is unchanged.",
|
||||
"failed": "Could not move the workspace"
|
||||
},
|
||||
"orcaCloud": {
|
||||
"workspaceActions": {
|
||||
"unavailable": "Orca Cloud is unavailable."
|
||||
}
|
||||
}
|
||||
},
|
||||
"hooks": {
|
||||
@@ -14420,7 +14425,11 @@
|
||||
"rotateConfirm": "The current URL stops working. Rotate?",
|
||||
"rotateAction": "Rotate URL",
|
||||
"rotate": "Rotate URL…",
|
||||
"rotateSaveFirst": "Save or discard your changes before rotating the URL."
|
||||
"rotateSaveFirst": "Save or discard your changes before rotating the URL.",
|
||||
"repoUrlPlaceholder": "https://github.com/acme/api",
|
||||
"labelsPlaceholder": "orca, needs-review",
|
||||
"authorsPlaceholder": "octocat, dependabot[bot]",
|
||||
"branchesPlaceholder": "main"
|
||||
},
|
||||
"trigger": {
|
||||
"schedule": "Schedule",
|
||||
@@ -14473,7 +14482,9 @@
|
||||
"keywordGithub": "github",
|
||||
"keywordCloud": "cloud",
|
||||
"sectionTitle": "Routines",
|
||||
"sectionDescription": "Agents that run in Orca Cloud on a schedule, on GitHub events or from a webhook."
|
||||
"sectionDescription": "Agents that run in Orca Cloud on a schedule, on GitHub events or from a webhook.",
|
||||
"agentCodex": "Codex",
|
||||
"agentClaude": "Claude Code"
|
||||
}
|
||||
},
|
||||
"right": {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const toasts = vi.hoisted(() => ({
|
||||
showOrcaCloudCleanupStartedToast: vi.fn(),
|
||||
showOrcaCloudCleanupDoneToast: vi.fn(),
|
||||
showOrcaCloudCleanupFailedToast: vi.fn()
|
||||
showOrcaCloudCleanupFailedToast: vi.fn<(creationId: string, tryAgain: () => void) => void>()
|
||||
}))
|
||||
vi.mock('@/lib/orca-cloud-session-toasts', () => toasts)
|
||||
|
||||
@@ -124,8 +124,9 @@ describe('Orca Cloud cancel cleanup', () => {
|
||||
canceledAt: 1000
|
||||
})
|
||||
await flush()
|
||||
const tryAgain = toasts.showOrcaCloudCleanupFailedToast.mock.calls[0]?.[1] as () => void
|
||||
tryAgain()
|
||||
const tryAgain = toasts.showOrcaCloudCleanupFailedToast.mock.calls[0]?.[1]
|
||||
expect(tryAgain).toBeTypeOf('function')
|
||||
tryAgain?.()
|
||||
await flush()
|
||||
expect(cleanupCalls).toEqual(['mine'])
|
||||
expect(toasts.showOrcaCloudCleanupStartedToast).toHaveBeenCalledTimes(2)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Lifecycle actions on an Orca Cloud workspace (restart, archive, unarchive) as store updates:
|
||||
// each marks the workspace pending while it runs and re-reads its status after.
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { CloudWorkspaceResult } from '../../../../shared/hosted-sandbox/cloud-workspace-api'
|
||||
import type { HostedArchivePullRequest } from '../../../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import {
|
||||
@@ -25,16 +26,21 @@ function withPending<T>(
|
||||
})
|
||||
}
|
||||
|
||||
const UNAVAILABLE = {
|
||||
ok: false,
|
||||
code: 'not_cloud',
|
||||
message: 'Orca Cloud is unavailable.'
|
||||
} as const
|
||||
function unavailable(): CloudWorkspaceResult<never> {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'not_cloud',
|
||||
message: translate(
|
||||
'auto.lib.orcaCloud.workspaceActions.unavailable',
|
||||
'Orca Cloud is unavailable.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function restartCloudWorkspace(workspaceId: string): Promise<CloudWorkspaceResult<null>> {
|
||||
const bridge = cloudWorkspaceApi()
|
||||
if (!bridge) {
|
||||
return Promise.resolve(UNAVAILABLE)
|
||||
return Promise.resolve(unavailable())
|
||||
}
|
||||
return withPending(workspaceId, 'restart', async () => {
|
||||
const result = await bridge.restart({ workspaceId })
|
||||
@@ -58,7 +64,7 @@ export function archiveCloudWorkspace(
|
||||
): Promise<CloudWorkspaceResult<null>> {
|
||||
const bridge = cloudWorkspaceApi()
|
||||
if (!bridge) {
|
||||
return Promise.resolve(UNAVAILABLE)
|
||||
return Promise.resolve(unavailable())
|
||||
}
|
||||
return withPending(workspaceId, 'archive', async () => {
|
||||
await deps.sleep(workspaceId)
|
||||
@@ -76,7 +82,7 @@ export function unarchiveCloudWorkspace(
|
||||
): Promise<CloudWorkspaceResult<null>> {
|
||||
const bridge = cloudWorkspaceApi()
|
||||
if (!bridge) {
|
||||
return Promise.resolve(UNAVAILABLE)
|
||||
return Promise.resolve(unavailable())
|
||||
}
|
||||
return withPending(workspaceId, 'unarchive', async () => {
|
||||
const result = await bridge.unarchive({ workspaceId })
|
||||
|
||||
@@ -69,8 +69,6 @@ export function deriveCloudDotState(input: {
|
||||
case 'waking':
|
||||
case 'provisioning':
|
||||
return 'waking'
|
||||
default:
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,18 +23,27 @@ function stub(
|
||||
getStatus: OrcaCloudWorkspaceApi['getStatus'],
|
||||
ids: string[] = []
|
||||
): OrcaCloudWorkspaceApi {
|
||||
const bridge = {
|
||||
const unused = async (): Promise<never> => {
|
||||
throw new Error('not used by these tests')
|
||||
}
|
||||
const bridge: OrcaCloudWorkspaceApi = {
|
||||
getStatus: vi.fn(getStatus),
|
||||
listCloudWorkspaceIds: vi.fn(async () => ids)
|
||||
} as unknown as OrcaCloudWorkspaceApi
|
||||
;(globalThis as unknown as { window: unknown }).window = { api: { orcaCloudWorkspace: bridge } }
|
||||
restart: vi.fn(unused),
|
||||
archive: vi.fn(unused),
|
||||
unarchive: vi.fn(unused),
|
||||
getArchive: vi.fn(unused),
|
||||
listCloudWorkspaceIds: vi.fn(async () => ids),
|
||||
onWakeProgress: vi.fn(() => () => {}),
|
||||
onOom: vi.fn(() => () => {})
|
||||
}
|
||||
vi.stubGlobal('window', { api: { orcaCloudWorkspace: bridge } })
|
||||
return bridge
|
||||
}
|
||||
|
||||
beforeEach(() => seedCloudWorkspaceSnapshot({}))
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
delete (globalThis as { window?: unknown }).window
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('wake state and archive guard', () => {
|
||||
|
||||
@@ -42,17 +42,13 @@ function stubApi(overrides: Partial<OrcaCloudWorkspaceApi> = {}): OrcaCloudWorks
|
||||
onOom: vi.fn(() => () => {}),
|
||||
...overrides
|
||||
}
|
||||
;(
|
||||
globalThis as unknown as { window: { api: { orcaCloudWorkspace: OrcaCloudWorkspaceApi } } }
|
||||
).window = {
|
||||
api: { orcaCloudWorkspace: bridge }
|
||||
}
|
||||
vi.stubGlobal('window', { api: { orcaCloudWorkspace: bridge } })
|
||||
return bridge
|
||||
}
|
||||
|
||||
beforeEach(() => seedCloudWorkspaceSnapshot({}))
|
||||
afterEach(() => {
|
||||
delete (globalThis as { window?: unknown }).window
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('orca cloud workspace store', () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from './remote-disk-usage-poll'
|
||||
import { RuntimeRpcCallError } from '../../rpc/calls/runtime-rpc-result'
|
||||
import type { OrcadDiskUsageResult } from '../../../../../shared/orcad-disk-usage'
|
||||
import type { RuntimeRpcFailure } from '../../../../../shared/runtime-rpc-envelope'
|
||||
|
||||
const RESULT: OrcadDiskUsageResult = {
|
||||
checkedAt: 1,
|
||||
@@ -17,12 +18,13 @@ const RESULT: OrcadDiskUsageResult = {
|
||||
}
|
||||
|
||||
function rpcError(code: string): RuntimeRpcCallError {
|
||||
return new RuntimeRpcCallError({
|
||||
const failure: RuntimeRpcFailure = {
|
||||
id: '1',
|
||||
ok: false,
|
||||
error: { code, message: code },
|
||||
_meta: { runtimeId: 'r' }
|
||||
} as never)
|
||||
}
|
||||
return new RuntimeRpcCallError(failure)
|
||||
}
|
||||
|
||||
function noFocus(): () => void {
|
||||
|
||||
@@ -50,7 +50,7 @@ describe('ephemeral VM workspace projection', () => {
|
||||
|
||||
describe('Orca Cloud environment builds', () => {
|
||||
it('exposes the environment build an Orca Cloud workspace booted from', () => {
|
||||
const fromBuild = {
|
||||
const fromBuild: EphemeralVmRuntimeRecord['recipeResult'] = {
|
||||
...result,
|
||||
userData: {
|
||||
environmentDriver: {
|
||||
@@ -59,7 +59,7 @@ describe('Orca Cloud environment builds', () => {
|
||||
driverState: { sandboxId: 'sbx_1', environmentBuildId: 'bld_0123456789' }
|
||||
}
|
||||
}
|
||||
} as EphemeralVmRuntimeRecord['recipeResult']
|
||||
}
|
||||
const built = project([record('vm', 'running', { recipeResult: fromBuild })])
|
||||
expect(built.ephemeralVmRuntimesByWorkspaceId['ws-1']?.environmentBuildId).toBe(
|
||||
'bld_0123456789'
|
||||
|
||||
@@ -28,10 +28,10 @@ function environmentBuildIdOf(record: EphemeralVmRuntimeRecord): string | undefi
|
||||
if (!driver || typeof driver !== 'object' || Array.isArray(driver)) {
|
||||
return undefined
|
||||
}
|
||||
const state = (driver as { driverState?: unknown }).driverState
|
||||
const state = 'driverState' in driver ? driver.driverState : undefined
|
||||
const id =
|
||||
state && typeof state === 'object' && !Array.isArray(state)
|
||||
? (state as { environmentBuildId?: unknown }).environmentBuildId
|
||||
state && typeof state === 'object' && !Array.isArray(state) && 'environmentBuildId' in state
|
||||
? state.environmentBuildId
|
||||
: undefined
|
||||
return typeof id === 'string' && id ? id : undefined
|
||||
}
|
||||
|
||||
@@ -32,6 +32,6 @@ export const Scopes = z
|
||||
.max(64)
|
||||
.transform((scopes) =>
|
||||
scopes.filter((scope): scope is CloudApiScope =>
|
||||
(CLOUD_API_SCOPES as readonly string[]).includes(scope)
|
||||
CLOUD_API_SCOPES.some((known) => known === scope)
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user