Skip to content

Commit 595fa48

Browse files
thymikeeclaude
andcommitted
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]>
1 parent 4f6dd3e commit 595fa48

5 files changed

Lines changed: 75 additions & 38 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
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 unavailable reason is reported once as the `png_worker_unavailable` diagnostic, by the first request that reaches the in-process fallback, instead of also printing a process warning at daemon startup.
5+
- The PNG worker no longer calls `process.emitWarning` when it is unavailable, and it starts with an empty environment (`env: {}`). The daemon pre-warms it inside a daemon diagnostics scope, so a worker that cannot start leaves a `png_worker_unavailable` event in `daemon.log`; every request that takes the in-process fallback reports the same event in its own diagnostics.
66
- 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.
77
- 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`.
88
- 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>`.

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

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events';
22
import { expect, test, vi } from 'vitest';
33
import { PNG } from './png.ts';
44

5-
test('an unavailable worker is reported by the first diagnostics scope that reaches the fallback', async () => {
5+
test('every scope that reaches the fallback reports the unavailable worker', async () => {
66
vi.resetModules();
77
vi.doMock('./internal-entry.ts', () => ({ resolveInternalEntryModulePath: () => null }));
88
// Loaded after the reset so the client and the scope share one diagnostics module.
@@ -11,22 +11,21 @@ test('an unavailable worker is reported by the first diagnostics scope that reac
1111
const { decodePngAsync, prewarmPngWorker } = await import('./png-worker-client.ts');
1212
const png = PNG.sync.write(new PNG({ width: 1, height: 1 }));
1313

14-
// The daemon pre-warms outside any request scope, where the report would be dropped.
15-
prewarmPngWorker();
16-
17-
const reported = await withDiagnosticsScope({ command: 'screenshot' }, async () => {
18-
await decodePngAsync(png, 'first');
19-
const afterFirst = countDiagnosticEventsByPhase(['png_worker_unavailable']);
20-
await decodePngAsync(png, 'second');
21-
return { afterFirst, afterSecond: countDiagnosticEventsByPhase(['png_worker_unavailable']) };
22-
});
23-
const laterScope = await withDiagnosticsScope({ command: 'screenshot' }, async () => {
24-
await decodePngAsync(png, 'third');
14+
const prewarmed = await withDiagnosticsScope({ command: 'daemon' }, async () => {
15+
prewarmPngWorker();
2516
return countDiagnosticEventsByPhase(['png_worker_unavailable']);
2617
});
18+
const scopes = [];
19+
for (const label of ['first', 'second']) {
20+
scopes.push(
21+
await withDiagnosticsScope({ command: 'screenshot' }, async () => {
22+
await decodePngAsync(png, label);
23+
return countDiagnosticEventsByPhase(['png_worker_unavailable']);
24+
}),
25+
);
26+
}
2727

28-
expect(reported).toEqual({ afterFirst: 1, afterSecond: 1 });
29-
expect(laterScope).toBe(0);
28+
expect({ prewarmed, scopes }).toEqual({ prewarmed: 1, scopes: [1, 1] });
3029
vi.doUnmock('./internal-entry.ts');
3130
});
3231

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

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Worker } from 'node:worker_threads';
2-
import { emitDiagnostic, getDiagnosticsMeta } from '@agent-device/host-kit/diagnostics';
2+
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
33
import { AppError, toAppErrorCode } from '@agent-device/kernel/errors';
44
import type { Rect } from '@agent-device/kernel/snapshot';
55
import { resolveInternalEntryModulePath } from './internal-entry.ts';
@@ -40,29 +40,20 @@ type PendingJob = {
4040
let worker: Worker | null = null;
4141
let workerUnavailable = false;
4242
let workerUnavailableReason: string | undefined;
43-
let reportedWorkerUnavailable = false;
4443
let nextJobId = 0;
4544
const pendingJobs = new Map<number, PendingJob>();
4645

47-
/** Permanently degrades to the sync path; the reason is reported by the first scope that sees it. */
46+
/** Permanently degrades to the sync path; a scope that reaches the fallback reports the reason. */
4847
function markWorkerUnavailable(reason: string): void {
4948
workerUnavailable = true;
5049
workerUnavailableReason ??= reason;
51-
reportWorkerUnavailable();
5250
}
5351

54-
/**
55-
* A pre-warm at daemon startup runs outside any diagnostics scope, where the event would be
56-
* dropped, so the report waits for the first request scope that reaches the degraded path.
57-
*/
58-
function reportWorkerUnavailable(): void {
59-
if (reportedWorkerUnavailable || workerUnavailableReason === undefined) return;
60-
if (Object.keys(getDiagnosticsMeta()).length === 0) return;
61-
reportedWorkerUnavailable = true;
52+
function reportWorkerUnavailable(fallbackReason: string): void {
6253
emitDiagnostic({
6354
level: 'warn',
6455
phase: 'png_worker_unavailable',
65-
data: { reason: workerUnavailableReason },
56+
data: { reason: workerUnavailableReason ?? fallbackReason },
6657
});
6758
}
6859

@@ -112,10 +103,7 @@ function updateWorkerRef(): void {
112103
}
113104

114105
function obtainWorker(): Worker | null {
115-
if (workerUnavailable) {
116-
reportWorkerUnavailable();
117-
return null;
118-
}
106+
if (workerUnavailable) return null;
119107
if (worker) return worker;
120108
const modulePath = resolveInternalEntryModulePath(import.meta.url, PNG_WORKER_ENTRYPOINT);
121109
if (!modulePath) {
@@ -192,17 +180,19 @@ async function runPngJob<Kind extends PngWorkerJobKind>(
192180
return await runWorkerJob(job);
193181
} catch (error) {
194182
if (error instanceof PngWorkerUnavailableError) {
195-
// A worker can fail while this request waits on it, from an event callback with no scope.
196-
reportWorkerUnavailable();
183+
reportWorkerUnavailable(error.message);
197184
return await runSync();
198185
}
199186
throw error;
200187
}
201188
}
202189

203-
/** Daemon startup hook: spawns the worker before the first screenshot job. */
190+
/**
191+
* Daemon startup hook: spawns the worker before the first screenshot job. Run it inside a
192+
* diagnostics scope so a worker that cannot start leaves its reason in the daemon log.
193+
*/
204194
export function prewarmPngWorker(): void {
205-
obtainWorker();
195+
if (obtainWorker() === null) reportWorkerUnavailable('PNG worker is unavailable');
206196
}
207197

208198
/** Stops the worker thread (used by tests and shutdown); later calls respawn it. */
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import fs from 'node:fs';
2+
import { expect, test, vi } from 'vitest';
3+
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
4+
import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit';
5+
import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts';
6+
import { startDaemonRuntime } from './daemon-runtime.ts';
7+
8+
vi.mock('node:worker_threads', async (importOriginal) => ({
9+
...(await importOriginal<typeof import('node:worker_threads')>()),
10+
Worker: class {
11+
constructor() {
12+
throw new Error('worker threads are not available');
13+
}
14+
},
15+
}));
16+
17+
test('a daemon whose PNG worker cannot start records the reason in daemon.log', async () => {
18+
const stateDir = mkdtempForTestSync('agent-device-daemon-png-worker-');
19+
let runtime: Awaited<ReturnType<typeof startDaemonRuntime>> = null;
20+
try {
21+
runtime = await startDaemonRuntime({
22+
host: createTestHostEnvironment({
23+
env: {
24+
AGENT_DEVICE_STATE_DIR: stateDir,
25+
AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0',
26+
AGENT_DEVICE_DAEMON_SERVER_MODE: 'http',
27+
},
28+
}),
29+
exit: () => {},
30+
registerProcessHandlers: false,
31+
stderr: { write: () => {} },
32+
stdout: { write: () => {} },
33+
composeDeps: daemonRuntimeDepsFixture({}),
34+
});
35+
expect(runtime).not.toBeNull();
36+
37+
const events = fs
38+
.readFileSync(resolveDaemonPaths(stateDir).logPath, 'utf8')
39+
.split('\n')
40+
.filter((line) => line.includes('png_worker_unavailable'));
41+
expect(events).toHaveLength(1);
42+
expect(events[0]).toContain('failed to spawn worker: worker threads are not available');
43+
} finally {
44+
await runtime?.shutdown();
45+
fs.rmSync(stateDir, { recursive: true, force: true });
46+
}
47+
});

‎packages/daemon/src/server/http/daemon-runtime.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -893,8 +893,9 @@ async function startDaemonRuntimeOnHost(
893893

894894
// Spawn the PNG worker ahead of the first screenshot request so its
895895
// cold-start cost is not paid on a user-visible call. Best effort: when it
896-
// cannot start, PNG processing falls back to the in-process sync path.
897-
prewarmPngWorker();
896+
// cannot start, PNG processing falls back to the in-process sync path and the daemon log
897+
// records why.
898+
await withDaemonDiagnosticsScope({ logPath }, prewarmPngWorker);
898899

899900
const shutdownOnHost = async (shutdownOptions: { exitCode?: number; cause?: unknown } = {}) => {
900901
idleReap.cancel();

0 commit comments

Comments
 (0)