Skip to content

Commit 523add4

Browse files
committed
fix(metro): report what the dev-server stop proved instead of assuming success
stopSpawnedMetroProcess read a refused SIGTERM as cleanup done and stayed quiet about it, so a dev server left running by a failed prepare looked stopped. It now runs on the same host-kit stopper the companion uses and decorates the readiness failure with the verdict: the pid, the reason, and the refusing signal and errno. The companion's own verdict also survives the bridge wrapper, which flattens the message into a bridgeError= fragment, by travelling in details.
1 parent e9c174d commit 523add4

3 files changed

Lines changed: 185 additions & 154 deletions

File tree

‎src/__tests__/client-metro-auto-companion.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
33
import fs from 'node:fs';
44
import path from 'node:path';
55
import { mkdtempForTestSync } from '@agent-device/test-kit/tmp-dir';
6+
import { AppError } from '@agent-device/kernel/errors';
67

78
vi.mock('../metro/client-metro-companion.ts', () => ({
89
ensureMetroCompanion: vi.fn(),
@@ -224,7 +225,7 @@ test('prepareMetroRuntime rejects bridged descriptors without iOS bundle URLs',
224225
}
225226
});
226227

227-
test('prepareMetroRuntime preserves the initial bridge error if companion startup fails', async () => {
228+
test('prepareMetroRuntime preserves the initial bridge error and companion stop verdict', async () => {
228229
const tempRoot = mkdtempForTestSync('agent-device-metro-companion-error-');
229230
const projectRoot = path.join(tempRoot, 'project');
230231
fs.mkdirSync(path.join(projectRoot, 'node_modules'), { recursive: true });
@@ -239,7 +240,16 @@ test('prepareMetroRuntime preserves the initial bridge error if companion startu
239240
}),
240241
);
241242

242-
vi.mocked(ensureMetroCompanion).mockRejectedValue(new Error('companion startup failed'));
243+
vi.mocked(ensureMetroCompanion).mockRejectedValue(
244+
// A companion stop that could not confirm the exit arrives typed, and the wrapper flattens the
245+
// message into a `bridgeError=` fragment: the verdict has to travel in `details` to be usable.
246+
new AppError('COMMAND_FAILED', 'companion startup failed', {
247+
reason: 'signal-failed',
248+
signal: 'SIGTERM',
249+
errno: 'EPERM',
250+
pid: 4101,
251+
}),
252+
);
243253

244254
const fetchMock = vi.fn();
245255
fetchMock.mockResolvedValueOnce({
@@ -269,6 +279,11 @@ test('prepareMetroRuntime preserves the initial bridge error if companion startu
269279
assert.match(error.message, /bridgeError=companion startup failed/);
270280
assert.match(error.message, /initialBridgeError=initial bridge auth failed/);
271281
assert.doesNotMatch(error.message, /metroCompanionLog=/);
282+
const details = (error as AppError).details;
283+
assert.equal(details?.reason, 'signal-failed');
284+
assert.equal(details?.signal, 'SIGTERM');
285+
assert.equal(details?.errno, 'EPERM');
286+
assert.equal(details?.pid, 4101);
272287
return true;
273288
},
274289
);

‎src/__tests__/client-metro-startup-cleanup.test.ts‎

Lines changed: 118 additions & 126 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,27 @@ import assert from 'node:assert/strict';
33
import fs from 'node:fs';
44
import path from 'node:path';
55
import { mkdtempForTestSync } from '@agent-device/test-kit/tmp-dir';
6+
import type { AppError } from '@agent-device/kernel/errors';
67

78
vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({
89
...(await importOriginal<typeof import('@agent-device/host-kit/command')>()),
910
runCmdDetached: vi.fn(),
1011
runCmdSync: vi.fn(),
1112
}));
13+
// Host-kit's own suite proves what each host answer means; this one owns the Metro half: the
14+
// budgets it hands over, and what the readiness failure says about what the stop came back with.
1215
vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({
1316
...(await importOriginal<typeof import('@agent-device/host-kit/process')>()),
14-
waitForProcessExit: vi.fn(),
17+
readProcessStartTime: vi.fn(),
18+
stopProcessAndConfirmExit: vi.fn(),
1519
}));
1620

1721
import { runCmdDetached } from '@agent-device/host-kit/command';
18-
import { waitForProcessExit } from '@agent-device/host-kit/process';
22+
import {
23+
readProcessStartTime,
24+
stopProcessAndConfirmExit,
25+
type ConfirmedProcessStop,
26+
} from '@agent-device/host-kit/process';
1927

2028
import { prepareMetroRuntime } from '../metro/client-metro.ts';
2129

@@ -26,6 +34,10 @@ afterEach(() => {
2634
vi.unstubAllGlobals();
2735
});
2836

37+
const SPAWNED_METRO_PID = 987;
38+
const SPAWNED_METRO_START = 'Mon Oct 13 00:00:00 2026';
39+
const METRO_STOP_BUDGET = { termTimeoutMs: 1_000, killTimeoutMs: 1_000 };
40+
2941
function createMetroProject(label: string): string {
3042
const tempRoot = mkdtempForTestSync(`agent-device-metro-startup-cleanup-${label}-`);
3143
const projectRoot = path.join(tempRoot, 'project');
@@ -56,8 +68,11 @@ function metroPrepareInput(projectRoot: string) {
5668
} as const;
5769
}
5870

59-
/** Starts a prepare whose Metro never becomes ready, letting readiness time out under fake timers. */
60-
async function runMetroPrepareThroughTimeout(projectRoot: string): Promise<void> {
71+
/**
72+
* Runs a prepare whose Metro never becomes ready and hands back the failure it rejected with, so a
73+
* case can read the cleanup verdict off the readiness failure. Fake timers keep the budget virtual.
74+
*/
75+
async function runMetroPrepareThroughTimeout(projectRoot: string): Promise<AppError> {
6176
const fetchMock = vi.fn().mockResolvedValue({
6277
ok: true,
6378
status: 200,
@@ -72,142 +87,119 @@ async function runMetroPrepareThroughTimeout(projectRoot: string): Promise<void>
7287
);
7388
await vi.advanceTimersByTimeAsync(30_000);
7489
await expectedFailure;
90+
return (await preparePromise.catch((error: unknown) => error)) as AppError;
7591
}
7692

77-
type KillSignal = 'SIGTERM' | 'SIGKILL';
78-
79-
function spyOnKill(behavior: (signal: KillSignal) => boolean): {
80-
signals: Array<[number, string]>;
81-
} {
82-
const signals: Array<[number, string]> = [];
83-
vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => {
84-
const name = (signal ?? 'SIGTERM') as KillSignal;
85-
signals.push([pid, name]);
86-
return behavior(name) as true;
87-
}) as typeof process.kill);
88-
return { signals };
89-
}
93+
/** What the readiness failure's `details` must carry; undefined keys pin what must stay absent. */
94+
const NO_CLEANUP = { reason: undefined, signal: undefined, errno: undefined, pid: undefined };
9095

91-
function killError(code: string): NodeJS.ErrnoException {
92-
return Object.assign(new Error(`kill failed: ${code}`), { code });
96+
function cleanupDetails(error: AppError): Record<string, unknown> {
97+
const details = error.details ?? {};
98+
return { reason: details.reason, signal: details.signal, errno: details.errno, pid: details.pid };
9399
}
94100

95-
test('prepareMetroRuntime stops a spawned Metro process when startup readiness times out', async () => {
96-
const projectRoot = createMetroProject('timeout');
97-
vi.mocked(runCmdDetached).mockReturnValue(987);
98-
vi.mocked(waitForProcessExit).mockResolvedValue(true);
99-
const kill = spyOnKill(() => true);
100-
101-
try {
102-
await runMetroPrepareThroughTimeout(projectRoot);
103-
assert.equal(vi.mocked(runCmdDetached).mock.calls.length, 1);
104-
assert.deepEqual(kill.signals, [[987, 'SIGTERM']]);
105-
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [[987, 1_000]]);
106-
} finally {
107-
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
108-
}
109-
});
110-
111-
test('stopSpawnedMetroProcess gives up cleanup (best effort) when SIGTERM throws ESRCH or EPERM', async () => {
112-
for (const code of ['ESRCH', 'EPERM']) {
113-
vi.clearAllMocks();
114-
const projectRoot = createMetroProject(`term-${code}`);
115-
vi.mocked(runCmdDetached).mockReturnValue(987);
116-
const kill = spyOnKill(() => {
117-
throw killError(code);
118-
});
119-
120-
try {
121-
await runMetroPrepareThroughTimeout(projectRoot);
122-
assert.deepEqual(kill.signals, [[987, 'SIGTERM']], `${code} on SIGTERM must stop cleanup`);
123-
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 0, code);
124-
} finally {
125-
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
126-
}
127-
}
128-
});
129-
130-
test('stopSpawnedMetroProcess escalates to SIGKILL when SIGTERM does not exit the process', async () => {
131-
const projectRoot = createMetroProject('escalate');
132-
vi.mocked(runCmdDetached).mockReturnValue(987);
133-
vi.mocked(waitForProcessExit).mockResolvedValue(false);
134-
const kill = spyOnKill(() => true);
135-
136-
try {
137-
await runMetroPrepareThroughTimeout(projectRoot);
138-
assert.deepEqual(kill.signals, [
139-
[987, 'SIGTERM'],
140-
[987, 'SIGKILL'],
141-
]);
142-
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [
143-
[987, 1_000],
144-
[987, 1_000],
145-
]);
146-
} finally {
147-
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
148-
}
149-
});
150-
151-
test('stopSpawnedMetroProcess gives up cleanup (best effort) when SIGKILL throws ESRCH or EPERM', async () => {
152-
for (const code of ['ESRCH', 'EPERM']) {
153-
vi.clearAllMocks();
154-
const projectRoot = createMetroProject(`kill-${code}`);
155-
vi.mocked(runCmdDetached).mockReturnValue(987);
156-
vi.mocked(waitForProcessExit).mockResolvedValue(false);
157-
const kill = spyOnKill((signal) => {
158-
if (signal === 'SIGKILL') throw killError(code);
159-
return true;
160-
});
101+
/**
102+
* Every cleanup outcome, read off the readiness failure it decorates: the message names the pid that
103+
* still holds the port and `details` is what a caller dispatches on.
104+
*/
105+
test.each([
106+
{
107+
name: 'the cleanup confirmed the exit',
108+
stop: { status: 'stopped' } satisfies ConfirmedProcessStop,
109+
says: '',
110+
details: NO_CLEANUP,
111+
},
112+
{
113+
name: 'a signal was refused',
114+
stop: {
115+
status: 'retained',
116+
reason: 'signal-failed',
117+
signal: 'SIGTERM',
118+
errno: 'EPERM',
119+
} satisfies ConfirmedProcessStop,
120+
says: 'Dev server pid 987 is still running and refused SIGTERM (EPERM)',
121+
details: { reason: 'signal-failed', signal: 'SIGTERM', errno: 'EPERM', pid: SPAWNED_METRO_PID },
122+
},
123+
{
124+
// SIGTERM is accepted, then refused on the escalation: the verdict carries the later signal.
125+
name: 'only the escalation was refused',
126+
stop: {
127+
status: 'retained',
128+
reason: 'signal-failed',
129+
signal: 'SIGKILL',
130+
errno: 'EPERM',
131+
} satisfies ConfirmedProcessStop,
132+
says: 'Dev server pid 987 is still running and refused SIGKILL (EPERM)',
133+
details: { reason: 'signal-failed', signal: 'SIGKILL', errno: 'EPERM', pid: SPAWNED_METRO_PID },
134+
},
135+
{
136+
// The host would not say when the child started, so nothing proves the pid is still ours: the
137+
// stop retains it instead of signaling whatever process has inherited the pid by now.
138+
name: 'the cleanup could not establish the identity',
139+
stop: {
140+
status: 'retained',
141+
reason: 'identity-unverified',
142+
} satisfies ConfirmedProcessStop,
143+
says: 'could not be confirmed as the process this run started',
144+
details: {
145+
reason: 'identity-unverified',
146+
signal: undefined,
147+
errno: undefined,
148+
pid: SPAWNED_METRO_PID,
149+
},
150+
},
151+
{
152+
name: 'the process outlived both budgets',
153+
stop: {
154+
status: 'retained',
155+
reason: 'exit-timeout',
156+
signal: 'SIGKILL',
157+
} satisfies ConfirmedProcessStop,
158+
says: 'Dev server pid 987 is still running',
159+
details: {
160+
reason: 'exit-timeout',
161+
signal: 'SIGKILL',
162+
errno: undefined,
163+
pid: SPAWNED_METRO_PID,
164+
},
165+
},
166+
])(
167+
'prepareMetroRuntime reports a dev server to reap when $name',
168+
async ({ stop, says, details }) => {
169+
const projectRoot = createMetroProject('outcome');
170+
vi.mocked(runCmdDetached).mockReturnValue(SPAWNED_METRO_PID);
171+
vi.mocked(readProcessStartTime).mockReturnValue(SPAWNED_METRO_START);
172+
vi.mocked(stopProcessAndConfirmExit).mockResolvedValue(stop);
161173

162174
try {
163-
await runMetroPrepareThroughTimeout(projectRoot);
164-
assert.deepEqual(kill.signals, [
165-
[987, 'SIGTERM'],
166-
[987, 'SIGKILL'],
175+
const failure = await runMetroPrepareThroughTimeout(projectRoot);
176+
if (says) assert.ok(failure.message.includes(says), failure.message);
177+
else assert.doesNotMatch(failure.message, /still running/);
178+
assert.deepEqual(cleanupDetails(failure), details);
179+
assert.deepEqual(vi.mocked(stopProcessAndConfirmExit).mock.calls, [
180+
[
181+
{ pid: SPAWNED_METRO_PID, identity: { startTime: SPAWNED_METRO_START } },
182+
METRO_STOP_BUDGET,
183+
],
167184
]);
168-
assert.deepEqual(
169-
vi.mocked(waitForProcessExit).mock.calls,
170-
[[987, 1_000]],
171-
`${code} on SIGKILL means the process is already gone; no second exit wait`,
172-
);
173185
} finally {
174186
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
175187
}
176-
}
177-
});
188+
},
189+
);
178190

179-
test('prepareMetroRuntime reports the readiness timeout when the escalated SIGKILL is refused with EACCES', async () => {
180-
const projectRoot = createMetroProject('kill-eacces');
181-
vi.mocked(runCmdDetached).mockReturnValue(987);
182-
vi.mocked(waitForProcessExit).mockResolvedValue(false);
183-
const kill = spyOnKill((signal) => {
184-
if (signal === 'SIGKILL') throw killError('EACCES');
185-
return true;
186-
});
187-
188-
try {
189-
await runMetroPrepareThroughTimeout(projectRoot);
190-
assert.deepEqual(kill.signals, [
191-
[987, 'SIGTERM'],
192-
[987, 'SIGKILL'],
193-
]);
194-
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [[987, 1_000]]);
195-
} finally {
196-
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
197-
}
198-
});
199-
200-
test('prepareMetroRuntime reports the readiness timeout when SIGTERM is refused with EACCES', async () => {
201-
const projectRoot = createMetroProject('term-eacces');
202-
vi.mocked(runCmdDetached).mockReturnValue(987);
203-
const kill = spyOnKill(() => {
204-
throw killError('EACCES');
205-
});
191+
// Cleanup stays best effort: an unclassifiable host fault is the cause, never a replacement for the
192+
// readiness failure and its log path, which is what the user acts on.
193+
test('prepareMetroRuntime keeps the readiness failure when cleanup faults', async () => {
194+
const projectRoot = createMetroProject('host-fault');
195+
const fault = new TypeError('kill refused: bad signal');
196+
vi.mocked(runCmdDetached).mockReturnValue(SPAWNED_METRO_PID);
197+
vi.mocked(stopProcessAndConfirmExit).mockRejectedValue(fault);
206198

207199
try {
208-
await runMetroPrepareThroughTimeout(projectRoot);
209-
assert.deepEqual(kill.signals, [[987, 'SIGTERM']]);
210-
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 0);
200+
const failure = await runMetroPrepareThroughTimeout(projectRoot);
201+
assert.equal(failure.cause, fault);
202+
assert.deepEqual(cleanupDetails(failure), NO_CLEANUP);
211203
} finally {
212204
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
213205
}

0 commit comments

Comments
 (0)