Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions docs/CLOUD.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<run>/runner · flows status --cloud --watch <run>
```

Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions packages/sdk/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}

Expand Down Expand Up @@ -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
Expand Down
15 changes: 5 additions & 10 deletions packages/sdk/src/cli/cloud-mirror-session.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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';
}

/**
Expand Down Expand Up @@ -293,13 +294,7 @@ function completionReport(report: RunReport): Record<string, unknown> {
* 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'
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/tests/cli-detach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
});

Expand Down
110 changes: 101 additions & 9 deletions packages/sdk/tests/cloud-mirror-live.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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,
Expand All @@ -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<void> {
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<void> {
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<void> {
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);
Expand Down Expand Up @@ -164,28 +202,82 @@ 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],
{ FLOWS_CLOUD_MIRROR: '0' });

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';
Expand Down
19 changes: 19 additions & 0 deletions packages/sdk/tests/cloud-mirror-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
31 changes: 24 additions & 7 deletions packages/sdk/tests/named-local-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -171,30 +172,46 @@ 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();
expect(await runCli(['run', 'named-demo', '--no-observer-link'], io)).toBe(2);
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 () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/tests/observer-link.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
});

Expand Down
Loading