Skip to content

Commit a517639

Browse files
committed
refactor(client): one daemon-error normalizer + client-route regressions for initialSnapshotError
Review follow-ups on #1671: normalizeInitialSnapshotError duplicated the target-shutdown error normalization and pushed the module over the fallow complexity threshold; consolidated into a single internal normalizeDaemonError (table-driven, full shape incl. retriable/supportedOn) used by both result paths, projected through normalizeOpenForegroundComposition. Client-route regressions: createAgentDeviceClient().apps.open now proves the full initialSnapshotError shape (hint/details/diagnosticId/logPath/retriable) survives normalization, and that a malformed one is dropped — deleting the boundary normalization fails these tests. Also rebased onto current main.
1 parent 60fc817 commit a517639

4 files changed

Lines changed: 109 additions & 45 deletions

File tree

‎src/__tests__/client.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,71 @@ test('apps.open resolves session device identifiers from open response', async (
260260
]);
261261
});
262262

263+
test('apps.open preserves the full initialSnapshotError shape through client normalization', async () => {
264+
// open --foreground: open succeeded, composed snapshot did not. The public
265+
// client result must carry the FULL daemon error — dropping the boundary
266+
// normalization (or truncating to code+message) must fail here.
267+
const initialSnapshotError = {
268+
code: 'COMMAND_FAILED',
269+
message: 'capture failed',
270+
hint: 'Run: agent-device snapshot -i',
271+
details: { reason: 'runner_capture_failed' },
272+
diagnosticId: 'ms-diag-1234',
273+
logPath: '/tmp/agent-device/sessions/qa/requests/snap.ndjson',
274+
retriable: true,
275+
};
276+
const setup = createTransport(async (req) => {
277+
if (req.command === 'open') {
278+
return {
279+
ok: true,
280+
data: {
281+
session: 'qa',
282+
appName: 'Settings',
283+
appBundleId: 'com.apple.Preferences',
284+
platform: 'ios',
285+
target: 'mobile',
286+
device: 'iPhone 16',
287+
id: 'SIM-001',
288+
kind: 'simulator',
289+
device_udid: 'SIM-001',
290+
warnings: ['The session is open, but the initial interactive snapshot failed.'],
291+
initialSnapshotError,
292+
},
293+
};
294+
}
295+
throw new Error(`Unexpected command: ${req.command}`);
296+
});
297+
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
298+
299+
const result = await client.apps.open({ app: 'Settings', platform: 'ios', foreground: true });
300+
301+
assert.deepEqual(result.initialSnapshotError, initialSnapshotError);
302+
assert.equal(result.snapshot, undefined);
303+
});
304+
305+
test('apps.open drops a malformed initialSnapshotError instead of projecting garbage', async () => {
306+
const setup = createTransport(async () => ({
307+
ok: true,
308+
data: {
309+
session: 'qa',
310+
appName: 'Settings',
311+
appBundleId: 'com.apple.Preferences',
312+
platform: 'ios',
313+
target: 'mobile',
314+
device: 'iPhone 16',
315+
id: 'SIM-001',
316+
kind: 'simulator',
317+
device_udid: 'SIM-001',
318+
initialSnapshotError: { code: 'COMMAND_FAILED' },
319+
},
320+
}));
321+
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
322+
323+
const result = await client.apps.open({ app: 'Settings', platform: 'ios' });
324+
325+
assert.equal(result.initialSnapshotError, undefined);
326+
});
327+
263328
test('apps.open forwards explicit runtime hints through the daemon request', async () => {
264329
const setup = createTransport(async () => ({
265330
ok: true,

‎src/agent-device-client.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import {
4242
buildMeta,
4343
normalizeDeployResult,
4444
normalizeDevice,
45-
normalizeInitialSnapshotError,
45+
normalizeOpenForegroundComposition,
4646
normalizeInstallFromSourceResult,
4747
normalizeMaterializationReleaseResult,
4848
normalizeOpenDevice,
@@ -267,7 +267,6 @@ export function createAgentDeviceClient(
267267
const warnings = Array.isArray(data.warnings)
268268
? data.warnings.filter((warning): warning is string => typeof warning === 'string')
269269
: [];
270-
const initialSnapshotError = normalizeInitialSnapshotError(data.initialSnapshotError);
271270
return {
272271
session,
273272
...(warnings.length > 0 ? { warnings } : {}),
@@ -281,15 +280,7 @@ export function createAgentDeviceClient(
281280
startup: normalizeStartupSample(data.startup),
282281
runtime: normalizeRuntimeHints(data.runtime),
283282
device,
284-
// RFC prototype (open --foreground): only present when the daemon's
285-
// foreground-attach composition captured an initial snapshot.
286-
...(data.snapshot && typeof data.snapshot === 'object'
287-
? { snapshot: data.snapshot as Record<string, unknown> }
288-
: {}),
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 } : {}),
283+
...normalizeOpenForegroundComposition(data),
293284
identifiers: {
294285
session,
295286
deviceId: device?.id,

‎src/client/client-normalizers.ts‎

Lines changed: 33 additions & 26 deletions
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 DaemonError, type NormalizedError } from '@agent-device/kernel/errors';
19+
import { AppError, type DaemonError } 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';
@@ -253,7 +253,7 @@ export function normalizeTargetShutdownResult(value: unknown): TargetShutdownRes
253253
) {
254254
return undefined;
255255
}
256-
const error = normalizeTargetShutdownError(value.error);
256+
const error = normalizeDaemonError(value.error);
257257
return {
258258
success: value.success,
259259
exitCode: value.exitCode,
@@ -264,36 +264,43 @@ export function normalizeTargetShutdownResult(value: unknown): TargetShutdownRes
264264
}
265265

266266
/**
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.
267+
* The one normalizer for daemon errors riding inside otherwise-ok results
268+
* (target-shutdown reports, the open --foreground initial-snapshot failure).
269+
* Preserves the FULL shape — hint/details/diagnosticId/logPath plus the
270+
* additive retriable/supportedOn signals — never a code+message truncation,
271+
* so recovery guidance survives to Node/CLI JSON callers.
271272
*/
272-
export function normalizeInitialSnapshotError(value: unknown): DaemonError | undefined {
273+
const DAEMON_ERROR_STRING_FIELDS = ['hint', 'diagnosticId', 'logPath', 'supportedOn'] as const;
274+
275+
function normalizeDaemonError(value: unknown): DaemonError | undefined {
273276
if (!isRecord(value)) return undefined;
274277
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-
};
278+
const error: DaemonError = { code: value.code, message: value.message };
279+
for (const field of DAEMON_ERROR_STRING_FIELDS) {
280+
const candidate = value[field];
281+
if (typeof candidate === 'string') error[field] = candidate;
282+
}
283+
if (isRecord(value.details)) error.details = value.details;
284+
if (typeof value.retriable === 'boolean') error.retriable = value.retriable;
285+
return error;
285286
}
286287

287-
function normalizeTargetShutdownError(value: unknown): NormalizedError | undefined {
288-
if (!isRecord(value)) return undefined;
289-
if (typeof value.code !== 'string' || typeof value.message !== 'string') return undefined;
288+
/**
289+
* open --foreground composition extras on an ok open response: the initial
290+
* snapshot when the foreground-attach capture succeeded, or the FULL capture
291+
* error (never a code+message truncation) when open succeeded and the
292+
* composed snapshot did not — the session is open and usable either way.
293+
*/
294+
export function normalizeOpenForegroundComposition(data: Record<string, unknown>): {
295+
snapshot?: Record<string, unknown>;
296+
initialSnapshotError?: DaemonError;
297+
} {
298+
const initialSnapshotError = normalizeDaemonError(data.initialSnapshotError);
290299
return {
291-
code: value.code,
292-
message: value.message,
293-
...(typeof value.hint === 'string' ? { hint: value.hint } : {}),
294-
...(typeof value.diagnosticId === 'string' ? { diagnosticId: value.diagnosticId } : {}),
295-
...(typeof value.logPath === 'string' ? { logPath: value.logPath } : {}),
296-
...(isRecord(value.details) ? { details: value.details } : {}),
300+
...(data.snapshot && typeof data.snapshot === 'object'
301+
? { snapshot: data.snapshot as Record<string, unknown> }
302+
: {}),
303+
...(initialSnapshotError ? { initialSnapshotError } : {}),
297304
};
298305
}
299306

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,22 +76,23 @@ describe('openCliOutput', () => {
7676
}),
7777
);
7878

79-
expect(openOutput).toBeDefined();
80-
expect(snapshotOutput?.text).toBeTruthy();
79+
if (!openOutput?.text || !snapshotOutput?.text) {
80+
throw new Error('production formatter route returned no text output');
81+
}
8182
// The tree lines are exactly what `snapshot -i` would print, appended
8283
// after the open confirmation lines.
83-
expect(openOutput?.text).toBe(
84+
expect(openOutput.text).toBe(
8485
[
8586
'Opened: com.apple.Preferences',
8687
'Session state: /tmp/agent-device/sessions/cwd_123_default',
87-
snapshotOutput?.text,
88+
snapshotOutput.text,
8889
].join('\n'),
8990
);
90-
expect(openOutput?.text).toContain('Sign In');
91-
expect(openOutput?.text).toContain('Email');
91+
expect(openOutput.text).toContain('Sign In');
92+
expect(openOutput.text).toContain('Email');
9293
// --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);
94+
const openJsonSnapshot = (openOutput.data as { snapshot?: unknown }).snapshot;
95+
expect(openJsonSnapshot).toEqual(snapshotOutput.jsonData ?? snapshotOutput.data);
9596
});
9697

9798
test('renders the initialSnapshotError warning without a tree when the composed capture failed', () => {

0 commit comments

Comments
 (0)