Skip to content

Commit 7a3f98d

Browse files
committed
fix(output): keep candidate rendering in surface owners
1 parent fbdbb05 commit 7a3f98d

19 files changed

Lines changed: 196 additions & 256 deletions

‎packages/kernel/src/device.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ function throwAmbiguousDeviceSelection(candidates: DeviceInfo[]): never {
421421
'AMBIGUOUS_MATCH',
422422
`${candidates.length} devices match this request equally; select one explicitly.`,
423423
{
424-
// The declared device-candidate details domain (src/daemon/handlers/error-candidates.ts), so the CLI
424+
// The declared device-candidate details domain (@agent-device/kernel/errors), so the CLI
425425
// and MCP renderers print these candidates without a new shape to learn.
426426
devices: listed.map((device) => ({ id: device.id, name: device.name })),
427427
matches: candidates.length,

‎packages/kernel/src/errors.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { readElementMatchCandidateRefs, readErrorCandidateViews } from './errors.ts';
4+
5+
test('readElementMatchCandidateRefs extracts refs from candidate lines', () => {
6+
assert.deepEqual(
7+
readElementMatchCandidateRefs({
8+
candidates: ['@e2 [button] "Follow"', '@e5~s42 [button] "Follow"', 'not a ref'],
9+
}),
10+
['e2', 'e5'],
11+
);
12+
});
13+
14+
test('readElementMatchCandidateRefs ignores non-string candidate details', () => {
15+
assert.deepEqual(readElementMatchCandidateRefs({ candidates: [{ ref: 'e2' }, 4] }), []);
16+
assert.deepEqual(readElementMatchCandidateRefs(undefined), []);
17+
});
18+
19+
test('readErrorCandidateViews projects element matches and generation', () => {
20+
assert.deepEqual(
21+
readErrorCandidateViews({
22+
matches: 7,
23+
candidates: ['@e2 [button] "Row"'],
24+
refsGeneration: 42,
25+
}),
26+
[
27+
{
28+
kind: 'element-match',
29+
matches: 7,
30+
candidates: ['@e2 [button] "Row"'],
31+
refsGeneration: 42,
32+
},
33+
],
34+
);
35+
});
36+
37+
test('readErrorCandidateViews projects devices and rejects object candidates', () => {
38+
assert.deepEqual(
39+
readErrorCandidateViews({
40+
candidates: [{ id: 'SIM-001', name: 'iPhone 17 Pro' }],
41+
devices: [{ id: 'SIM-001', name: 'iPhone 17 Pro' }],
42+
}),
43+
[{ kind: 'device', devices: [{ id: 'SIM-001', name: 'iPhone 17 Pro' }] }],
44+
);
45+
});

‎packages/kernel/src/errors.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,62 @@ export type NormalizedError = {
122122
details?: Record<string, unknown>;
123123
};
124124

125+
export type ElementMatchCandidateDetails = {
126+
candidates: string[];
127+
matches: number;
128+
refsGeneration?: number;
129+
};
130+
131+
export type ErrorCandidateView =
132+
| (ElementMatchCandidateDetails & { kind: 'element-match' })
133+
| { kind: 'device'; devices: Array<{ id: string; name: string }> };
134+
135+
export function readErrorCandidateViews(
136+
details: Record<string, unknown> | undefined,
137+
): ErrorCandidateView[] {
138+
const candidates = readStringArray(details?.candidates);
139+
const views: ErrorCandidateView[] = [];
140+
if (candidates.length > 0) {
141+
const matches = typeof details?.matches === 'number' ? details.matches : candidates.length;
142+
const refsGeneration =
143+
typeof details?.refsGeneration === 'number' ? details.refsGeneration : undefined;
144+
views.push({
145+
kind: 'element-match',
146+
candidates,
147+
matches,
148+
...(refsGeneration !== undefined ? { refsGeneration } : {}),
149+
});
150+
}
151+
const devices = readDeviceList(details?.devices);
152+
if (devices.length > 0) views.push({ kind: 'device', devices });
153+
return views;
154+
}
155+
156+
export function readElementMatchCandidateRefs(
157+
details: Record<string, unknown> | undefined,
158+
): string[] {
159+
return readStringArray(details?.candidates).flatMap((candidate) => {
160+
const match = /^@(e\d+)(?:~s\d+)?(?:\s|$)/.exec(candidate);
161+
return match?.[1] ? [match[1]] : [];
162+
});
163+
}
164+
165+
function readStringArray(value: unknown): string[] {
166+
if (!Array.isArray(value)) return [];
167+
return value.filter((entry): entry is string => typeof entry === 'string');
168+
}
169+
170+
function readDeviceList(value: unknown): Array<{ id: string; name: string }> {
171+
if (!Array.isArray(value)) return [];
172+
return value.filter(
173+
(entry): entry is { id: string; name: string } =>
174+
typeof entry === 'object' &&
175+
entry !== null &&
176+
typeof (entry as { id?: unknown }).id === 'string' &&
177+
typeof (entry as { name?: unknown }).name === 'string',
178+
);
179+
}
180+
125181
/**
126182
* Error payload returned by the daemon transport. It is kept beside the local
127183
* error representation because clients immediately rehydrate this wire shape

‎scripts/help-conformance-sample-outputs.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,7 @@ Hint: Ref @e12 was minted from snapshot s5 but the session's ref frame is now s7
114114
// — the parity test drives that exact producer. The by-design rejection
115115
// instead of silent disambiguation: #1597 made the candidate refs (ref, role,
116116
// label/identifier — the same compact rendering as snapshot -i) print
117-
// unconditionally via formatErrorCandidateLines
118-
// (src/daemon/handlers/error-candidates.ts), capped at AMBIGUOUS_MATCH_CANDIDATE_LIMIT (5) with a
117+
// unconditionally by the output owners, capped at AMBIGUOUS_MATCH_CANDIDATE_LIMIT (5) with a
119118
// "+N more" marker. Here all 3 candidates share the identical "Follow" label,
120119
// so the printed refs still cannot be told apart from this output alone —
121120
// the agent must re-observe or narrow, not guess which @ref is the right row.

‎src/ai-sdk/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export async function createAgentDeviceTools(
127127
// this exact shape as `structuredContent` (ADR 0012) — reuse it
128128
// instead of re-normalizing an already-normalized error.
129129
const normalized = result.structuredContent as NormalizedError;
130-
const message = await formatToolErrorText(normalized);
130+
const message = formatToolErrorText(normalized);
131131
throw new AppError(normalized.code, message, normalized.details);
132132
}
133133
return result.structuredContent ?? {};

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ test('printHumanError lists AMBIGUOUS_MATCH candidates unconditionally, not gate
9393
// This is the exact old-message shape the bug reported: the human render
9494
// used to stop at "Error (...): ...\nHint: ...", so an agent reading it had
9595
// no @ref to act on. Asserting the candidate lines appear proves this red
96-
// against that shape (it would fail before formatErrorCandidateLines was
97-
// wired into printHumanError).
96+
// against that shape (it would fail before candidate views were wired into
97+
// printHumanError).
9898
const output = await captureStderr(() => printHumanError(err));
9999

100100
assert.match(output, /^Error \(AMBIGUOUS_MATCH\): find matched 3 elements/);
@@ -126,8 +126,8 @@ test('printHumanError appends a "+N more" marker when candidates were capped', a
126126

127127
// The device-domain resolvers (findBootedAppleSimulatorWithApp,
128128
// src/core/dispatch-resolve.ts) key their candidate list `devices`, so the CLI
129-
// renders the udids the "pass --udid" hint asks for. Shape rules live with the
130-
// daemon-owned candidate renderer (src/daemon/handlers/__tests__/interaction-error-candidates.test.ts).
129+
// renders the udids the "pass --udid" hint asks for. The structured candidate
130+
// view comes from @agent-device/kernel/errors and formatting stays local here.
131131
test('printHumanError lists device candidates for the device-domain resolvers', async () => {
132132
const err = new AppError(
133133
'AMBIGUOUS_MATCH',

‎src/commands/output/error.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
1-
import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors';
1+
import {
2+
AppError,
3+
normalizeError,
4+
readErrorCandidateViews,
5+
type ErrorCandidateView,
6+
type NormalizedError,
7+
} from '@agent-device/kernel/errors';
28
import { formatReplayDivergenceReport } from '@agent-device/contracts/divergence';
39

4-
export async function printHumanError(
10+
export function printHumanError(
511
err: AppError | NormalizedError,
612
options: { showDetails?: boolean } = {},
7-
): Promise<void> {
13+
): void {
814
const normalized = err instanceof AppError ? normalizeError(err) : err;
9-
const { formatErrorCandidateLines } = await import('../../daemon/handlers/error-candidates.ts');
1015
process.stderr.write(`Error (${normalized.code}): ${normalized.message}\n`);
1116
if (normalized.cause) {
1217
const code = normalized.cause.code ? `${normalized.cause.code} ` : '';
@@ -15,10 +20,7 @@ export async function printHumanError(
1520
if (normalized.hint) {
1621
process.stderr.write(`Hint: ${normalized.hint}\n`);
1722
}
18-
// #1597: printed unconditionally (not gated behind --debug), same as the
19-
// divergence report below — an agent must see the candidate refs without a
20-
// follow-up round trip.
21-
const candidateLines = formatErrorCandidateLines(normalized.details);
23+
const candidateLines = formatErrorCandidateViews(readErrorCandidateViews(normalized.details));
2224
if (candidateLines.length > 0) {
2325
process.stderr.write(`${candidateLines.join('\n')}\n`);
2426
}
@@ -44,3 +46,24 @@ export async function printHumanError(
4446
process.stderr.write(`${JSON.stringify(normalized.details, null, 2)}\n`);
4547
}
4648
}
49+
50+
function formatErrorCandidateViews(views: ErrorCandidateView[]): string[] {
51+
return views.flatMap((view) => {
52+
if (view.kind === 'element-match') {
53+
const remaining = view.matches - view.candidates.length;
54+
return [
55+
'Candidates:',
56+
...view.candidates.map(
57+
(candidate) => ` ${pinCandidateLine(candidate, view.refsGeneration)}`,
58+
),
59+
...(remaining > 0 ? [` +${remaining} more`] : []),
60+
];
61+
}
62+
return ['Devices:', ...view.devices.map((device) => ` ${device.id} ${device.name}`)];
63+
});
64+
}
65+
66+
function pinCandidateLine(candidate: string, generation: number | undefined): string {
67+
if (generation === undefined) return candidate;
68+
return candidate.replace(/^@(e\d+)(?=\s|$)/, `@$1~s${generation}`);
69+
}

‎src/core/__tests__/dispatch-resolve.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ test('resolveTargetDevice refuses booted simulator selection when the requested
290290
assert.equal(error.code, 'APP_NOT_INSTALLED');
291291
assert.match(error.message, /No booted iOS simulator has com\.example\.demo installed/);
292292
// Keyed `devices`, not `candidates`: the find handler's element matches own
293-
// that key with an incompatible shape (src/daemon/handlers/error-candidates.ts).
293+
// that key with an incompatible shape (@agent-device/kernel/errors).
294294
assert.equal(error.details?.candidates, undefined);
295295
assert.deepEqual(error.details?.devices, [
296296
{ id: bootedSimulator.id, name: bootedSimulator.name },

‎src/core/device-selection-resolver.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ function withDeviceRetrySelectors(error: unknown, candidates: readonly DeviceInf
223223
/**
224224
* The device-domain candidate list. Keyed `devices`, not `candidates`: the find
225225
* handler's element matches own that key with an incompatible shape
226-
* (src/daemon/handlers/error-candidates.ts).
226+
* (@agent-device/kernel/errors).
227227
*/
228228
function deviceCandidateDetails(devices: readonly DeviceInfo[]) {
229229
return {

‎src/daemon/handlers/__tests__/interaction-error-candidates.test.ts‎

Lines changed: 0 additions & 101 deletions
This file was deleted.

0 commit comments

Comments
 (0)