Skip to content

Commit 8e239d1

Browse files
committed
fix(cli): render the composed open --foreground snapshot on default stdout and project initialSnapshotError through the public surfaces
Post-merge review on #1671 found the daemon fixes never reached the public boundaries: openCliOutput ignored the nested snapshot (the one-call promise held only under --json), and initialSnapshotError was daemon-only — absent from AppOpenResult, Node normalization, and serializeOpenResult, with the normalized shape truncated to code+message. - default open output now renders the composed interactive tree through the same snapshotCliOutput path snapshot -i uses - AppOpenResult carries initialSnapshotError as the FULL daemon error (hint/details/diagnosticId/logPath preserved) through normalization and serialization Worker-authored; committed by the coordinating session after the worker stalled twice mid-push. Tests: output.test.ts + session-open-foreground (26 pass), typecheck, oxfmt.
1 parent 2b878f8 commit 8e239d1

8 files changed

Lines changed: 158 additions & 7 deletions

File tree

‎packages/contracts/src/client-app.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { JsonObject } from './json.ts';
55
import type { SessionSurface } from './session-surface.ts';
66
import type { TargetShutdownResult } from './target-shutdown-contract.ts';
77
import type { DaemonInstallSource, SessionRuntimeHints } from '@agent-device/kernel/contracts';
8+
import type { DaemonError } from '@agent-device/kernel/errors';
89
import type { PublicPlatform } from '@agent-device/kernel/device';
910
import type {
1011
AgentDeviceIdentifiers,
@@ -84,6 +85,14 @@ export type AppOpenResult = {
8485
* fields like `identifiers`.
8586
*/
8687
snapshot?: Record<string, unknown>;
88+
/**
89+
* open --foreground: present when the session opened successfully but the
90+
* composed initial snapshot capture failed. Carries the FULL daemon error
91+
* shape (code, message, hint, details, diagnosticId, logPath) so recovery
92+
* guidance survives to the caller; the session itself is open and usable —
93+
* a `warnings` entry says so and points at `snapshot -i`.
94+
*/
95+
initialSnapshotError?: DaemonError;
8796
identifiers: AgentDeviceIdentifiers;
8897
};
8998

‎src/agent-device-client.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
buildMeta,
4343
normalizeDeployResult,
4444
normalizeDevice,
45+
normalizeInitialSnapshotError,
4546
normalizeInstallFromSourceResult,
4647
normalizeMaterializationReleaseResult,
4748
normalizeOpenDevice,
@@ -266,6 +267,7 @@ export function createAgentDeviceClient(
266267
const warnings = Array.isArray(data.warnings)
267268
? data.warnings.filter((warning): warning is string => typeof warning === 'string')
268269
: [];
270+
const initialSnapshotError = normalizeInitialSnapshotError(data.initialSnapshotError);
269271
return {
270272
session,
271273
...(warnings.length > 0 ? { warnings } : {}),
@@ -284,6 +286,10 @@ export function createAgentDeviceClient(
284286
...(data.snapshot && typeof data.snapshot === 'object'
285287
? { snapshot: data.snapshot as Record<string, unknown> }
286288
: {}),
289+
// open --foreground: full-shape capture failure (hint/details/
290+
// diagnosticId/logPath preserved) when open succeeded but the
291+
// composed snapshot did not; the session is open and usable.
292+
...(initialSnapshotError ? { initialSnapshotError } : {}),
287293
identifiers: {
288294
session,
289295
deviceId: device?.id,

‎src/client/client-normalizers.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
isSerialAddressablePlatform,
1717
type AppleOS,
1818
} from '@agent-device/kernel/device';
19-
import { AppError, type NormalizedError } from '@agent-device/kernel/errors';
19+
import { AppError, type DaemonError, type NormalizedError } from '@agent-device/kernel/errors';
2020
import type { SnapshotNode } from '@agent-device/kernel/snapshot';
2121
import { leaseScopeFromOptions, leaseScopeToRequestMeta } from '../core/lease-scope.ts';
2222
import type { DaemonRequest, SessionRuntimeHints } from '../daemon/types.ts';
@@ -263,6 +263,27 @@ export function normalizeTargetShutdownResult(value: unknown): TargetShutdownRes
263263
};
264264
}
265265

266+
/**
267+
* open --foreground: the composed initial-snapshot failure rides the open
268+
* response as a FULL daemon error (hint/details/diagnosticId/logPath — plus
269+
* the additive retriable/supportedOn signals), never a code+message
270+
* truncation, so recovery guidance survives to Node/CLI JSON callers.
271+
*/
272+
export function normalizeInitialSnapshotError(value: unknown): DaemonError | undefined {
273+
if (!isRecord(value)) return undefined;
274+
if (typeof value.code !== 'string' || typeof value.message !== 'string') return undefined;
275+
return {
276+
code: value.code,
277+
message: value.message,
278+
...(typeof value.hint === 'string' ? { hint: value.hint } : {}),
279+
...(typeof value.diagnosticId === 'string' ? { diagnosticId: value.diagnosticId } : {}),
280+
...(typeof value.logPath === 'string' ? { logPath: value.logPath } : {}),
281+
...(isRecord(value.details) ? { details: value.details } : {}),
282+
...(typeof value.retriable === 'boolean' ? { retriable: value.retriable } : {}),
283+
...(typeof value.supportedOn === 'string' ? { supportedOn: value.supportedOn } : {}),
284+
};
285+
}
286+
266287
function normalizeTargetShutdownError(value: unknown): NormalizedError | undefined {
267288
if (!isRecord(value)) return undefined;
268289
if (typeof value.code !== 'string' || typeof value.message !== 'string') return undefined;

‎src/commands/management/output.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,85 @@ describe('openCliOutput', () => {
4545
expect(output.data).toMatchObject({ warnings: [warning] });
4646
expect(output.text).toBe(`Opened: authoring\nWarning: ${warning}`);
4747
});
48+
49+
// #1671 P1: the composed open --foreground snapshot must render on default
50+
// stdout through the PRODUCTION formatter route (the family-registry entry
51+
// the CLI resolves, not a helper mock), printing the same interactive tree
52+
// lines `snapshot -i` prints after the open confirmation.
53+
test('production formatter route renders the composed --foreground snapshot tree on default output', async () => {
54+
const { formatCliOutput } = await import('../cli-output.ts');
55+
const { attachRefs } = await import('@agent-device/kernel/snapshot');
56+
const nodes = attachRefs([
57+
{ index: 0, type: 'Button', label: 'Sign In', depth: 0, hittable: true },
58+
{ index: 1, type: 'TextField', label: 'Email', depth: 0, hittable: true },
59+
]);
60+
const openResult: AppOpenResult = {
61+
session: 'default',
62+
sessionStateDir: '/tmp/agent-device/sessions/cwd_123_default',
63+
appBundleId: 'com.apple.Preferences',
64+
snapshot: { nodes, truncated: false, backend: 'xctest', refsGeneration: 1 },
65+
identifiers: { session: 'default' },
66+
};
67+
68+
const openOutput = withNoColor(() =>
69+
formatCliOutput({ name: 'open', input: {}, result: openResult }),
70+
);
71+
const snapshotOutput = withNoColor(() =>
72+
formatCliOutput({
73+
name: 'snapshot',
74+
input: { interactiveOnly: true },
75+
result: { nodes, truncated: false, backend: 'xctest', refsGeneration: 1 },
76+
}),
77+
);
78+
79+
expect(openOutput).toBeDefined();
80+
expect(snapshotOutput?.text).toBeTruthy();
81+
// The tree lines are exactly what `snapshot -i` would print, appended
82+
// after the open confirmation lines.
83+
expect(openOutput?.text).toBe(
84+
[
85+
'Opened: com.apple.Preferences',
86+
'Session state: /tmp/agent-device/sessions/cwd_123_default',
87+
snapshotOutput?.text,
88+
].join('\n'),
89+
);
90+
expect(openOutput?.text).toContain('Sign In');
91+
expect(openOutput?.text).toContain('Email');
92+
// --json carries the same presented snapshot payload snapshot -i emits.
93+
const openJsonSnapshot = (openOutput?.data as { snapshot?: unknown } | undefined)?.snapshot;
94+
expect(openJsonSnapshot).toEqual(snapshotOutput?.jsonData ?? snapshotOutput?.data);
95+
});
96+
97+
test('renders the initialSnapshotError warning without a tree when the composed capture failed', () => {
98+
const warning =
99+
'The session is open, but the initial interactive snapshot failed (COMMAND_FAILED: capture failed). Run: agent-device snapshot -i';
100+
const output = openCliOutput({
101+
session: 'default',
102+
warnings: [warning],
103+
initialSnapshotError: {
104+
code: 'COMMAND_FAILED',
105+
message: 'capture failed',
106+
hint: 'Retry with --debug and inspect diagnostics log for details.',
107+
diagnosticId: 'diag-1',
108+
logPath: '/tmp/req.ndjson',
109+
details: { reason: 'runner_unavailable' },
110+
},
111+
identifiers: { session: 'default' },
112+
});
113+
114+
expect(output.text).toBe(`Opened: default\nWarning: ${warning}`);
115+
// The FULL error shape survives into public JSON output.
116+
expect(output.data).toMatchObject({
117+
initialSnapshotError: {
118+
code: 'COMMAND_FAILED',
119+
message: 'capture failed',
120+
hint: 'Retry with --debug and inspect diagnostics log for details.',
121+
diagnosticId: 'diag-1',
122+
logPath: '/tmp/req.ndjson',
123+
details: { reason: 'runner_unavailable' },
124+
},
125+
});
126+
});
48127
});
49128

50129
describe('artifactsCliOutput', () => {

‎src/commands/management/output.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
serializeSessionListEntry,
3030
} from '../../utils/result-serialization.ts';
3131
import { readCommandMessage } from '../../utils/success-text.ts';
32+
import { snapshotCliOutput } from '../capture/output.ts';
3233
import type { CliOutput } from '../command-contract.ts';
3334
import {
3435
messageCliOutput,
@@ -101,7 +102,28 @@ export function openCliOutput(result: AppOpenResult): CliOutput {
101102
for (const warning of result.warnings ?? []) {
102103
lines.push(`Warning: ${warning}`);
103104
}
104-
return { data, text: lines.join('\n') || null };
105+
// open --foreground: the composed initial snapshot renders through the SAME
106+
// path `snapshot -i` uses (label dedupe + interactive tree text), after the
107+
// open confirmation — the one-call promise holds on default stdout, not just
108+
// --json. The composed capture is interactive-only by construction.
109+
const snapshotOutput = buildOpenInitialSnapshotOutput(result.snapshot);
110+
if (snapshotOutput) {
111+
data.snapshot = snapshotOutput.jsonData ?? snapshotOutput.data;
112+
if (snapshotOutput.text) lines.push(snapshotOutput.text);
113+
}
114+
return {
115+
data,
116+
...(snapshotOutput?.stderr ? { stderr: snapshotOutput.stderr } : {}),
117+
text: lines.join('\n') || null,
118+
};
119+
}
120+
121+
function buildOpenInitialSnapshotOutput(snapshot: AppOpenResult['snapshot']): CliOutput | null {
122+
if (!snapshot || !Array.isArray(snapshot.nodes)) return null;
123+
return snapshotCliOutput({
124+
result: snapshot as unknown as Parameters<typeof snapshotCliOutput>[0]['result'],
125+
interactiveOnly: true,
126+
});
105127
}
106128

107129
function closeCliOutput(result: AppCloseResult | SessionCloseResult): CliOutput {

‎src/daemon/handlers/__tests__/session-open-foreground.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,14 @@ test('a snapshot-capture failure never masks the successful open', async () => {
268268
// and tell the caller the session is usable.
269269
const snapshotFailure: DaemonResponse = {
270270
ok: false,
271-
error: { code: 'COMMAND_FAILED', message: 'capture failed' },
271+
error: {
272+
code: 'COMMAND_FAILED',
273+
message: 'capture failed',
274+
hint: 'Retry with --debug and inspect diagnostics log for details.',
275+
diagnosticId: 'diag-1',
276+
logPath: '/tmp/requests/req-1.ndjson',
277+
details: { reason: 'runner_unavailable' },
278+
},
272279
};
273280
dispatchSnapshotViaRuntime.mockResolvedValue(snapshotFailure);
274281

@@ -284,9 +291,15 @@ test('a snapshot-capture failure never masks the successful open', async () => {
284291
if (result.ok) {
285292
expect(result.data?.session).toBe('default');
286293
expect(result.data?.snapshot).toBeUndefined();
294+
// The FULL error shape survives — hint/details/diagnosticId/logPath, not
295+
// a code+message truncation.
287296
expect(result.data?.initialSnapshotError).toEqual({
288297
code: 'COMMAND_FAILED',
289298
message: 'capture failed',
299+
hint: 'Retry with --debug and inspect diagnostics log for details.',
300+
diagnosticId: 'diag-1',
301+
logPath: '/tmp/requests/req-1.ndjson',
302+
details: { reason: 'runner_unavailable' },
290303
});
291304
expect(result.data?.warnings).toEqual([
292305
'pre-existing warning',

‎src/daemon/handlers/session-open-foreground.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,10 +153,10 @@ export async function composeOpenWithInitialSnapshot(params: {
153153
...readStringWarnings(openResponse.data),
154154
`The session is open, but the initial interactive snapshot failed (${snapshotResponse.error.code}: ${snapshotResponse.error.message}). Run: agent-device snapshot -i`,
155155
],
156-
initialSnapshotError: {
157-
code: snapshotResponse.error.code,
158-
message: snapshotResponse.error.message,
159-
},
156+
// The FULL error shape (hint/details/diagnosticId/logPath), not a
157+
// code+message truncation — recovery guidance must survive to the
158+
// public Node/CLI JSON surfaces.
159+
initialSnapshotError: snapshotResponse.error,
160160
},
161161
};
162162
}

‎src/utils/result-serialization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ export function serializeOpenResult(result: AppOpenResult): Record<string, unkno
165165
...(result.runtime ? { runtime: result.runtime } : {}),
166166
...(result.device ? serializeSessionDevice(result.device) : {}),
167167
...(result.snapshot ? { snapshot: result.snapshot } : {}),
168+
...(result.initialSnapshotError ? { initialSnapshotError: result.initialSnapshotError } : {}),
168169
},
169170
target ? `Opened: ${target}` : 'Opened',
170171
);

0 commit comments

Comments
 (0)