From 49bbcf83c142800d032489f50665fa4da78d7168 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Sun, 8 Nov 2026 11:57:05 -0800 Subject: [PATCH] fix(cli): require explicit Cloud mirror opt-in --- docs/CLOUD.md | 15 +-- packages/sdk/src/cli.ts | 9 +- packages/sdk/src/cli/cloud-mirror-session.ts | 15 +-- packages/sdk/tests/cli-detach.test.ts | 2 +- packages/sdk/tests/cloud-mirror-live.test.ts | 110 ++++++++++++++++-- .../sdk/tests/cloud-mirror-session.test.ts | 19 +++ packages/sdk/tests/named-local-run.test.ts | 31 +++-- packages/sdk/tests/observer-link.test.ts | 2 +- 8 files changed, 164 insertions(+), 39 deletions(-) diff --git a/docs/CLOUD.md b/docs/CLOUD.md index bdd1e8b65..bf270f6f8 100644 --- a/docs/CLOUD.md +++ b/docs/CLOUD.md @@ -192,17 +192,18 @@ started in a terminal, and it is unchanged. The Observer link needs `RELAYCAST_WORKSPACE_KEY` or an active workspace key in `~/.agentworkforce/relay/workspaces.json`. When neither is available, a plain `flows run` prints one hint: configure a workspace key for the Observer link, -or sign in with `agent-relay cloud login` for the Cloud dashboard. `--no-observer-link`, +or use `--cloud-mirror` after signing in for the Cloud dashboard. `--no-observer-link`, `FLOWS_NO_OBSERVER=1`, and `--json` suppress that human-facing hint. -Signed-in local runs also appear on the **Cloud dashboard**. The CLI reuses -`agent-relay cloud login` credentials (or `FLOWS_CLOUD_TOKEN`). Signed-out runs -print one note and continue locally. +Local runs appear on the **Cloud dashboard** only when `--cloud-mirror` or +`FLOWS_CLOUD_MIRROR=1` explicitly requests that projection. The CLI then reuses +`agent-relay cloud login` credentials (or `FLOWS_CLOUD_TOKEN`). A login by +itself never uploads a local run. ```sh agent-relay cloud login flows deploy review.flow.ts # save a manual flow without a trigger -flows run review --input '{"pr":7}' # resolve your saved flow and run locally +flows run review --input '{"pr":7}' --cloud-mirror # resolve, run locally, and mirror # Dashboard: https://…/dashboard/workflow//runner · flows status --cloud --watch ``` @@ -240,8 +241,8 @@ The dashboard stores the flow source, step metadata, agent transcripts and this invocation's output. Reported strings pass through the same redactor as `flows status`. Reporting follows only the current run and child journals named by its authored-step index. Reporting failures leave local execution and -the journal unchanged. `--cloud-mirror` and `FLOWS_CLOUD_MIRROR=1` remain explicit -requests for reporting; signed-in runs report automatically without either. +the journal unchanged. `--cloud-mirror` and `FLOWS_CLOUD_MIRROR=1` are the only +requests for reporting; being signed in is authentication, not consent to upload. The terminal line names Cloud's run id as well as the page, because the report's own `runId` is the *journal's* and every hosted read verb (`flows diff --git a/packages/sdk/src/cli.ts b/packages/sdk/src/cli.ts index 3ba441e0b..71ff293d5 100644 --- a/packages/sdk/src/cli.ts +++ b/packages/sdk/src/cli.ts @@ -264,7 +264,7 @@ export async function runCli( const link = resolveObserverLinkEnv(process.env); if (!link.suppressed && link.workspaceKey === undefined) { io.stderr('Observer unavailable: no workspace key configured; set RELAYCAST_WORKSPACE_KEY or configure ' - + '~/.agentworkforce/relay/workspaces.json for an Observer link, or sign in with agent-relay cloud login for the Cloud dashboard'); + + '~/.agentworkforce/relay/workspaces.json for an Observer link, or use --cloud-mirror after signing in for the Cloud dashboard'); } } @@ -414,14 +414,15 @@ export async function runCli( onObserverUrl: url => options.detachedReceipt?.observerUrl(url), }); const runnerLog: string[] = []; - const mirror = createCloudMirrorSession({ + const mirrorRequested = parsed.cloudMirror || cloudMirrorRequested(process.env); + const mirror = mirrorRequested ? createCloudMirrorSession({ source: parsed.command === 'run' ? mirrorSourceFromPath(parsed.value, parsed.input, parsed.dataDir, named) : mirrorSourceFromJournal(parsed.dataDir), dataDir: parsed.dataDir, log: () => runnerLog, - requested: parsed.cloudMirror ? 'flag' : cloudMirrorRequested(process.env) ? 'env' : 'login', - }, io); + requested: parsed.cloudMirror ? 'flag' : 'env', + }, io) : undefined; // Everything this invocation prints, kept in order, so the mirror can upload // it as the run's `runner.log` — the object the dashboard's log pane reads, // and the sandbox's own equivalent. A declarative run emits no progress diff --git a/packages/sdk/src/cli/cloud-mirror-session.ts b/packages/sdk/src/cli/cloud-mirror-session.ts index 1a942f5aa..cc42c1991 100644 --- a/packages/sdk/src/cli/cloud-mirror-session.ts +++ b/packages/sdk/src/cli/cloud-mirror-session.ts @@ -1,5 +1,6 @@ -// Signed-in local runs project their journal onto the Cloud dashboard. -// Reporting is best-effort and never changes the durable run outcome. +// Local runs project their journal onto the Cloud dashboard only when the +// invocation explicitly opts in. Reporting is best-effort and never changes +// the durable run outcome. import { readFile } from 'node:fs/promises'; import type { CliIo } from '../cli.js'; @@ -61,7 +62,7 @@ export interface CloudMirrorRequest { /** Lines the CLI has printed for this run, uploaded as the run's `runner.log`. */ log: () => readonly string[]; /** How the dashboard was asked for, so a refusal can name the right switch. */ - requested: 'flag' | 'env' | 'login'; + requested: 'flag' | 'env'; } /** @@ -293,13 +294,7 @@ function completionReport(report: RunReport): Record { * missing-login case is the common one and names the two commands that fix * it: sign in, or stop asking. */ -function mirrorRefusal(error: unknown, requested: 'flag' | 'env' | 'login'): string { - if (requested === 'login') { - if (error instanceof CloudFlowError && error.reason === 'auth_missing') { - return 'Not signed in; this run stays local. Sign in with `agent-relay cloud login` to report runs.'; - } - return `Local run reporting unavailable: ${error instanceof Error ? error.message : String(error)}; the run itself is unaffected.`; - } +function mirrorRefusal(error: unknown, requested: 'flag' | 'env'): string { const asked = requested === 'flag' ? '--cloud-mirror' : `${MIRROR_ENV}=1`; if (error instanceof CloudFlowError && error.code === 'configuration') { return error.reason === 'auth_missing' diff --git a/packages/sdk/tests/cli-detach.test.ts b/packages/sdk/tests/cli-detach.test.ts index 90c7fba06..f6094ec0a 100644 --- a/packages/sdk/tests/cli-detach.test.ts +++ b/packages/sdk/tests/cli-detach.test.ts @@ -62,7 +62,7 @@ describe('detached CLI contract', () => { expect(stderr.filter(line => line.startsWith('Observer unavailable:'))).toEqual([ 'Observer unavailable: no workspace key configured; set RELAYCAST_WORKSPACE_KEY or configure ' - + '~/.agentworkforce/relay/workspaces.json for an Observer link, or sign in with agent-relay cloud login for the Cloud dashboard', + + '~/.agentworkforce/relay/workspaces.json for an Observer link, or use --cloud-mirror after signing in for the Cloud dashboard', ]); }); diff --git a/packages/sdk/tests/cloud-mirror-live.test.ts b/packages/sdk/tests/cloud-mirror-live.test.ts index e4db141c1..477704ef4 100644 --- a/packages/sdk/tests/cloud-mirror-live.test.ts +++ b/packages/sdk/tests/cloud-mirror-live.test.ts @@ -16,6 +16,7 @@ import { dirname, join, resolve } from 'node:path'; import { spawn, spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { readDetachedRecord } from '../src/cli/detached-record.js'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..'); const BUILT_CLI = join(ROOT, 'packages', 'sdk', 'dist', 'cli.js'); @@ -51,7 +52,10 @@ let origin: string; let seen: Seen[] = []; /** One `flows run`, with the stub Cloud configured. */ -function runCli(args: readonly string[], extraEnv: NodeJS.ProcessEnv = {}): Promise<{ stderr: string; code: number }> { +function runCli( + args: readonly string[], + extraEnv: NodeJS.ProcessEnv = {}, +): Promise<{ stdout: string; stderr: string; code: number }> { return new Promise((done, reject) => { const child = spawn(process.execPath, [BUILT_CLI, ...args], { cwd: work, @@ -65,14 +69,48 @@ function runCli(args: readonly string[], extraEnv: NodeJS.ProcessEnv = {}): Prom }, stdio: ['ignore', 'pipe', 'pipe'], }); + let stdout = ''; let stderr = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); child.stderr.on('data', chunk => { stderr += chunk; }); - child.stdout.resume(); child.on('error', reject); - child.on('close', code => done({ stderr, code: code ?? 1 })); + child.on('close', code => done({ stdout, stderr, code: code ?? 1 })); }); } +async function waitForDetachedFinish(recordPath: string): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + const record = readDetachedRecord(recordPath); + if (record?.phase === 'finished') return; + if (record?.phase === 'refused') throw new Error(`detached run refused: ${JSON.stringify(record)}`); + await new Promise(resolve => setTimeout(resolve, 25)); + } + throw new Error(`detached run did not finish: ${recordPath}`); +} + +async function waitForSeen(predicate: (call: Seen) => boolean): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + if (seen.some(predicate)) return; + await new Promise(resolve => setTimeout(resolve, 25)); + } + throw new Error(`expected Cloud request was not observed: ${JSON.stringify(seen)}`); +} + +async function waitForProcessExit(pid: number): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + try { process.kill(pid, 0); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ESRCH') return; + throw error; + } + await new Promise(resolve => setTimeout(resolve, 25)); + } + throw new Error(`detached process did not exit: ${pid}`); +} + beforeAll(async () => { expect(existsSync(RELAYFLOWD), `relayflowd at ${RELAYFLOWD} — build it with (cd kernel && ../ops/cargo.sh build)`).toBe(true); expect(existsSync(BUILT_CLI), `built CLI at ${BUILT_CLI} — build it with (cd packages/sdk && npm run build)`).toBe(true); @@ -164,7 +202,7 @@ describe('a local run on the Cloud dashboard', () => { expect(terminal.body).toMatchObject({ status: 'completed', callbackToken: 'cb' }); }, 120_000); - it('reports signed-in runs automatically and keeps signed-out runs local', async () => { + it('keeps signed-in runs local unless the invocation explicitly opts in', async () => { seen = []; const plain = await runCli(['run', '--no-observer-link', '--data-dir', join(work, 'data'), FLOW]); const zero = await runCli(['run', '--no-observer-link', '--data-dir', join(work, 'data'), FLOW], @@ -172,20 +210,74 @@ describe('a local run on the Cloud dashboard', () => { expect(plain.code, plain.stderr).toBe(0); expect(zero.code, zero.stderr).toBe(0); - expect(plain.stderr).toContain('Dashboard:'); - expect(zero.stderr).toContain('Dashboard:'); - expect(seen.filter(call => call.url === '/api/v1/workflows/local-run')).toHaveLength(2); - expect(seen.filter(call => call.url === '/api/v1/workflows/callback')).toHaveLength(2); + expect(plain.stderr).not.toContain('Dashboard:'); + expect(zero.stderr).not.toContain('Dashboard:'); + expect(seen).toEqual([]); seen = []; const signedOut = await runCli(['run', '--no-observer-link', '--data-dir', join(work, 'data'), FLOW], { FLOWS_CLOUD_TOKEN: undefined }); expect(signedOut.code, signedOut.stderr).toBe(0); - expect(signedOut.stderr).toContain('Not signed in; this run stays local'); expect(signedOut.stderr).not.toContain('Dashboard:'); expect(seen).toEqual([]); }, 180_000); + it('keeps resume and detach local, while the environment switch remains an explicit opt-in', async () => { + const dataDir = join(work, 'resume-data'); + seen = []; + const initial = await runCli(['run', '--json', '--no-observer-link', '--data-dir', dataDir, FLOW]); + expect(initial.code, initial.stderr).toBe(0); + const runId = (JSON.parse(initial.stdout) as { runId: string }).runId; + expect(runId).toMatch(/^[A-Za-z0-9][A-Za-z0-9_-]*$/u); + expect(seen).toEqual([]); + + const resumed = await runCli(['resume', runId, '--json', '--no-observer-link', '--data-dir', dataDir]); + expect(resumed.code, resumed.stderr).toBe(0); + expect(seen).toEqual([]); + + const detachedData = join(work, 'detached-data'); + const detached = await runCli(['run', '--json', '--no-observer-link', '--detach', + '--data-dir', detachedData, FLOW]); + expect(detached.code, detached.stderr).toBe(0); + const handle = JSON.parse(detached.stdout) as { pid: number; recordPath: string }; + await waitForDetachedFinish(handle.recordPath); + await waitForProcessExit(handle.pid); + expect(seen).toEqual([]); + + const mirroredData = join(work, 'env-data'); + const mirrored = await runCli(['run', '--no-observer-link', '--data-dir', mirroredData, FLOW], + { FLOWS_CLOUD_MIRROR: '1' }); + expect(mirrored.code, mirrored.stderr).toBe(0); + expect(seen.some(call => call.url === '/api/v1/workflows/local-run')).toBe(true); + expect(mirrored.stderr).toContain('Dashboard:'); + }, 180_000); + + it('mirrors resume and detached execution when the flag explicitly opts them in', async () => { + const dataDir = join(work, 'explicit-resume-data'); + seen = []; + const initial = await runCli(['run', '--json', '--no-observer-link', '--data-dir', dataDir, FLOW]); + expect(initial.code, initial.stderr).toBe(0); + const runId = (JSON.parse(initial.stdout) as { runId: string }).runId; + expect(seen).toEqual([]); + + const resumed = await runCli(['resume', runId, '--cloud-mirror', '--no-observer-link', + '--data-dir', dataDir]); + expect(resumed.code, resumed.stderr).toBe(0); + expect(resumed.stderr).toContain('Dashboard:'); + expect(seen.some(call => call.url === '/api/v1/workflows/local-run')).toBe(true); + expect(seen.some(call => call.url === '/api/v1/workflows/callback')).toBe(true); + + seen = []; + const detachedData = join(work, 'explicit-detached-data'); + const detached = await runCli(['run', '--json', '--no-observer-link', '--cloud-mirror', '--detach', + '--data-dir', detachedData, FLOW]); + expect(detached.code, detached.stderr).toBe(0); + const handle = JSON.parse(detached.stdout) as { recordPath: string }; + await waitForDetachedFinish(handle.recordPath); + await waitForSeen(call => call.url === '/api/v1/workflows/callback'); + expect(seen.some(call => call.url === '/api/v1/workflows/local-run')).toBe(true); + }, 180_000); + it('publishes a composed authored flow as one connected dashboard DAG', async () => { seen = []; await writeFile(join(work, 'child.flow.ts'), `import { flow } from '@relayflows/surface'; diff --git a/packages/sdk/tests/cloud-mirror-session.test.ts b/packages/sdk/tests/cloud-mirror-session.test.ts index ea3ee637c..a212b785c 100644 --- a/packages/sdk/tests/cloud-mirror-session.test.ts +++ b/packages/sdk/tests/cloud-mirror-session.test.ts @@ -125,6 +125,25 @@ describe('createCloudMirrorSession', () => { expect(err[0]).toContain('agent-relay cloud login'); }); + it('names the environment opt-in when it cannot find a Cloud login', async () => { + const { io: cli, err } = io(); + const missing = new CloudFlowError('configuration', 'Set FLOWS_CLOUD_TOKEN …'); + missing.reason = 'auth_missing'; + const session = createCloudMirrorSession({ + source: async () => ({ workflow: 'name: demo\n', fileType: 'yaml' }), + dataDir: '/data', + log: () => [], + requested: 'env', + }, cli, {}, { register: vi.fn(async () => { throw missing; }) }); + + session.onRunStarted({ runId: '01RUN' }); + await expect(session.finish(okReport)).resolves.toBeUndefined(); + + expect(err).toHaveLength(1); + expect(err[0]).toContain(`${MIRROR_ENV}=1 asked for the Cloud dashboard`); + expect(err[0]).toContain('no Cloud login, so this run stays local'); + }); + it('names a deployment that does not serve the route yet, without blaming the run', async () => { const { io: cli, err } = io(); const session = createCloudMirrorSession({ diff --git a/packages/sdk/tests/named-local-run.test.ts b/packages/sdk/tests/named-local-run.test.ts index be64dc77b..e918e20f5 100644 --- a/packages/sdk/tests/named-local-run.test.ts +++ b/packages/sdk/tests/named-local-run.test.ts @@ -149,13 +149,14 @@ describe('named local flows against a fake HTTP server', () => { expect(state.executed).toEqual([]); }); - it('uses cloud login and reports named runs without a mirror flag, callback last', async () => { + it('uses cloud login to report an explicitly mirrored named run, callback last', async () => { vi.stubEnv('FLOWS_CLOUD_TOKEN', undefined); await writeFile(join(directory, 'cloud-auth.json'), JSON.stringify({ apiUrl: 'https://fake-cloud.example', accessToken: 'login-token', })); const { io, out } = capture(); - expect(await runCli(['run', 'named-demo', '--input', '{"n":1}', '--json', '--no-observer-link', '--data-dir', directory], io)).toBe(0); + expect(await runCli(['run', 'named-demo', '--input', '{"n":1}', '--json', '--no-observer-link', + '--cloud-mirror', '--data-dir', directory], io)).toBe(0); expect(state.executed).toEqual([join(state.cacheRoot, 'named-demo', `${sha}.flow.ts`)]); const registration = requests.find(r => r.path.endsWith('/local-run'))!; expect(registration.authorization).toBe('Bearer login-token'); @@ -171,10 +172,21 @@ describe('named local flows against a fake HTTP server', () => { it('runs a saved name without input using an empty object', async () => { const { io } = capture(); - expect(await runCli(['run', 'named-demo', '--no-observer-link', '--data-dir', directory], io)).toBe(0); + expect(await runCli(['run', 'named-demo', '--no-observer-link', '--cloud-mirror', + '--data-dir', directory], io)).toBe(0); expect(requests.find(r => r.path.endsWith('/local-run'))!.body.inputs).toEqual({}); }); + it('resolves a signed-in saved name without treating login as mirror consent', async () => { + const { io, err } = capture(); + expect(await runCli(['run', 'named-demo', '--json', '--no-observer-link', '--data-dir', directory], io)).toBe(0); + expect(state.executed).toEqual([join(state.cacheRoot, 'named-demo', `${sha}.flow.ts`)]); + expect(requests.map(request => request.path)).toEqual(['/api/v1/flows/by-name/named-demo']); + expect(requests.some(request => request.path.endsWith('/local-run'))).toBe(false); + expect(requests.some(request => request.path.endsWith('/callback'))).toBe(false); + expect(err).toEqual([]); + }); + it('refuses malformed metadata before executing downloaded code', async () => { response.body = { ...named, fileType: 'yaml' }; const { io } = capture(); @@ -182,19 +194,24 @@ describe('named local flows against a fake HTTP server', () => { expect(state.executed).toEqual([]); }); - it('reports file runs automatically and stays local with one note when signed out', async () => { + it('keeps file runs local regardless of login until mirroring is explicitly requested', async () => { const path = join(directory, 'demo.flow.ts'); await writeFile(path, source); const args = ['run', path, '--input', '{}', '--json', '--no-observer-link', '--data-dir', directory]; - expect(await runCli(args, capture().io)).toBe(0); + const signedIn = capture(); + expect(await runCli(args, signedIn.io)).toBe(0); + expect(requests).toEqual([]); + expect(signedIn.err).toEqual([]); + + const mirrored = capture(); + expect(await runCli([...args, '--cloud-mirror'], mirrored.io)).toBe(0); expect(requests.find(r => r.path.endsWith('/local-run'))!.body).not.toHaveProperty('flowId'); requests = []; vi.stubEnv('FLOWS_CLOUD_TOKEN', undefined); const { io, err } = capture(); expect(await runCli(args, io)).toBe(0); expect(requests).toEqual([]); - expect(err).toHaveLength(1); - expect(err[0]).toContain('Not signed in; this run stays local'); + expect(err).toEqual([]); }); it('saves a manual flow without repo, approver or trigger and prints its run command', async () => { diff --git a/packages/sdk/tests/observer-link.test.ts b/packages/sdk/tests/observer-link.test.ts index 631326c24..5bd22a882 100644 --- a/packages/sdk/tests/observer-link.test.ts +++ b/packages/sdk/tests/observer-link.test.ts @@ -693,7 +693,7 @@ describe('flows run: observer link integration', () => { expect(output.stdout.some((line) => line.startsWith('Observer:'))).toBe(false); expect(output.stderr.filter(line => line.startsWith('Observer unavailable:'))).toEqual([ 'Observer unavailable: no workspace key configured; set RELAYCAST_WORKSPACE_KEY or configure ' - + '~/.agentworkforce/relay/workspaces.json for an Observer link, or sign in with agent-relay cloud login for the Cloud dashboard', + + '~/.agentworkforce/relay/workspaces.json for an Observer link, or use --cloud-mirror after signing in for the Cloud dashboard', ]); });