Skip to content

Commit 740d99a

Browse files
committed
fix: make the metro-sessions file the single reload hint store
Review follow-up (PR #1199): - open's --metro-host/--metro-port/--bundle-url now also record the session's dev-server binding in the metro-sessions file (the one local store metro reload resolves against), so a later plain reload actually reuses what open set. The daemon runtime-hints write stays for device-native dev-server prefs. - The binding now carries bundleUrl (prepare persists the local-flow bundle URL; bridge runtimes are excluded). - clearMetroSessionHints is wired: session close drops the binding (teardown intent — even when the daemon call fails), and a hintless open that creates the session clears a leftover same-name binding. The open result carries sessionReused so the client can tell fresh from reused sessions. Regression test pins prepare -> close -> flagless reload resolving to the default, never the stale port. - Package-manager detection recognizes bun.lock (text lockfile, default since Bun 1.2) and bounds the lockfile walk-up at the nearest .git entry. - Comment audit per maintainer directive: multi-line acceptability arguments trimmed to one-line constraint statements; the store's lifecycle is documented once on MetroSessionHints.
1 parent 94ada31 commit 740d99a

14 files changed

Lines changed: 379 additions & 102 deletions

File tree

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

Lines changed: 110 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import os from 'node:os';
1010
import path from 'node:path';
1111
import { prepareMetroRuntime, reloadMetro, resolveMetroReloadUrl } from '../metro/client-metro.ts';
1212
import { createAgentDeviceClient } from '../client/client.ts';
13+
import { readMetroSessionHints } from '../metro/metro-session-hints.ts';
14+
import { resolveDaemonPaths } from '../daemon/config.ts';
1315
import { AppError } from '../kernel/errors.ts';
1416
import { isProcessAlive, waitForProcessExit } from '../utils/host-process.ts';
1517

@@ -421,6 +423,88 @@ test('prepareMetroRuntime install failure hints at --no-install-deps and the det
421423
rmSync(tempRoot, { recursive: true, force: true });
422424
});
423425

426+
test('prepareMetroRuntime detects bun from the text bun.lock lockfile', async () => {
427+
const tempRoot = path.join(os.tmpdir(), `agent-device-pm-bun-${randomUUID()}`);
428+
const projectRoot = path.join(tempRoot, 'project');
429+
const binDir = path.join(tempRoot, 'bin');
430+
431+
mkdirSync(projectRoot, { recursive: true });
432+
mkdirSync(binDir, { recursive: true });
433+
writeFileSync(path.join(projectRoot, 'bun.lock'), '');
434+
writeFileSync(
435+
path.join(projectRoot, 'package.json'),
436+
JSON.stringify({
437+
name: 'pm-bun-test',
438+
private: true,
439+
dependencies: { 'react-native': '0.0.0-test' },
440+
}),
441+
);
442+
writeFailingPackageManager(binDir, 'bun');
443+
444+
await assert.rejects(
445+
() =>
446+
prepareMetroRuntime({
447+
projectRoot,
448+
publicBaseUrl: 'http://127.0.0.1:9',
449+
installDependenciesIfNeeded: true,
450+
env: {
451+
...process.env,
452+
PATH: `${binDir}:${process.env.PATH || ''}`,
453+
},
454+
}),
455+
(error) => {
456+
assert.ok(error instanceof AppError);
457+
assert.equal(error.details?.packageManager, 'bun');
458+
return true;
459+
},
460+
);
461+
462+
rmSync(tempRoot, { recursive: true, force: true });
463+
});
464+
465+
test('prepareMetroRuntime lockfile walk-up stops at the repo root instead of adopting an outside lockfile', async () => {
466+
const tempRoot = path.join(os.tmpdir(), `agent-device-pm-bound-${randomUUID()}`);
467+
const repoRoot = path.join(tempRoot, 'repo');
468+
const projectRoot = path.join(repoRoot, 'example');
469+
const binDir = path.join(tempRoot, 'bin');
470+
471+
mkdirSync(projectRoot, { recursive: true });
472+
mkdirSync(path.join(repoRoot, '.git'), { recursive: true });
473+
mkdirSync(binDir, { recursive: true });
474+
// A lockfile ABOVE the repo root must not be adopted; detection falls back to npm.
475+
writeFileSync(path.join(tempRoot, 'yarn.lock'), '');
476+
writeFileSync(
477+
path.join(projectRoot, 'package.json'),
478+
JSON.stringify({
479+
name: 'pm-bound-test',
480+
private: true,
481+
dependencies: { 'react-native': '0.0.0-test' },
482+
}),
483+
);
484+
writeFakePackageManager(binDir, 'yarn', path.join(tempRoot, 'yarn-args.json'));
485+
writeFailingPackageManager(binDir, 'npm');
486+
487+
await assert.rejects(
488+
() =>
489+
prepareMetroRuntime({
490+
projectRoot,
491+
publicBaseUrl: 'http://127.0.0.1:9',
492+
installDependenciesIfNeeded: true,
493+
env: {
494+
...process.env,
495+
PATH: `${binDir}:${process.env.PATH || ''}`,
496+
},
497+
}),
498+
(error) => {
499+
assert.ok(error instanceof AppError);
500+
assert.equal(error.details?.packageManager, 'npm');
501+
return true;
502+
},
503+
);
504+
505+
rmSync(tempRoot, { recursive: true, force: true });
506+
});
507+
424508
test('prepareMetroRuntime rejects incomplete proxy configuration', async () => {
425509
await assert.rejects(
426510
() =>
@@ -603,15 +687,15 @@ test('metro reload targets the dev server bound by metro prepare in the same ses
603687
const client = createAgentDeviceClient(
604688
{ session: 'metro-session-hints', stateDir, cwd: projectRoot },
605689
{
606-
transport: async () => {
690+
// Only session close may reach the daemon; metro prepare/reload must stay local.
691+
transport: async (req) => {
692+
if (req.command === 'close') return { ok: true, data: {} };
607693
throw new Error('metro prepare/reload must stay local and never call the daemon');
608694
},
609695
},
610696
);
611697

612-
// MetroPrepareOptions (the public client surface) doesn't expose `env`, so the fake `npx`
613-
// has to be reachable through the real PATH for the duration of this test, matching the
614-
// temporary-PATH pattern used elsewhere for exec-dependent tests.
698+
// The public MetroPrepareOptions doesn't expose env, so the fake npx must be on the real PATH.
615699
const previousPath = process.env.PATH;
616700
process.env.PATH = `${binDir}${path.delimiter}${previousPath ?? ''}`;
617701

@@ -626,11 +710,33 @@ test('metro reload targets the dev server bound by metro prepare in the same ses
626710
});
627711
pid = prepared.pid;
628712

713+
const storedHints = readMetroSessionHints({
714+
stateDir: resolveDaemonPaths(stateDir).baseDir,
715+
session: 'metro-session-hints',
716+
});
717+
assert.deepEqual(storedHints, {
718+
metroHost: '127.0.0.1',
719+
metroPort,
720+
bundleUrl: `http://127.0.0.1:${metroPort}/index.bundle?platform=ios&dev=true&minify=false`,
721+
});
722+
629723
// No explicit --metro-host/--metro-port/--bundle-url: reload must resolve against the
630724
// dev server this session's `metro prepare` bound, not the Metro default (localhost:8081).
631725
const hintedReload = await client.metro.reload();
632726
assert.equal(hintedReload.reloadUrl, `http://127.0.0.1:${metroPort}/reload`);
633727
assert.equal(hintedReload.body, 'RELOADED');
728+
729+
// Regression (prepare -> close -> same-name session): close clears the binding, so a later
730+
// flagless reload resolves to the Metro default instead of silently hitting the stale port.
731+
await client.sessions.close();
732+
assert.equal(
733+
readMetroSessionHints({
734+
stateDir: resolveDaemonPaths(stateDir).baseDir,
735+
session: 'metro-session-hints',
736+
}),
737+
undefined,
738+
);
739+
assert.equal(resolveMetroReloadUrl({}), 'http://localhost:8081/reload');
634740
} finally {
635741
process.env.PATH = previousPath;
636742
await stopProcess(pid);

‎src/__tests__/client.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
3+
import { mkdtempSync } from 'node:fs';
4+
import os from 'node:os';
5+
import path from 'node:path';
36
import {
47
createAgentDeviceClient,
58
type AgentDeviceClient,
@@ -14,6 +17,9 @@ import type { CommandResult } from '../core/command-descriptor/command-result.ts
1417
import type { DaemonRequest, DaemonResponse, DaemonResponseData } from '../kernel/contracts.ts';
1518
import { AppError } from '../kernel/errors.ts';
1619

20+
// Isolated so open/close metro-session-hint file writes never touch the real state dir.
21+
const TEST_STATE_DIR = mkdtempSync(path.join(os.tmpdir(), 'agent-device-client-test-'));
22+
1723
type Equal<A, B> =
1824
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
1925

@@ -66,6 +72,7 @@ function createTransport(
6672
const calls: Array<Omit<DaemonRequest, 'token'>> = [];
6773
const config: AgentDeviceClientConfig = {
6874
session: 'qa',
75+
stateDir: TEST_STATE_DIR,
6976
cwd: '/tmp/agent-device',
7077
debug: true,
7178
daemonBaseUrl: 'http://daemon.example.test',

‎src/__tests__/metro-session-hints.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@ test('writeMetroSessionHints and readMetroSessionHints round-trip per session',
3131
writeMetroSessionHints({
3232
stateDir,
3333
session: 'proj-a',
34-
hints: { metroHost: '127.0.0.1', metroPort: 8082 },
34+
hints: {
35+
metroHost: '127.0.0.1',
36+
metroPort: 8082,
37+
bundleUrl: 'http://127.0.0.1:8082/.expo/.virtual-metro-entry.bundle?platform=ios',
38+
},
3539
});
3640
writeMetroSessionHints({
3741
stateDir,
@@ -42,6 +46,7 @@ test('writeMetroSessionHints and readMetroSessionHints round-trip per session',
4246
assert.deepEqual(readMetroSessionHints({ stateDir, session: 'proj-a' }), {
4347
metroHost: '127.0.0.1',
4448
metroPort: 8082,
49+
bundleUrl: 'http://127.0.0.1:8082/.expo/.virtual-metro-entry.bundle?platform=ios',
4550
});
4651
assert.deepEqual(readMetroSessionHints({ stateDir, session: 'proj-b' }), {
4752
metroHost: '127.0.0.1',

‎src/cli/parser/__tests__/cli-help-command-usage.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,8 +327,9 @@ test('metro command usage documents session-hint reload priority, expo bundle ki
327327
if (help === null) throw new Error('Expected metro help text');
328328
assert.match(help, /resolves against the dev server/);
329329
assert.match(help, /never silently reload[s]? a different project/);
330+
assert.match(help, /cleared when the session closes/);
330331
assert.match(help, /\.expo\/\.virtual-metro-entry\.bundle/);
331-
assert.match(help, /yarn\.lock\/pnpm-lock\.yaml\/bun\.lockb\/package-lock\.json/);
332+
assert.match(help, /yarn\.lock\/pnpm-lock\.yaml\/bun\.lock\/bun\.lockb\/package-lock\.json/);
332333
assert.match(help, /--no-install-deps/);
333334
});
334335

@@ -340,6 +341,8 @@ test('open command usage documents metro session-hint setter flags', async () =>
340341
assert.match(help, /--bundle-url <url>/);
341342
assert.match(help, /--launch-url <url>/);
342343
assert.match(help, /before its first reload/);
344+
assert.match(help, /plain metro reload in the same session reuses/);
345+
assert.match(help, /clears any leftover binding/);
343346
});
344347

345348
test('command usage shows no command flags when unsupported', async () => {

‎src/client/client.ts‎

Lines changed: 93 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { sendToDaemon } from '../daemon/client/daemon-client.ts';
22
import { prepareMetroRuntime, reloadMetro } from '../metro/client-metro.ts';
33
import {
4+
clearMetroSessionHints,
45
readMetroSessionHints,
56
writeMetroSessionHints,
67
type MetroSessionHints,
@@ -51,9 +52,14 @@ import type {
5152
Lease,
5253
MaterializationReleaseOptions,
5354
MetroPrepareOptions,
55+
MetroPrepareResult,
5456
} from './client-types.ts';
5557
import type { CommandResult } from '../core/command-descriptor/command-result.ts';
56-
import { isNonDefaultResponseLevel, type ResponseLevel } from '../kernel/contracts.ts';
58+
import {
59+
isNonDefaultResponseLevel,
60+
type ResponseLevel,
61+
type SessionRuntimeHints,
62+
} from '../kernel/contracts.ts';
5763
import { readSerializedSnapshotCaptureAnnotations } from '../snapshot-capture-annotations.ts';
5864
import { readSnapshotDiagnosticsSummary } from '../snapshot-diagnostics.ts';
5965
import type { CommandFlags } from '../core/dispatch-context.ts';
@@ -163,13 +169,18 @@ export function createAgentDeviceClient(
163169
},
164170
close: async (options = {}) => {
165171
const session = resolveRequestSession(options);
166-
const data = await executeCommand<Record<string, unknown>>('close', options);
167-
return {
168-
session,
169-
shutdown: normalizeTargetShutdownResult(data.shutdown),
170-
provider: readObject(data.provider),
171-
identifiers: { session },
172-
};
172+
try {
173+
const data = await executeCommand<Record<string, unknown>>('close', options);
174+
return {
175+
session,
176+
shutdown: normalizeTargetShutdownResult(data.shutdown),
177+
provider: readObject(data.provider),
178+
identifiers: { session },
179+
};
180+
} finally {
181+
// Close is teardown intent: drop the dev-server binding even if the daemon call fails.
182+
clearMetroSessionHintsQuietly(config, options);
183+
}
173184
},
174185
artifacts: async (options = {}) =>
175186
await executeCommand<AgentArtifactsResult>('artifacts', options),
@@ -199,6 +210,12 @@ export function createAgentDeviceClient(
199210
open: async (options: AppOpenOptions) => {
200211
const session = resolveRequestSession(options);
201212
const data = await executeCommand<Record<string, unknown>>('open', options);
213+
recordMetroSessionHintsAfterOpen({
214+
config,
215+
options,
216+
runtime: mergeClientOptions(config, options).runtime,
217+
sessionReused: data.sessionReused === true,
218+
});
202219
const device = normalizeOpenDevice(data);
203220
const appBundleId = readOptionalString(data, 'appBundleId');
204221
const appId = appBundleId;
@@ -283,7 +300,7 @@ export function createAgentDeviceClient(
283300
runtimeFilePath: options.runtimeFilePath,
284301
logPath: options.logPath,
285302
});
286-
persistMetroSessionHints(config, result.statusUrl);
303+
persistMetroSessionHints(config, result);
287304
return result;
288305
},
289306
reload: async (options = {}) =>
@@ -445,23 +462,33 @@ function mergeClientOptions(
445462
return { ...config, ...options };
446463
}
447464

448-
function metroSessionHintsStateDir(config: AgentDeviceClientConfig): string {
449-
return resolveDaemonPaths(config.stateDir ?? process.env.AGENT_DEVICE_STATE_DIR).baseDir;
465+
function metroSessionHintsScope(
466+
config: AgentDeviceClientConfig,
467+
options: InternalRequestOptions = {},
468+
): { stateDir: string; session: string } {
469+
const merged = mergeClientOptions(config, options);
470+
return {
471+
stateDir: resolveDaemonPaths(merged.stateDir ?? process.env.AGENT_DEVICE_STATE_DIR).baseDir,
472+
session: resolveSessionName(merged.session),
473+
};
450474
}
451475

452-
// `metro prepare` and `metro reload` are local-only (they never round-trip through the daemon),
453-
// so session-scoped Metro coordinates can't live in the daemon's session store. Persisting them
454-
// to a small per-session file lets a plain `metro reload --session <s>` find the dev server a
455-
// prior `metro prepare --session <s>` bound, instead of silently defaulting to localhost:8081.
456-
function persistMetroSessionHints(config: AgentDeviceClientConfig, statusUrl: string): void {
476+
// The metro-sessions file is the session's dev-server binding; see MetroSessionHints.
477+
function persistMetroSessionHints(
478+
config: AgentDeviceClientConfig,
479+
result: Pick<MetroPrepareResult, 'statusUrl' | 'bridge' | 'iosRuntime' | 'androidRuntime'>,
480+
): void {
457481
try {
458-
const url = new URL(statusUrl);
482+
const url = new URL(result.statusUrl);
459483
const port = Number.parseInt(url.port, 10);
460484
if (!url.hostname || !Number.isInteger(port)) return;
485+
// Bridge runtimes carry remote bundle URLs; persist local-flow bundle URLs only.
486+
const bundleUrl = result.bridge
487+
? undefined
488+
: (result.iosRuntime.bundleUrl ?? result.androidRuntime.bundleUrl);
461489
writeMetroSessionHints({
462-
stateDir: metroSessionHintsStateDir(config),
463-
session: resolveSessionName(config.session),
464-
hints: { metroHost: url.hostname, metroPort: port },
490+
...metroSessionHintsScope(config),
491+
hints: { metroHost: url.hostname, metroPort: port, bundleUrl },
465492
});
466493
} catch {
467494
// Session-hint persistence is best-effort; reload still works with explicit flags.
@@ -470,15 +497,57 @@ function persistMetroSessionHints(config: AgentDeviceClientConfig, statusUrl: st
470497

471498
function resolveMetroSessionHints(config: AgentDeviceClientConfig): MetroSessionHints | undefined {
472499
try {
473-
return readMetroSessionHints({
474-
stateDir: metroSessionHintsStateDir(config),
475-
session: resolveSessionName(config.session),
476-
});
500+
return readMetroSessionHints(metroSessionHintsScope(config));
477501
} catch {
478502
return undefined;
479503
}
480504
}
481505

506+
function metroHintsFromRuntime(
507+
runtime: SessionRuntimeHints | undefined,
508+
): MetroSessionHints | undefined {
509+
if (!runtime) return undefined;
510+
const { metroHost, metroPort, bundleUrl } = runtime;
511+
if (metroHost === undefined && metroPort === undefined && bundleUrl === undefined) {
512+
return undefined;
513+
}
514+
return { metroHost, metroPort, bundleUrl };
515+
}
516+
517+
// Hint flags rebind the session's dev server; a hintless open that created the session clears
518+
// any leftover binding from a previous same-name session.
519+
function recordMetroSessionHintsAfterOpen(params: {
520+
config: AgentDeviceClientConfig;
521+
options: InternalRequestOptions;
522+
runtime: SessionRuntimeHints | undefined;
523+
sessionReused: boolean;
524+
}): void {
525+
try {
526+
const scope = metroSessionHintsScope(params.config, params.options);
527+
const hints = metroHintsFromRuntime(params.runtime);
528+
if (hints) {
529+
writeMetroSessionHints({ ...scope, hints });
530+
return;
531+
}
532+
if (!params.sessionReused) {
533+
clearMetroSessionHints(scope);
534+
}
535+
} catch {
536+
// Session-hint sync is best-effort; reload still works with explicit flags.
537+
}
538+
}
539+
540+
function clearMetroSessionHintsQuietly(
541+
config: AgentDeviceClientConfig,
542+
options: InternalRequestOptions,
543+
): void {
544+
try {
545+
clearMetroSessionHints(metroSessionHintsScope(config, options));
546+
} catch {
547+
// Session-hint cleanup is best-effort; close must not fail on local file state.
548+
}
549+
}
550+
482551
function normalizeLease(data: Record<string, unknown>): Lease {
483552
const rawLease = data.lease;
484553
if (!isRecord(rawLease)) {

0 commit comments

Comments
 (0)