Skip to content

Commit 069bb4a

Browse files
committed
refactor(host): pass observer configuration explicitly
1 parent f312543 commit 069bb4a

6 files changed

Lines changed: 48 additions & 25 deletions

File tree

‎packages/host-kit/src/internal/process-executable-path.test.ts‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ vi.mock('./exec.ts', async (original) => ({
1717
import { readProcessExecutablePaths } from '../process.ts';
1818

1919
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!;
20+
const host = { env: process.env, cwd: process.cwd() };
2021
afterEach(() => {
2122
Object.defineProperty(process, 'platform', originalPlatform);
2223
vi.resetAllMocks();
@@ -45,7 +46,10 @@ test('Linux reads requested executable links and refuses missing, deleted and in
4546
if (!(name in entries)) throw new Error('unavailable');
4647
return entries[name];
4748
});
48-
const paths = await readProcessExecutablePaths([1, 2, 3, 4, 5, 6, 1, 0, -1, 1.5, 2147483648]);
49+
const paths = await readProcessExecutablePaths(
50+
[1, 2, 3, 4, 5, 6, 1, 0, -1, 1.5, 2147483648],
51+
host,
52+
);
4953
assert.deepEqual([...paths], [[1, '/opt/应用/my binary']]);
5054
assert.equal(readlinkMock.mock.calls.length, 6);
5155
assert.equal(runCmdMock.mock.calls.length, 0);
@@ -54,7 +58,7 @@ test('Linux reads requested executable links and refuses missing, deleted and in
5458
test('Linux deadline returns unknown when a read does not settle', async () => {
5559
platform('linux');
5660
readlinkMock.mockImplementation(() => new Promise(() => {}));
57-
assert.deepEqual([...(await readProcessExecutablePaths([1], 1))], []);
61+
assert.deepEqual([...(await readProcessExecutablePaths([1], host, 1))], []);
5862
});
5963

6064
test.each(['darwin', 'win32'] as const)(
@@ -76,7 +80,11 @@ test.each(['darwin', 'win32'] as const)(
7680
{ pid: 5, path: valid },
7781
]),
7882
});
79-
const paths = await readProcessExecutablePaths([1, 2, 3, 4, 5, 0, 1, -1, 1.5, 2147483648], 20);
83+
const paths = await readProcessExecutablePaths(
84+
[1, 2, 3, 4, 5, 0, 1, -1, 1.5, 2147483648],
85+
host,
86+
20,
87+
);
8088
assert.deepEqual([...paths], [[1, valid]]);
8189
assert.equal(runCmdMock.mock.calls.length, 1);
8290
const [cmd, args, options] = runCmdMock.mock.calls[0]!;
@@ -117,8 +125,8 @@ test.each(['darwin', 'win32'] as const)(
117125
stderr: '',
118126
});
119127
runCmdMock.mockRejectedValueOnce(new Error('timeout'));
120-
for (let i = 0; i < 3; i++) assert.equal((await readProcessExecutablePaths([1])).size, 0);
121-
assert.equal((await readProcessExecutablePaths([0, -1])).size, 0);
128+
for (let i = 0; i < 3; i++) assert.equal((await readProcessExecutablePaths([1], host)).size, 0);
129+
assert.equal((await readProcessExecutablePaths([0, -1], host)).size, 0);
122130
assert.equal(runCmdMock.mock.calls.length, 3);
123131
},
124132
);
@@ -128,17 +136,18 @@ test.each([undefined, '', 'Windows', String.raw`C:Windows`, String.raw`\Windows`
128136
async (root) => {
129137
platform('win32');
130138
vi.stubEnv('SystemRoot', root);
131-
assert.equal((await readProcessExecutablePaths([1])).size, 0);
139+
assert.equal((await readProcessExecutablePaths([1], host)).size, 0);
132140
assert.equal(runCmdMock.mock.calls.length, 0);
133141
},
134142
);
135143

136-
test('Windows host SystemRoot variable names are case-insensitive', async () => {
144+
test('Windows uses only its supplied host SystemRoot with case-insensitive names', async () => {
137145
platform('win32');
138-
vi.stubEnv('SystemRoot', undefined);
139-
vi.stubEnv('sYsTeMrOoT', String.raw`E:\Windows`);
140146
runCmdMock.mockResolvedValue({ stdout: '[]', stderr: '', exitCode: 0 });
141-
await readProcessExecutablePaths([1]);
147+
await readProcessExecutablePaths([1], {
148+
env: { sYsTeMrOoT: String.raw`E:\Windows` },
149+
cwd: process.cwd(),
150+
});
142151
assert.equal(
143152
runCmdMock.mock.calls[0]?.[0],
144153
String.raw`E:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`,

‎packages/host-kit/src/internal/process-executable-path.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value';
12
import { readlink } from 'node:fs/promises';
23
import path from 'node:path';
34
import { setTimeout, clearTimeout } from 'node:timers';
@@ -10,6 +11,7 @@ const PATH_BUFFER_BYTES = 4_096;
1011

1112
export async function readProcessExecutablePaths(
1213
pids: Iterable<number>,
14+
host: HostEnvironment,
1315
timeoutMs = DEFAULT_TIMEOUT_MS,
1416
): Promise<ReadonlyMap<number, string>> {
1517
const selected = uniquePositivePids(pids).filter((pid) => pid <= 2_147_483_647);
@@ -20,7 +22,7 @@ export async function readProcessExecutablePaths(
2022
return await withoutCommandExecutorOverride(async () => {
2123
try {
2224
const windows = platform === 'win32';
23-
const executable = windows ? windowsPowerShellPath() : '/usr/bin/osascript';
25+
const executable = windows ? windowsPowerShellPath(host.env) : '/usr/bin/osascript';
2426
if (!executable) return new Map();
2527
const result = await runCmd(
2628
executable,
@@ -37,9 +39,9 @@ export async function readProcessExecutablePaths(
3739
});
3840
}
3941

40-
function windowsPowerShellPath(): string | undefined {
41-
const key = Object.keys(process.env).find((name) => name.toUpperCase() === 'SYSTEMROOT');
42-
const root = key === undefined ? undefined : process.env[key];
42+
function windowsPowerShellPath(env: EnvMap): string | undefined {
43+
const key = Object.keys(env).find((name) => name.toUpperCase() === 'SYSTEMROOT');
44+
const root = key === undefined ? undefined : env[key];
4345
if (!root || !path.win32.isAbsolute(root) || path.win32.parse(root).root.length < 3) {
4446
return undefined;
4547
}

‎packages/host-kit/src/process.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
2+
13
export {
24
captureHostEnvironment,
35
type HostEnvironmentSource,
@@ -60,8 +62,9 @@ export {
6062
/** Observes actual executable paths. Missing entries are unknown, not proof of exit. */
6163
export async function readProcessExecutablePaths(
6264
pids: Iterable<number>,
65+
host: HostEnvironment,
6366
timeoutMs?: number,
6467
): Promise<ReadonlyMap<number, string>> {
6568
const observer = await import('./internal/process-executable-path.ts');
66-
return await observer.readProcessExecutablePaths(pids, timeoutMs);
69+
return await observer.readProcessExecutablePaths(pids, host, timeoutMs);
6770
}

‎packages/platform-web/src/agent-browser-lifecycle.test.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { bindTestCommandHost, installFakeManagedAgentBrowser } from '@agent-device/test-kit';
1+
import {
2+
bindTestCommandHost,
3+
createLiveTestHostEnvironment,
4+
installFakeManagedAgentBrowser,
5+
} from '@agent-device/test-kit';
26
import assert from 'node:assert/strict';
37
import * as hostFile from '@agent-device/host-kit/host-file';
48
import { ChildProcess } from 'node:child_process';
@@ -77,6 +81,7 @@ import {
7781
} from '@agent-device/host-kit/process';
7882

7983
bindTestCommandHost();
84+
const testHost = createLiveTestHostEnvironment();
8085

8186
const mockRunCmd = vi.mocked(runCmdMock);
8287

@@ -556,7 +561,9 @@ test.each([
556561
});
557562
observeProcesses([{ pid: 101, command: `${binary} daemon`, executable: observed }]);
558563
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
559-
expect((await recordManagedAgentBrowserProcesses(status, store)).pids).toEqual(expected);
564+
expect((await recordManagedAgentBrowserProcesses(status, store, testHost)).pids).toEqual(
565+
expected,
566+
);
560567
} finally {
561568
fs.rmSync(stateDir, { recursive: true, force: true });
562569
}
@@ -584,7 +591,7 @@ test('a managed binary symlink cannot confer ownership on an executable outside
584591
]);
585592
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
586593

587-
expect((await recordManagedAgentBrowserProcesses(status, store)).pids).toEqual([101]);
594+
expect((await recordManagedAgentBrowserProcesses(status, store, testHost)).pids).toEqual([101]);
588595
expect(store.replace.mock.calls[0]?.[1].map(({ pid }: { pid: number }) => pid)).toEqual([101]);
589596
} finally {
590597
fs.rmSync(stateDir, { recursive: true, force: true });
@@ -612,7 +619,7 @@ test('records verified current and retained native roots and stable descendants'
612619
];
613620
observeProcesses(rows);
614621
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
615-
const summary = await recordManagedAgentBrowserProcesses(status, store);
622+
const summary = await recordManagedAgentBrowserProcesses(status, store, testHost);
616623
expect(summary.pids).toEqual([101, 102, 201, 301]);
617624
expect(summary.processes.map(({ reason }) => reason)).toEqual([
618625
'agent-browser-daemon',
@@ -670,7 +677,7 @@ test('retained Chrome home and marker roots require a Chrome executable and this
670677
];
671678
observeProcesses(rows);
672679
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
673-
const summary = await recordManagedAgentBrowserProcesses(status, store);
680+
const summary = await recordManagedAgentBrowserProcesses(status, store, testHost);
674681
expect(summary.pids).toEqual([201, 202]);
675682
expect(summary.processes.map(({ reason }) => reason)).toEqual([
676683
'launch-marker',
@@ -726,7 +733,7 @@ test('an unstable root or intermediate process cannot authorize its descendants'
726733
),
727734
);
728735
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
729-
const summary = await recordManagedAgentBrowserProcesses(status, store);
736+
const summary = await recordManagedAgentBrowserProcesses(status, store, testHost);
730737
expect(summary.pids).toEqual([101]);
731738
} finally {
732739
fs.rmSync(stateDir, { recursive: true, force: true });
@@ -748,7 +755,7 @@ test('recording refuses a scanned command that differs from the bracketed identi
748755
new Map([[101, { startTime: 'start-101', command: 'different command', zombie: false }]]),
749756
);
750757
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
751-
expect((await recordManagedAgentBrowserProcesses(status, store)).pids).toEqual([]);
758+
expect((await recordManagedAgentBrowserProcesses(status, store, testHost)).pids).toEqual([]);
752759
expect(store.replace).not.toHaveBeenCalled();
753760
} finally {
754761
fs.rmSync(stateDir, { recursive: true, force: true });
@@ -793,7 +800,7 @@ test('recording and reaping require executable provenance and matching identity'
793800
sessionsDir: path.join(stateDir, 'sessions'),
794801
resolveSessionDir: (id) => path.join(stateDir, 'sessions', id),
795802
});
796-
await recordManagedAgentBrowserProcesses(status, store);
803+
await recordManagedAgentBrowserProcesses(status, store, testHost);
797804
const recordedPids = store.read()[0]?.records.map(({ pid }) => pid);
798805
const alive = new Set(rows.map(({ pid }) => pid));
799806
const signals: number[] = [];

‎packages/platform-web/src/agent-browser-process-record.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { HostEnvironment } from '@agent-device/kernel/source-value';
12
import crypto from 'node:crypto';
23
import path from 'node:path';
34
import type { OwnedProcessRecord } from '@agent-device/contracts/platform-runtime-host';
@@ -125,12 +126,13 @@ export async function inspectManagedAgentBrowserProcesses(
125126
export async function recordManagedAgentBrowserProcesses(
126127
status: AgentBrowserToolStatus,
127128
store: OwnedProcessRecordStore,
129+
host: HostEnvironment,
128130
): Promise<AgentBrowserProcessSummary> {
129131
const initial = await listRealHostProcesses();
130132
const pids = initial.map(({ pid }) => pid);
131133
const before = await readProcessIdentities(pids);
132134
const scanned = await listRealHostProcesses();
133-
const executablePaths = await readProcessExecutablePaths(pids);
135+
const executablePaths = await readProcessExecutablePaths(pids, host);
134136
const after = await readProcessIdentities(pids);
135137
const initialPids = new Set(pids);
136138
const processes = scanned.filter(({ pid, command }) => {

‎packages/platform-web/src/agent-browser-provider.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -683,7 +683,7 @@ async function finalizeAgentBrowserProcessRecord(params: {
683683
return;
684684
}
685685
if (await shouldRefreshAgentBrowserProcessRecord(params, store)) {
686-
await recordManagedAgentBrowserProcesses(params.status, store);
686+
await recordManagedAgentBrowserProcesses(params.status, store, params.options.host);
687687
}
688688
} catch (error) {
689689
emitDiagnostic({

0 commit comments

Comments
 (0)