mirror of
https://github.com/callstack/agent-device.git
synced 2026-09-14 20:06:34 +08:00
e832325e87
* refactor: split generic host mechanics into @agent-device/host-kit (#2082 W1) The shared src/utils closure that blocked the platform-family moves lands on declared owners: generic host mechanics form a new private @agent-device/host-kit package between kernel and capture-kit, and capture-kit keeps capture, snapshot, and recording behavior, depending on host-kit for the mechanics it needs. tar-stream and yauzl move with the archive code. Every seam's exported subpaths are pinned in package-boundaries.test.ts, the layering model ranks the new zone, R13's allow-list names it, and each seam carries an exact eager-closure row. ADR-0019's substrate amendment describes the layout. Tests that mocked two of the moved modules separately became duplicate same-seam vi.mock factories, where the second silently replaced the first; those are merged, and the mocks that production code reaches past are pinned at their injection points instead. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * refactor(host-kit): one narrow capability port per export The four technical barrels (exec/fs/values/request) grouped by category rather than by capability, so a consumer needing one mechanic evaluated unrelated ones. Each export is now a single capability over the host machine: command, process, diagnostics, retry, archive, file, request, version. A port re-exports only what a consumer of that capability uses, and every port carries its own eager-closure row. Most of the old values barrel was never host mechanics. Pure record readers, config-source values, result text, memoization, async scoping, coordinate validation, and device-scope parsing touch no process, file, or environment, so they join kernel's other primitives instead. Closures fall accordingly: capture-kit's png-worker-client from 20 to 10, png-resize from 28 to 18, session-teardown from 79 to 68, and the CLI from 386 to 380. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * chore: drop the migration inventories and trim the touched comments Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * docs: trim the touched host-kit and mutation-lane comments Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * docs: keep tool directives only in the touched files Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * docs: keep tool directives only across the touched tree Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * fix: point the Swift parity comment at the real TS twin and test The W1 move rewrote this citation to packages/contracts/src/mobile-snapshot-semantics.ts, which does not exist: the module went to capture-kit while isTapPointInsideViewport itself went to packages/contracts/src/snapshot-visibility.ts. The TS test line was left pointing at the pre-move path. Both now resolve. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH * fix: repoint comment citations at the homes this refactor moved them to The W1 move left ~20 comment citations pointing at src/utils/*.ts and src/request/*.ts paths that no longer exist. Each now names the capability port that owns the symbol, which survives further file moves: exec -> host-kit/command host-process, owner-identity -> host-kit/process diagnostics -> host-kit/diagnostics atomic-file, process-lock -> host-kit/file retry -> host-kit/retry request progress/cancel -> host-kit/request version -> host-kit/version ttl-memo, source-value, parsing, device-isolation, keyed-lock, success-text -> kernel subpaths Comment-only; no closure, budget, or behavior change. ADR citations are left as written, being dated records of the decision rather than live references. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018VngeKZH6zBuJzNBk5YzUH --------- Co-authored-by: Claude <noreply@anthropic.com>
124 lines
4.9 KiB
TypeScript
124 lines
4.9 KiB
TypeScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { skipWhenLoopbackUnavailable } from '../../src/__tests__/test-utils/loopback.ts';
|
|
import { stopProcessForTakeover } from '../../src/daemon/daemon-process.ts';
|
|
import { isProcessAlive } from '@agent-device/host-kit/process';
|
|
import { assertNoDaemonLeaks } from './support/daemon-leak-oracle.ts';
|
|
import { runCliJson } from './test-helpers.ts';
|
|
|
|
// #1596: a CLI command that finds its recorded daemon unreachable replaces it
|
|
// (`Replacing daemon (pid N, vX) in <state-dir>: unreachable`) and retries
|
|
// against a fresh one. Three field runs died with zero further agent actions
|
|
// immediately after that replace plus a SESSION_NOT_FOUND (the fresh daemon
|
|
// has no sessions yet, which is expected). This file locks down that a
|
|
// replace-mid-command always ends in a normal, fully-delivered structured
|
|
// error rather than a truncated or hung process.
|
|
|
|
type DaemonInfo = {
|
|
pid: number;
|
|
processStartTime?: string;
|
|
};
|
|
|
|
test('daemon replace mid-command returns a structured, parseable error and exits normally', async (t) => {
|
|
if (await skipWhenLoopbackUnavailable(t)) {
|
|
return;
|
|
}
|
|
|
|
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-replace-exit-flush-'));
|
|
let info: DaemonInfo | null = null;
|
|
const daemonPids: number[] = [];
|
|
try {
|
|
// A real daemon, started by this codebase, so its recorded version/code
|
|
// signature legitimately match — the only way to reach the "unreachable"
|
|
// takeover reason (as opposed to a version/signature mismatch takeover).
|
|
const started = runCliJson(['session', 'list', '--json', '--state-dir', stateDir]);
|
|
assert.equal(started.status, 0, `${started.stderr}\n${started.stdout}`);
|
|
|
|
info = readDaemonInfo(stateDir);
|
|
daemonPids.push(info.pid);
|
|
assert.equal(isProcessAlive(info.pid), true, 'expected the started daemon to be alive');
|
|
|
|
// Kill it out from under its own metadata: daemon.json stays put and
|
|
// still points at a pid that is now unreachable, reproducing the crash
|
|
// the field transcripts observed.
|
|
process.kill(info.pid, 'SIGKILL');
|
|
await waitForProcessDeath(info.pid);
|
|
|
|
const result = runCliJson(['close', '--json', '--state-dir', stateDir]);
|
|
|
|
assert.equal(result.status, 1, formatUnexpected('exit code', result));
|
|
assert.ok(
|
|
result.stderr.includes('Replacing daemon') && result.stderr.includes('unreachable'),
|
|
formatUnexpected('takeover notice on stderr', result),
|
|
);
|
|
assert.ok(result.json, formatUnexpected('parseable JSON stdout', result));
|
|
assert.equal(result.json.success, false, formatUnexpected('success:false', result));
|
|
assert.equal(
|
|
result.json.error?.code,
|
|
'SESSION_NOT_FOUND',
|
|
formatUnexpected('SESSION_NOT_FOUND', result),
|
|
);
|
|
// #1596 requirement: a hint pointing at `open` is always present, not
|
|
// just "fresh daemon, good luck" — this is the daemon.json truthfully
|
|
// having no sessions, which is expected; only the error's shape/delivery
|
|
// was ever in question.
|
|
assert.match(
|
|
result.json.error?.hint ?? '',
|
|
/open/i,
|
|
formatUnexpected('an `open` hint', result),
|
|
);
|
|
|
|
info = readDaemonInfo(stateDir);
|
|
daemonPids.push(info.pid);
|
|
await stopProcessForTakeover(info.pid, {
|
|
termTimeoutMs: 1_500,
|
|
killTimeoutMs: 1_500,
|
|
expectedStartTime: info.processStartTime,
|
|
});
|
|
// #1781 B1: neither the SIGKILLed daemon nor its replacement may leave owned
|
|
// processes or unclassified state-dir residue once both are gone. `info`
|
|
// stays set until this passes: `stopProcessForTakeover` is best-effort, so a
|
|
// failed stop must still reach the `finally` retry below rather than have
|
|
// the state dir removed out from under a daemon that is still running.
|
|
await assertNoDaemonLeaks({ stateDir, daemonPids, phase: 'after-shutdown' });
|
|
info = null;
|
|
} finally {
|
|
if (info) {
|
|
await stopProcessForTakeover(info.pid, {
|
|
termTimeoutMs: 1_500,
|
|
killTimeoutMs: 1_500,
|
|
expectedStartTime: info.processStartTime,
|
|
});
|
|
}
|
|
fs.rmSync(stateDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
async function waitForProcessDeath(pid: number): Promise<void> {
|
|
const deadline = Date.now() + 5_000;
|
|
while (Date.now() < deadline) {
|
|
if (!isProcessAlive(pid)) return;
|
|
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
}
|
|
assert.fail(`daemon pid ${pid} did not die after SIGKILL`);
|
|
}
|
|
|
|
function readDaemonInfo(stateDir: string): DaemonInfo {
|
|
return JSON.parse(fs.readFileSync(path.join(stateDir, 'daemon.json'), 'utf8')) as DaemonInfo;
|
|
}
|
|
|
|
function formatUnexpected(
|
|
expected: string,
|
|
result: { status: number; stdout: string; stderr: string },
|
|
): string {
|
|
return [
|
|
`expected ${expected}`,
|
|
`status: ${result.status}`,
|
|
`stdout: ${result.stdout || '(empty)'}`,
|
|
`stderr: ${result.stderr || '(empty)'}`,
|
|
].join('\n');
|
|
}
|