Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Spawned agents now stamp a `Session-Id:` git trailer on commits when the dispatcher supplies a session reference, enabling auditors to trace each commit back to the session that produced it.
- `agent-relay node agent attach` now distinguishes between "agent does not exist" and "agent is running on a different fleet node": when a 404 resolves to a workspace-registered agent with a fleet placement, the error names the node (`agent 'X' is registered on node 'finn-mini'; cross-node attach is not yet supported`) instead of the indistinguishable "no agent named 'X'".

### Fixed

Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/cli/lib/attach-drive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,18 @@ describe('runDriveSession', () => {
expect(errors.some((args) => String(args[0]).includes("no agent named 'Ghost'"))).toBe(true);
});

it('emits cross-node hint when mode flip returns 404 and fleetHint resolves a placement', async () => {
const { deps, sockets, errors } = createHarness({
modeFlipFailure: { status: 404, error: "no agent named 'Ghost'" },
});
deps.fleetHint = vi.fn(async () => "on node 'barry'");
const code = await runDriveSession('Ghost', {}, deps);
expect(code).toBe(1);
expect(sockets).toHaveLength(0);
expect(errors.some((args) => String(args[0]).includes("on node 'barry'"))).toBe(true);
expect(errors.some((args) => String(args[0]).includes('cross-node attach'))).toBe(true);
});

it('aborts and closes the WS when the snapshot is not_found', async () => {
const { deps, sockets, errors, fetchLog } = createHarness({
snapshotResult: { status: 'not_found', message: "no agent named 'Ghost'" },
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/cli/lib/attach-drive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import {
type BrokerConnection,
} from '../lib/broker-connection.js';
import { defaultExit, runSignalHandler } from '../lib/exit.js';
import { resolveFleetHint } from '../lib/fleet-hint.js';
import {
createBrokerClient,
mapBrokerSdkFailure,
Expand Down Expand Up @@ -188,6 +189,12 @@ export interface DriveDependencies {
name: string,
deps: AttachSnapshotDeps
) => ReturnType<typeof captureAndRenderSnapshot>;
/**
* Best-effort workspace lookup for improving cross-node 404 messages.
* Defaults to `resolveFleetHint` from `fleet-hint.ts`. Tests inject a stub
* to avoid network calls.
*/
fleetHint?: (name: string) => Promise<string | null>;
/** Stdin handle — defaults to `process.stdin`. */
stdin: DriveStdin;
/** Local terminal size source — defaults to `process.stdout`. */
Expand Down Expand Up @@ -258,6 +265,7 @@ function withDefaults(overrides: Partial<DriveDependencies> = {}): DriveDependen
exit: defaultExit,
fetch: fetchFn,
captureAndRenderSnapshot,
fleetHint: resolveFleetHint,
stdin: process.stdin as DriveStdin,
terminal: {
getSize: () => {
Expand Down Expand Up @@ -1334,7 +1342,7 @@ function runDriveSessionLoop(state: DriveSessionState, deps: DriveDependencies):
const snapshot = await deps.captureAndRenderSnapshot(
{ url: connection.url, apiKey: connection.apiKey },
name,
{ fetch: deps.fetch, writeChunk: captureWrite }
{ fetch: deps.fetch, writeChunk: captureWrite, fleetHint: deps.fleetHint }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: switchInboundDeliveryModeOrAbort emits its own 'no agent named ...' message and returns before captureAndRenderSnapshot runs on a 404, so the fleetHint threaded through at this call site never gets a chance to run for the mode-switch preflight path in passthrough (and the same gap applies to drive's preflight).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/cli/src/cli/lib/attach-drive.ts, line 1345:

<comment>switchInboundDeliveryModeOrAbort emits its own 'no agent named ...' message and returns before captureAndRenderSnapshot runs on a 404, so the fleetHint threaded through at this call site never gets a chance to run for the mode-switch preflight path in passthrough (and the same gap applies to drive's preflight).</comment>

<file context>
@@ -1334,7 +1342,7 @@ function runDriveSessionLoop(state: DriveSessionState, deps: DriveDependencies):
         { url: connection.url, apiKey: connection.apiKey },
         name,
-        { fetch: deps.fetch, writeChunk: captureWrite }
+        { fetch: deps.fetch, writeChunk: captureWrite, fleetHint: deps.fleetHint }
       );
       if (settled) return;
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[cross-node-attach-lead-0811 via Chief] Fixed — commit d9dc3c6 (same fix as coderabbitai Threads 2 & 3). switchInboundDeliveryModeOrAbort now accepts fleetHint in its deps and uses it in the 404 branch, so drive and passthrough preflights emit the cross-node message. Regression tests added for both drive and passthrough.

);
if (settled) return;
switch (snapshot.status) {
Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/cli/lib/attach-passthrough.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,18 @@ describe('runPassthroughSession', () => {
expect(errors.some((args) => String(args[0]).includes("no agent named 'Ghost'"))).toBe(true);
});

it('emits cross-node hint when mode flip returns 404 and fleetHint resolves a placement', async () => {
const { deps, sockets, errors } = createHarness({
modeFlipFailure: { status: 404, error: "no agent named 'Ghost'" },
});
deps.fleetHint = vi.fn(async () => "on node 'barry'");
const code = await runPassthroughSession('Ghost', {}, deps);
expect(code).toBe(1);
expect(sockets).toHaveLength(0);
expect(errors.some((args) => String(args[0]).includes("on node 'barry'"))).toBe(true);
expect(errors.some((args) => String(args[0]).includes('cross-node attach'))).toBe(true);
});

it('aborts on snapshot not_found', async () => {
const { deps, sockets, errors, fetchLog } = createHarness({
snapshotResult: { status: 'not_found', message: "no agent named 'Ghost'" },
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/cli/lib/attach-passthrough.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
type BrokerConnection,
} from '../lib/broker-connection.js';
import { defaultExit, runSignalHandler } from '../lib/exit.js';
import { resolveFleetHint } from '../lib/fleet-hint.js';
import {
createInputStreamRecovery,
INPUT_REOPEN_BASE_DELAY_MS,
Expand Down Expand Up @@ -133,6 +134,12 @@ export interface PassthroughDependencies {
name: string,
deps: AttachSnapshotDeps
) => ReturnType<typeof captureAndRenderSnapshot>;
/**
* Best-effort workspace lookup for improving cross-node 404 messages.
* Defaults to `resolveFleetHint` from `fleet-hint.ts`. Tests inject a stub
* to avoid network calls.
*/
fleetHint?: (name: string) => Promise<string | null>;
stdin: PassthroughStdin;
terminal: PassthroughTerminal;
/** Opens the SDK PTY input stream used for raw human keystrokes. */
Expand Down Expand Up @@ -192,6 +199,7 @@ function withDefaults(overrides: Partial<PassthroughDependencies> = {}): Passthr
exit: defaultExit,
fetch: fetchFn,
captureAndRenderSnapshot,
fleetHint: resolveFleetHint,
stdin: process.stdin as PassthroughStdin,
terminal: {
getSize: () => {
Expand Down Expand Up @@ -874,7 +882,7 @@ export async function runPassthroughSession(
const snapshot = await deps.captureAndRenderSnapshot(
{ url: connection.url, apiKey: connection.apiKey },
name,
{ fetch: deps.fetch, writeChunk: captureWrite }
{ fetch: deps.fetch, writeChunk: captureWrite, fleetHint: deps.fleetHint }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);
if (settled) return;
switch (snapshot.status) {
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/cli/lib/attach-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
type AttachSnapshotConnection,
type AttachSnapshotDeps,
} from '../lib/attach.js';
import { resolveFleetHint } from '../lib/fleet-hint.js';
import { defaultExit, runSignalHandler } from '../lib/exit.js';

type ExitFn = (code: number) => never;
Expand Down Expand Up @@ -115,6 +116,12 @@ export interface ViewDependencies {
agentName: string,
deps: AttachSnapshotDeps
) => ReturnType<typeof captureAndRenderSnapshot>;
/**
* Best-effort workspace lookup for improving cross-node 404 messages.
* Defaults to `resolveFleetHint` from `fleet-hint.ts`. Tests inject a stub
* to avoid network calls.
*/
fleetHint?: (name: string) => Promise<string | null>;
/**
* True when stdout is an interactive terminal. Gates the on-detach terminal
* reset so a piped/redirected `view` never writes reset controls into the
Expand Down Expand Up @@ -160,6 +167,7 @@ function withDefaults(overrides: Partial<ViewDependencies> = {}): ViewDependenci
exit: defaultExit,
fetch: (input, init) => fetch(input, init),
captureAndRenderSnapshot,
fleetHint: resolveFleetHint,
stdoutIsTty: Boolean(process.stdout.isTTY),
...overrides,
};
Expand Down Expand Up @@ -520,7 +528,7 @@ export async function runViewSession(
const snapshot = await deps.captureAndRenderSnapshot(
{ url: connection.url, apiKey: connection.apiKey },
name,
{ fetch: deps.fetch, writeChunk: guardedWrite }
{ fetch: deps.fetch, writeChunk: guardedWrite, fleetHint: deps.fleetHint }
);
if (settled) return;
switch (snapshot.status) {
Expand Down
57 changes: 57 additions & 0 deletions packages/cli/src/cli/lib/attach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,63 @@ describe('captureAndRenderSnapshot', () => {
expect(writes).toEqual([]);
});

it('returns cross-node hint in not_found message when fleetHint resolves a placement', async () => {
const { deps, writes } = makeDeps({
fetch: vi.fn(async () => new Response('', { status: 404 })),
fleetHint: vi.fn(async () => "on node 'finn-mini'"),
});

const result = await captureAndRenderSnapshot(conn, 'remote-worker', deps);

expect(result.status).toBe('not_found');
expect(result.message).toContain('remote-worker');
expect(result.message).toContain('finn-mini');
expect(result.message).toContain('cross-node attach');
expect(writes).toEqual([]);
});

it('falls back to "no agent named" message when fleetHint returns null', async () => {
const { deps, writes } = makeDeps({
fetch: vi.fn(async () => new Response('', { status: 404 })),
fleetHint: vi.fn(async () => null),
});

const result = await captureAndRenderSnapshot(conn, 'Ghost', deps);

expect(result.status).toBe('not_found');
expect(result.message).toContain('Ghost');
expect(result.message).not.toContain('cross-node');
expect(writes).toEqual([]);
});

it('returns not_found when fleetHint rejects (never propagates)', async () => {
const { deps, writes } = makeDeps({
fetch: vi.fn(async () => new Response('', { status: 404 })),
fleetHint: vi.fn(async () => Promise.reject(new Error('network failure'))),
});

const result = await captureAndRenderSnapshot(conn, 'Ghost', deps);

expect(result.status).toBe('not_found');
expect(result.message).toContain('Ghost');
expect(result.message).not.toContain('cross-node');
expect(writes).toEqual([]);
});

it('shell-quotes agent names with spaces in the suggested command', async () => {
const { deps, writes } = makeDeps({
fetch: vi.fn(async () => new Response('', { status: 404 })),
fleetHint: vi.fn(async () => "on node 'finn-mini'"),
});

const result = await captureAndRenderSnapshot(conn, 'my agent name', deps);

expect(result.status).toBe('not_found');
// The suggested command must quote the name so it is not split by the shell.
expect(result.message).toContain("'my agent name'");
expect(result.message).not.toContain('attach my agent name ');
});

it('returns no_pty on HTTP 409', async () => {
const { deps, writes } = makeDeps({
fetch: vi.fn(async () => new Response('', { status: 409 })),
Expand Down
49 changes: 46 additions & 3 deletions packages/cli/src/cli/lib/attach.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ export interface AttachSnapshotDeps {
fetch: typeof globalThis.fetch;
/** Where the ANSI bytes get written. Typically `process.stdout.write`. */
writeChunk: (chunk: string) => void;
/**
* Optional best-effort workspace lookup. When the local broker returns 404
* for an agent, `fleetHint` is called with the agent name and may return a
* placement description like `"on node 'finn-mini'"` to produce a more
* actionable error message. If it returns `null` or is not provided, the
* original "no agent named 'X'" message is used.
*/
fleetHint?: (name: string) => Promise<string | null>;
}

/** Outcome of a snapshot capture. Callers decide whether to bail or continue
Expand Down Expand Up @@ -91,7 +99,20 @@ export async function captureAndRenderSnapshot(
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
if (failure.status === 404) {
return { status: 'not_found', message: `no agent named '${agentName}'` };
let hint: string | null = null;
if (deps.fleetHint) {
try {
hint = await deps.fleetHint(agentName);
} catch {
// Best-effort lookup — preserve the existing not-found message.
}
}
const safeArg = `'${agentName.replace(/'/g, "'\\''")}'`;
const message = hint
? `agent '${agentName}' is ${hint}; cross-node attach is not yet supported` +
` — run \`agent-relay node agent attach ${safeArg}\` on that machine`
: `no agent named '${agentName}'`;
return { status: 'not_found', message };
}
if (failure.status === 409) {
return {
Expand Down Expand Up @@ -616,7 +637,12 @@ export async function switchInboundDeliveryModeOrAbort(
name: string,
targetMode: InboundDeliveryMode,
actionPhrase: string,
deps: { fetch: typeof globalThis.fetch; error: (...args: unknown[]) => void }
deps: {
fetch: typeof globalThis.fetch;
error: (...args: unknown[]) => void;
/** Optional best-effort fleet placement lookup, same contract as {@link AttachSnapshotDeps.fleetHint}. */
fleetHint?: (name: string) => Promise<string | null>;
}
): Promise<{ previousMode: InboundDeliveryMode | null; sessionRevision: string | null } | null> {
let previousMode: InboundDeliveryMode | null = null;
try {
Expand All @@ -642,7 +668,23 @@ export async function switchInboundDeliveryModeOrAbort(
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
if (failure.status === 404) {
deps.error(`Error: no agent named '${name}'`);
let hint: string | null = null;
if (deps.fleetHint) {
try {
hint = await deps.fleetHint(name);
} catch {
// Best-effort lookup — preserve the existing not-found message.
}
}
if (hint) {
const safeArg = `'${name.replace(/'/g, "'\\''")}'`;
deps.error(
`Error: agent '${name}' is ${hint}; cross-node attach is not yet supported` +
` — run \`agent-relay node agent attach ${safeArg}\` on that machine`
);
} else {
deps.error(`Error: no agent named '${name}'`);
}
} else {
deps.error(`Error: could not ${actionPhrase}: ${failure.message ?? 'unknown error'}`);
}
Expand Down Expand Up @@ -1302,6 +1344,7 @@ export async function captureInitialSnapshot(
const snapshot = await render({ url: connection.url, apiKey: connection.apiKey }, name, {
fetch: deps.fetch,
writeChunk: deps.writeChunk,
fleetHint: deps.fleetHint,
});
switch (snapshot.status) {
case 'ok':
Expand Down
Loading
Loading