Skip to content

Commit 2819be4

Browse files
thymikeeclaude
andauthored
feat(host): capture HostEnvironment once at entry points (#3763)
* feat(host): capture HostEnvironment once at entry points Add HostEnvironment to the kernel and captureHostEnvironment to host-kit. The CLI, the daemon executable and the client factory capture it once; startDaemonRuntime requires it and the request scope exposes it. Host-kit, kernel and daemon-contracts no longer read the process environment or working directory. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): resolve relative state dirs against the captured working directory Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): give platform code the command host instead of process reads Platform packages may not read process; they take the environment and working directory of the enclosing command host. Unit tests enter the live process environment as their host. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): answer review of the host environment foundation Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): keep the test host setup out of mutation scope and finish CLI env plumbing Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): bind the test command host per suite, not globally The global setup made every test related to every mutated source. Suites that reach host-reading code through neither a daemon request nor the CLI bind a host with bindTestCommandHost(). Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * chore(deps): declare test-kit in the HarmonyOS and Linux platform packages Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): bind the test command host in the stale-provider admission scenarios Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): resolve every client read from the client's host createAgentDeviceClient's default transport, the daemon launch and the CLI run's transport read the host the client was given, not the process. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): resolve the daemon policy path against the host working directory Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * style: format the daemon policy reuse test Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: merge the duplicate test-kit import in the handler chain routing test Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): start a launched daemon in the launching host's working directory Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: keep the registration-owner test under its size ratchet Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: merge the duplicate test-kit import in the stale provider admission scenarios Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(daemon): read configuration from the request host instead of the ambient scope Handlers, claim writers and lease admission take the host (or its env) from the request execution scope, runtime-owned timers take it at construction. commandHostEnvironment() stays for command execution until the platform and root packages convert. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(daemon): drop the unused host from install-from-source and tighten test envs Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(cli): resolve one transport per run and one host per MCP tool call; default the lease provider cwd to the bound host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: pin the one-transport CLI run and one-host MCP call; document the bound host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: keep the failure that explains a missed materialization in the transport test Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(daemon): read the host cwd where the deploy handlers use it, leaving their shared prologue untouched Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: give the iOS recording scenario's daemon host the PATH and Swift cache its process already had Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: fail the transport test on an unexpected exit or throw and always remove its workspace Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: keep the scenario harness's state dir and transport out of reach of its env override Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(daemon): abandon a transient device claim under the same env that cleared it Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): read host settings from HostEnvironment in root src and remaining packages (#3775) * refactor(host): thread the client host through remote artifact preparation and materialization Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): pass the composition's env to the platform runtime, diagnostics, toolchain and deployment hosts Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): refuse a relative provider app path that names no working directory Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): require the host's env and cwd where the CLI resolves options, binding and auth Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): keep the upload client suite under its size ratchet Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): pass the run's host to CLI command handlers Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): bind host-taking commands once in a shared helper Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * docs(changelog): resolveHubAppReference needs cwd for a relative app path Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): give the new handler suites a host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]> * test: build the scenario gateway on the daemon host's env and pin the host claims directory on a failed release Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test: say which package still reads PATH from the process in the recording scenario Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(platforms): read host settings from HostEnvironment in platform and capture packages (#3777) * refactor(capture-kit): read swift cache, app-log and PNG worker settings from the command host The PNG worker starts with an empty environment and reports unavailability through diagnostics instead of a process warning. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(provision-kit): read proxy settings from the command host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(react-native): read dev-server settings from the command host The detached companion process starts with an explicit env and cwd, and its process entry captures its host from its own spawn environment. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): run the dev-server helpers inside the client's and the SDK's host The helpers moved from process reads to the command host, so the released agent-device/metro functions and the client bind one at their boundary. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(platform-apple): give detached runner and bridge children an explicit env and cwd Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(platform-apple): read runner settings from the command host The runner reaches the host through its port. The container bundle ids were fixed at import time from the process environment; they are now resolved from the host a caller passes in. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): run the daemon clean script's runner lease cleanup inside its own host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(host): hand leaf modules their environment instead of importing the command host The eager-closure budgets forbid the host-kit command import in the install source download, the app-log file policy and the Maestro HTTP helper, so their callers pass the environment they already hold. Client tests that change PATH give the client a host instead. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): bind the command host in the install-artifact suites Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(host): answer review of the platform host environment change Redaction patterns come from the command host, the maestro child reads its own environment without a working-directory lookup, local ~ install sources expand against the host environment, and the runner launch resolves its host inside the try that closes its log descriptor. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(react-native): take the host explicitly instead of reading the command host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(platforms): pass the host explicitly where a platform package reads configuration Android install artifacts read the environment from the Android adb host port, Apple install artifacts take it as an option from the root deployment executor, and the Apple runner names its host port member hostEnvironment. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(daemon): hand the app-log marker the request host's environment Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(capture-kit): report an unavailable PNG worker in the first diagnostics scope that sees it A startup pre-warm runs outside any scope, where the event is dropped; it no longer latches the one-time report. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): share the test command host binding through test-kit and test the runner's bound host behaviorally test-kit no longer depends on capture-kit: its app-log live-handle alias is gone (callers use the capture-kit constructor) and its keyboard fixture builds its own snapshot state. capture-kit's tests take the helper from test-kit. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(capture-kit): expose the app-log live handle adapter through its own entry Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(test-kit): build the test app-log handle without importing capture-kit Replaces the capture-kit subpath entry, which grew the declared export surface. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(capture-kit): take the host explicitly for Swift cache and recording tooling capture-kit no longer reads the command host, so its suites need no bound host and its local test-host copy is gone; the root recording seams supply the host. test-kit keeps depending on capture-kit again, and capture-kit does not depend on test-kit. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(capture-kit): report a worker that dies under a request in that request Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(platform-android): take the install environment from the caller The Android adb host port's environment is bound at module load, so a host whose environment differs from the process's got the process's proxy settings on a network install. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(platform-apple): pin the detached snapshot bridge's starting directory Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(capture-kit): fail when the pre-warm starts no worker to kill Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): keep the provider scenario host's Swift cache directory for scenarios that set it on the process Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * fix(capture-kit): key the cached Swift helper paths on the host they were built for The video validator is cached per Swift cache root and the overlay scripts per working directory, so a second host does not reuse the first host's paths. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): give the Android recording scenarios their host env through the harness Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): scenarios name their own host env; the harness no longer forwards the process's Swift cache Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * test(host): drop the iOS recording scenario's process-env block now that capture-kit takes the host Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]> * test: pass the host to the iOS e2e live runner's request Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(react-native): drop the redundant outer catch around the scoped Metro session read; changelog the PNG worker change Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(capture-kit): report an unavailable PNG worker in every scope that takes the fallback; the daemon pre-warms it inside a daemon diagnostics scope Co-Authored-By: Claude Sonnet 5.5 <[email protected]> * refactor(capture-kit): report each PNG worker transition to unavailable once, through a daemon-registered sink with a typed reason Co-Authored-By: Claude Sonnet 5.5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]>
1 parent f2e60e9 commit 2819be4

479 files changed

Lines changed: 5324 additions & 1820 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- The PNG worker no longer calls `process.emitWarning` when it is unavailable, and it starts with an empty environment (`env: {}`). The daemon registers a sink when it pre-warms the worker, so every transition to unavailable (spawn failure, missing entry, load error, exit) leaves exactly one `png_worker_unavailable` event, with a typed `reason` (`entry-not-found`, `spawn-failed`, `worker-error`, `worker-exited`) and its `detail`, in `daemon.log`, with or without `--debug`. Requests then continue on the in-process fallback without repeating the event.
6+
- Behavior change: `resolveHubAppReference`, shipped through `agent-device/plugins/webdriver`, now needs `cwd` to resolve a relative app path. Without it the call fails with `INVALID_ARGS` and `details.reason: provider_app_cwd_missing`; it used to resolve against the process's working directory. Absolute paths, URLs and provider references are unaffected. The daemon fills it from the client's working directory (or its host's) for every provider lease request, so `connect` and `lease_allocate` are unchanged.
57
- The `daemon-not-running` hint now always names `--state-dir <dir>`, and a daemon force-retired for outlasting its drain is reported as `Replaced unreachable daemon` instead of `Replaced idle daemon`. `daemon-drain-timeout` and the post-drain force retire are documented in the client API and `help`.
68
- Fix `ensureDaemon()`, the CLI and MCP killing a daemon they had just asked to leave. After the daemon answers the quiesce request with `draining`, the client now waits up to 60 s for it to exit by itself and clean up its registration, so plugin disposal and lease finalization finish (on Windows a signal ends the process outright, and on POSIX a drain longer than 3 s was killed). A daemon still running at the deadline that fails its liveness probes is force-retired; one that still answers is left running and the call fails with `details.reason: 'daemon-drain-timeout'`, with a hint naming `agent-device daemon stop --state-dir <path>`.
79
- `@agent-device/testmu` is now a version 2 provider plugin. `import testmu from '@agent-device/testmu'` gives a factory, `testmu({ credentials: { username, accessKey } })`, that reads those credentials instead of `LT_USERNAME` and `LT_ACCESS_KEY`; without options it reads the variables as before. The package still declares the version 1 plugin entry, so `agent-device plugins add @agent-device/testmu` keeps working on hosts that predate the version 2 contract.

‎packages/capture-kit/src/capture-admission/app-log-files.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export type AppLogRotationConfig = Readonly<{
1212
}>;
1313

1414
/** Shared lower-level file policy for daemon markers and runtime output sinks. */
15-
export function ensureAppLogPath(outPath: string, env: NodeJS.ProcessEnv = process.env): void {
15+
export function ensureAppLogPath(outPath: string, env: NodeJS.ProcessEnv): void {
1616
const directory = path.dirname(outPath);
1717
if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true });
1818
assertAppLogFileIsNotSymbolicLink(outPath);
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { captureHostEnvironment } from '@agent-device/host-kit/process';
2+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
3+
4+
/**
5+
* The host a capture-kit test hands to code that takes one explicitly: a snapshot of the process
6+
* as it is when called, so `vi.stubEnv` made earlier in the test reaches it. Test-kit depends on
7+
* capture-kit, so capture-kit keeps this local.
8+
*/
9+
export function createTestHost(): HostEnvironment {
10+
return captureHostEnvironment(process);
11+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { EventEmitter } from 'node:events';
2+
import { expect, test, vi } from 'vitest';
3+
import { PNG } from './png.ts';
4+
5+
test('a worker whose entry is missing is reported once and later registrations hear it', async () => {
6+
vi.resetModules();
7+
vi.doMock('./internal-entry.ts', () => ({ resolveInternalEntryModulePath: () => null }));
8+
const { decodePngAsync, prewarmPngWorker } = await import('./png-worker-client.ts');
9+
const png = PNG.sync.write(new PNG({ width: 1, height: 1 }));
10+
const first = vi.fn();
11+
const second = vi.fn();
12+
13+
prewarmPngWorker(first);
14+
const decoded = await decodePngAsync(png, 'fallback');
15+
prewarmPngWorker(second);
16+
17+
expect(decoded.width).toBe(1);
18+
expect(first.mock.calls).toEqual([[{ kind: 'entry-not-found' }]]);
19+
expect(second.mock.calls).toEqual([[{ kind: 'entry-not-found' }]]);
20+
vi.doUnmock('./internal-entry.ts');
21+
});
22+
23+
test('a worker that dies after it started is reported once, and its pending job still completes', async () => {
24+
vi.resetModules();
25+
class FakeWorker extends EventEmitter {
26+
static last: FakeWorker | undefined;
27+
constructor() {
28+
super();
29+
FakeWorker.last = this;
30+
}
31+
postMessage(): void {}
32+
ref(): void {}
33+
unref(): void {}
34+
terminate(): Promise<number> {
35+
return Promise.resolve(0);
36+
}
37+
}
38+
vi.doMock('node:worker_threads', async (importOriginal) => ({
39+
...(await importOriginal<typeof import('node:worker_threads')>()),
40+
Worker: FakeWorker,
41+
}));
42+
const { decodePngAsync, prewarmPngWorker } = await import('./png-worker-client.ts');
43+
const png = PNG.sync.write(new PNG({ width: 1, height: 1 }));
44+
const unavailable = vi.fn();
45+
prewarmPngWorker(unavailable);
46+
expect(unavailable).not.toHaveBeenCalled();
47+
48+
const decoded = decodePngAsync(png, 'under-request');
49+
const worker = FakeWorker.last;
50+
if (!worker) throw new Error('the pre-warm did not start a worker');
51+
worker.emit('error', new Error('worker crashed'));
52+
worker.emit('exit', 1);
53+
54+
expect((await decoded).width).toBe(1);
55+
expect(unavailable.mock.calls).toEqual([[{ kind: 'worker-error', detail: 'worker crashed' }]]);
56+
vi.doUnmock('node:worker_threads');
57+
});

‎packages/capture-kit/src/png-worker-client.ts‎

Lines changed: 39 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { Worker } from 'node:worker_threads';
2-
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
32
import { AppError, toAppErrorCode } from '@agent-device/kernel/errors';
43
import type { Rect } from '@agent-device/kernel/snapshot';
54
import { resolveInternalEntryModulePath } from './internal-entry.ts';
@@ -29,6 +28,12 @@ import {
2928

3029
const PNG_WORKER_ENTRYPOINT = 'png-worker';
3130

31+
/** Why the worker left service for good; `detail` carries the underlying error text. */
32+
export type PngWorkerUnavailableReason = {
33+
kind: 'entry-not-found' | 'spawn-failed' | 'worker-error' | 'worker-exited';
34+
detail?: string;
35+
};
36+
3237
/** Worker-infrastructure failure: the generic runner falls back to the sync path. */
3338
class PngWorkerUnavailableError extends Error {}
3439

@@ -38,22 +43,16 @@ type PendingJob = {
3843
};
3944

4045
let worker: Worker | null = null;
41-
let workerUnavailable = false;
42-
let warnedWorkerUnavailable = false;
46+
let unavailableReason: PngWorkerUnavailableReason | undefined;
47+
let reportUnavailable: ((reason: PngWorkerUnavailableReason) => void) | undefined;
4348
let nextJobId = 0;
4449
const pendingJobs = new Map<number, PendingJob>();
4550

46-
/** Permanently degrades to the sync path and reports the reason once. */
47-
function markWorkerUnavailable(reason: string): void {
48-
workerUnavailable = true;
49-
if (warnedWorkerUnavailable) return;
50-
warnedWorkerUnavailable = true;
51-
// Worker failures can surface outside a diagnostics scope (e.g. daemon
52-
// startup pre-warm), so pair the scoped diagnostic with a process warning.
53-
emitDiagnostic({ level: 'warn', phase: 'png_worker_unavailable', data: { reason } });
54-
process.emitWarning(
55-
`PNG worker unavailable, falling back to in-process PNG processing: ${reason}`,
56-
);
51+
/** Permanently degrades to the sync path; the daemon's sink hears each transition once. */
52+
function markWorkerUnavailable(reason: PngWorkerUnavailableReason): void {
53+
if (unavailableReason) return;
54+
unavailableReason = reason;
55+
reportUnavailable?.(reason);
5756
}
5857

5958
function handleWorkerMessage(message: PngWorkerResponse): void {
@@ -74,14 +73,14 @@ function handleWorkerMessage(message: PngWorkerResponse): void {
7473
}
7574
}
7675

77-
function handleWorkerFailure(failed: Worker, error: Error): void {
76+
function handleWorkerFailure(failed: Worker, reason: PngWorkerUnavailableReason): void {
7877
if (worker !== failed) return;
7978
// Keep the failure handling conservative: after any worker-level error the
8079
// daemon permanently falls back to the in-process synchronous path.
81-
markWorkerUnavailable(error.message);
80+
markWorkerUnavailable(reason);
8281
worker = null;
8382
void failed.terminate().catch(() => {});
84-
rejectPendingJobs(new PngWorkerUnavailableError(`PNG worker failed: ${error.message}`));
83+
rejectPendingJobs(new PngWorkerUnavailableError(`PNG worker failed: ${reason.kind}`));
8584
}
8685

8786
function rejectPendingJobs(error: Error): void {
@@ -102,31 +101,34 @@ function updateWorkerRef(): void {
102101
}
103102

104103
function obtainWorker(): Worker | null {
105-
if (workerUnavailable) return null;
104+
if (unavailableReason) return null;
106105
if (worker) return worker;
107106
const modulePath = resolveInternalEntryModulePath(import.meta.url, PNG_WORKER_ENTRYPOINT);
108107
if (!modulePath) {
109-
markWorkerUnavailable('worker entry module not found next to the current module');
108+
markWorkerUnavailable({ kind: 'entry-not-found' });
110109
return null;
111110
}
112111
try {
112+
// The worker decodes and encodes bytes it is sent; it needs none of the host's environment.
113113
const created = new Worker(modulePath, {
114+
env: {},
114115
execArgv: modulePath.endsWith('.ts') ? ['--experimental-strip-types'] : [],
115116
});
116117
created.on('message', handleWorkerMessage);
117118
created.on('error', (error) => {
118-
handleWorkerFailure(created, error);
119+
handleWorkerFailure(created, { kind: 'worker-error', detail: error.message });
119120
});
120121
created.on('exit', (code) => {
121-
handleWorkerFailure(created, new Error(`PNG worker exited with code ${code}`));
122+
handleWorkerFailure(created, { kind: 'worker-exited', detail: `exit code ${code}` });
122123
});
123124
created.unref();
124125
worker = created;
125126
return created;
126127
} catch (error) {
127-
markWorkerUnavailable(
128-
`failed to spawn worker: ${error instanceof Error ? error.message : String(error)}`,
129-
);
128+
markWorkerUnavailable({
129+
kind: 'spawn-failed',
130+
detail: error instanceof Error ? error.message : String(error),
131+
});
130132
return null;
131133
}
132134
}
@@ -176,14 +178,23 @@ async function runPngJob<Kind extends PngWorkerJobKind>(
176178
try {
177179
return await runWorkerJob(job);
178180
} catch (error) {
179-
if (error instanceof PngWorkerUnavailableError) return await runSync();
181+
if (error instanceof PngWorkerUnavailableError) {
182+
return await runSync();
183+
}
180184
throw error;
181185
}
182186
}
183187

184-
/** Daemon startup hook: spawns the worker before the first screenshot job. */
185-
export function prewarmPngWorker(): void {
186-
obtainWorker();
188+
/**
189+
* Daemon startup hook: spawns the worker before the first screenshot job and registers the daemon's
190+
* sink, which hears every later transition to unavailable once, inside or outside a request.
191+
*/
192+
export function prewarmPngWorker(
193+
onUnavailable: (reason: PngWorkerUnavailableReason) => void,
194+
): void {
195+
reportUnavailable = onUnavailable;
196+
if (unavailableReason) onUnavailable(unavailableReason);
197+
else obtainWorker();
187198
}
188199

189200
/** Stops the worker thread (used by tests and shutdown); later calls respawn it. */
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { expect, test, vi } from 'vitest';
4+
import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts';
5+
6+
vi.mock('@agent-device/host-kit/command', async () => {
7+
const fs = await import('node:fs');
8+
return {
9+
runCmd: vi.fn(async (_cmd: string, args: string[]) => {
10+
fs.writeFileSync(args[args.indexOf('--output') + 1]!, 'processed');
11+
return { stdout: '', stderr: '', exitCode: 0 };
12+
}),
13+
};
14+
});
15+
vi.mock('../video.ts', () => ({ waitForPlayableVideo: vi.fn(async () => {}) }));
16+
vi.mock('../swift-cache.ts', () => ({
17+
buildSwiftToolEnv: () => ({}),
18+
compileSwiftSourceFile: vi.fn(async () => '/bin/true'),
19+
resolveRecordingScriptPath: vi.fn(
20+
(name: string, _projectRoot: string, cwd: string) => `${cwd}/${name}`,
21+
),
22+
}));
23+
24+
import { overlayRecordingTouches, startRecordingOverlayBudget } from '../overlay.ts';
25+
import { compileSwiftSourceFile } from '../swift-cache.ts';
26+
27+
test('a helper script path is resolved per host working directory, not once per process', async () => {
28+
const root = mkdtempForTestSync('agent-device-overlay-script-paths-');
29+
const videoPath = path.join(root, 'recording.mp4');
30+
const telemetryPath = path.join(root, 'recording.gesture-telemetry.json');
31+
fs.writeFileSync(telemetryPath, '{"events":[]}');
32+
const overlay = async (cwd: string) => {
33+
fs.writeFileSync(videoPath, 'original');
34+
await overlayRecordingTouches({
35+
host: { env: {}, cwd },
36+
videoPath,
37+
telemetryPath,
38+
deadline: startRecordingOverlayBudget(),
39+
});
40+
};
41+
42+
await overlay('/cwd/one');
43+
await overlay('/cwd/two');
44+
await overlay('/cwd/one');
45+
46+
expect(vi.mocked(compileSwiftSourceFile).mock.calls.map(([params]) => params.sourcePath)).toEqual(
47+
[
48+
'/cwd/one/recording-overlay.swift',
49+
'/cwd/two/recording-overlay.swift',
50+
'/cwd/one/recording-overlay.swift',
51+
],
52+
);
53+
});

0 commit comments

Comments
 (0)