Skip to content

Commit 3916a64

Browse files
committed
test(11a-2d): assert platform cleanup at the port; move find read-only suites root-side
Owner review on #3519: - Teardown/close suites inject platformResourceCleanupFixture() and assert the stopSnapshotHelper / closeManagedBrowser port members, with a rejecting override for the cleanup-failure channel. The no-op constant and the as-platformResourceCleanup alias are gone; one fixture per port. The adapter's web-device filter (a composition decision) is pinned root-owned in daemon-runtime-web-close-teardown. - find-read-only and find-ambiguous-match run the selector find/wait route, so they relocate to src/__tests__/daemon-composition/interaction/ behind testCreateCommandSurface, per the PR's own sorting rule. - providerCredentialsFixture drops the copied digest format for an opaque deterministic key over the sorted defined pairs. - fakeCommandSurface becomes module-private (fallow's unused export).
1 parent 2c7a8d0 commit 3916a64

22 files changed

Lines changed: 148 additions & 120 deletions

src/daemon/interaction/internal/__tests__/find-ambiguous-match.test.ts renamed to src/__tests__/daemon-composition/interaction/find-ambiguous-match.test.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,17 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal
77
resolveTargetDevice: actual.resolveTargetDevice,
88
};
99
});
10-
vi.mock('../../../snapshot-interactor-capture.ts', async () => {
11-
const fixture = await import('../../../__tests__/legacy-snapshot-capture-fixture.ts');
10+
vi.mock('../../../daemon/snapshot-interactor-capture.ts', async () => {
11+
const fixture = await import('../../../daemon/__tests__/legacy-snapshot-capture-fixture.ts');
1212
return { captureSnapshotWithInteractor: fixture.captureSnapshotThroughLegacyDispatchFixture };
1313
});
1414

1515
import {
1616
resetFindTouchRuntimeFixture,
1717
runFindClickScenario,
18-
} from './find-touch-runtime-fixture.ts';
19-
import { refFrameScope, refFrameState } from '../../../ref-frame.ts';
18+
} from '../../../daemon/interaction/internal/__tests__/find-touch-runtime-fixture.ts';
19+
import { testCreateCommandSurface } from '../command-surface-fixture.ts';
20+
import { refFrameScope, refFrameState } from '../../../daemon/ref-frame.ts';
2021

2122
beforeEach(() => {
2223
resetFindTouchRuntimeFixture();
@@ -39,6 +40,7 @@ test('handleFindCommands ambiguous match lists snapshot-line candidates capped a
3940
});
4041

4142
const { response } = await runFindClickScenario({
43+
createCommandSurface: testCreateCommandSurface,
4244
positionals: ['Follow', 'click'],
4345
nodes: [
4446
{ index: 0, ref: 'e1', type: 'Application', rect: { x: 0, y: 0, width: 800, height: 1200 } },
@@ -72,6 +74,7 @@ test('handleFindCommands ambiguous match lists snapshot-line candidates capped a
7274

7375
test('handleFindCommands ambiguous match with few candidates lists them all uncapped', async () => {
7476
const { response } = await runFindClickScenario({
77+
createCommandSurface: testCreateCommandSurface,
7578
positionals: ['Follow', 'click'],
7679
nodes: [
7780
{ index: 0, ref: 'e1', type: 'Application', rect: { x: 0, y: 0, width: 800, height: 1200 } },
@@ -126,6 +129,7 @@ test('handleFindCommands list returns every match without acting', async () => {
126129
});
127130

128131
const { response, invokeCalls, session } = await runFindClickScenario({
132+
createCommandSurface: testCreateCommandSurface,
129133
positionals: ['text', 'Follow', 'list'],
130134
nodes: [
131135
{ index: 0, ref: 'e1', type: 'Application', rect: { x: 0, y: 0, width: 800, height: 1200 } },
@@ -152,6 +156,7 @@ test('handleFindCommands list returns every match without acting', async () => {
152156

153157
test('handleFindCommands list on a unique match still lists instead of tapping', async () => {
154158
const { response, invokeCalls } = await runFindClickScenario({
159+
createCommandSurface: testCreateCommandSurface,
155160
positionals: ['Dictionary', 'list'],
156161
nodes: [
157162
{ index: 0, ref: 'e1', type: 'Application', rect: { x: 0, y: 0, width: 800, height: 1200 } },
@@ -190,6 +195,7 @@ test('handleFindCommands selector-shaped find rejects multiple matches with cand
190195
});
191196

192197
const { response, invokeCalls } = await runFindClickScenario({
198+
createCommandSurface: testCreateCommandSurface,
193199
positionals: ['role=button', 'click'],
194200
nodes: [
195201
{ index: 0, ref: 'e1', type: 'Application', rect: { x: 0, y: 0, width: 800, height: 1200 } },
@@ -219,6 +225,7 @@ test('handleFindCommands selector-shaped find honors the explicit --first opt-ou
219225
});
220226

221227
const { response, invokeCalls } = await runFindClickScenario({
228+
createCommandSurface: testCreateCommandSurface,
222229
positionals: ['role=button', 'click'],
223230
flags: { findFirst: true },
224231
nodes: [

src/daemon/interaction/internal/__tests__/find-read-only.test.ts renamed to src/__tests__/daemon-composition/interaction/find-read-only.test.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { test, expect, vi, beforeEach } from 'vitest';
2-
import type { SessionState } from '../../../session-state.ts';
2+
import type { SessionState } from '../../../daemon/session-state.ts';
33
import { buildSnapshotSignatures } from '@agent-device/capture-kit/snapshot-freshness';
4-
import { makeSessionStore } from '../../../__tests__/support/store-factory.ts';
4+
import { makeSessionStore } from '../../../daemon/__tests__/support/store-factory.ts';
55
import {
66
makeAuthoringSession,
77
makeIosSession as makeSession,
8-
} from '../../../__tests__/support/session-factories.ts';
8+
} from '../../../daemon/__tests__/support/session-factories.ts';
99

1010
vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal) => {
1111
const actual = (await importOriginal()) as Record<string, unknown>;
@@ -14,17 +14,18 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal
1414
resolveTargetDevice: actual.resolveTargetDevice,
1515
};
1616
});
17-
vi.mock('../../../snapshot-interactor-capture.ts', async () => {
18-
const fixture = await import('../../../__tests__/legacy-snapshot-capture-fixture.ts');
17+
vi.mock('../../../daemon/snapshot-interactor-capture.ts', async () => {
18+
const fixture = await import('../../../daemon/__tests__/legacy-snapshot-capture-fixture.ts');
1919
return { captureSnapshotWithInteractor: fixture.captureSnapshotThroughLegacyDispatchFixture };
2020
});
2121

2222
import {
2323
mockDispatch,
2424
resetFindTouchRuntimeFixture,
2525
runFindClickScenario,
26-
} from './find-touch-runtime-fixture.ts';
27-
import { invokeFindHandler } from './find-handler-fixture.ts';
26+
} from '../../../daemon/interaction/internal/__tests__/find-touch-runtime-fixture.ts';
27+
import { testCreateCommandSurface } from '../command-surface-fixture.ts';
28+
import { invokeFindHandler } from '../../../daemon/interaction/internal/__tests__/find-handler-fixture.ts';
2829

2930
beforeEach(() => {
3031
resetFindTouchRuntimeFixture();
@@ -89,6 +90,7 @@ test('handleFindCommands wait bypasses snapshot cache while Android freshness re
8990
});
9091

9192
const { response } = await runFindClickScenario({
93+
createCommandSurface: testCreateCommandSurface,
9294
positionals: ['text', 'Create document', 'wait', '700'],
9395
session,
9496
});
@@ -136,6 +138,7 @@ test('handleFindCommands wait reports sparse verdict through selector runtime ro
136138
});
137139

138140
const { response } = await runFindClickScenario({
141+
createCommandSurface: testCreateCommandSurface,
139142
positionals: ['text', 'Never appears', 'wait', '350'],
140143
session,
141144
});
@@ -154,6 +157,7 @@ test('handleFindCommands wait reports sparse verdict through selector runtime ro
154157

155158
test('handleFindCommands wait captures fresh snapshots while polling', async () => {
156159
const { response } = await runFindClickScenario({
160+
createCommandSurface: testCreateCommandSurface,
157161
positionals: ['text', 'Never appears', 'wait', '350'],
158162
nodes: [{ index: 0, depth: 0, type: 'StaticText', label: 'Other text' }],
159163
});
@@ -196,6 +200,7 @@ test('read-only find while recording is intentionally deferred from target-v1 ev
196200
});
197201

198202
const response = await invokeFindHandler({
203+
createCommandSurface: testCreateCommandSurface,
199204
sessionName,
200205
sessionStore,
201206
positionals: ['text', 'Save', 'exists'],

‎src/__tests__/daemon-composition/server/daemon-runtime-web-close-teardown.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,33 @@ test('daemon shutdown reports a web close failure on stderr instead of losing it
127127
expect(stderrChunks.join('')).toMatch(/web_browser/);
128128
expect(sessionStore.get(session.name)).toBeUndefined();
129129
});
130+
131+
// The platform filter lives in the composed adapter, not in the neutral teardown: the daemon
132+
// asks the port for every session, and only a web device reaches the agent-browser process.
133+
test('daemon session teardown never dispatches a web close for a non-web session', async () => {
134+
const root = mkdtempForTestSync('agent-device-non-web-teardown-');
135+
const sessionStore = new SessionStore(path.join(root, 'sessions'));
136+
sessionStore.publish('android-non-web-teardown-session', {
137+
name: 'android-non-web-teardown-session',
138+
device: {
139+
platform: 'android',
140+
id: 'emulator-5554',
141+
name: 'Pixel',
142+
kind: 'emulator',
143+
booted: true,
144+
},
145+
createdAt: Date.now(),
146+
actions: [],
147+
});
148+
149+
await teardownDaemonSessionForShutdown({
150+
ref: sessionStore.lookup('android-non-web-teardown-session')!,
151+
sessionStore,
152+
stderr: { write: () => {} },
153+
platformCleanup: platformResourceCleanup,
154+
});
155+
156+
// The snapshot-helper leg is a real-mechanics no-op for a device with no registered helper
157+
// session; the process seam below is what a mistaken web close would have shown up on.
158+
expect(mockRunCmd).not.toHaveBeenCalled();
159+
});

‎src/daemon/__tests__/daemon-runtime-app-log.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { noopPlatformResourceCleanup as platformResourceCleanup } from './support/platform-resource-cleanup-fixture.ts';
1+
import { platformResourceCleanupFixture } from './support/platform-resource-cleanup-fixture.ts';
22
import fs from 'node:fs';
33
import path from 'node:path';
44
import { expect, test, vi } from 'vitest';
@@ -132,7 +132,7 @@ test('daemon shutdown settles fenced app-log cleanup before finalization can rel
132132
sessionStore,
133133
stderr: { write: () => {} },
134134

135-
platformCleanup: platformResourceCleanup,
135+
platformCleanup: platformResourceCleanupFixture(),
136136
});
137137
await cleanupStarted;
138138

‎src/daemon/__tests__/replay-maestro/session-replay-maestro-remote-evalscript.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from 'node:path';
44
import { describe, expect, test, vi } from 'vitest';
55
import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
66
import { LeaseRegistry } from '../../lease-registry.ts';
7-
import { noopPlatformResourceCleanup as platformResourceCleanup } from '../support/platform-resource-cleanup-fixture.ts';
7+
import { platformResourceCleanupFixture } from '../support/platform-resource-cleanup-fixture.ts';
88
import { SessionStore } from '../../session-store.ts';
99
import { makeIosSession } from '../support/session-factories.ts';
1010
import { maestroScriptSourceBundleFor } from '../../../__tests__/test-utils/replay-script-source.ts';
@@ -143,7 +143,7 @@ async function runWithTestNetworkFlag(publicNetworkOnly: boolean | undefined) {
143143
},
144144
retainDeviceExecutionLock: async () => {},
145145
throwIfCanceled: () => {},
146-
platformResourceCleanup,
146+
platformResourceCleanup: platformResourceCleanupFixture(),
147147
} as unknown as SessionCommandParams);
148148

149149
if (!response) throw new Error('Expected replay test response');

‎src/daemon/__tests__/replay-repair/session-replay-repair-record-exclusion.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ import {
6565
bindLifecycleRuntime,
6666
inspectLifecycleRuntimeFacts,
6767
} from '../application-lifecycle-runtime-harness.ts';
68-
import { noopPlatformResourceCleanup as platformResourceCleanup } from '../support/platform-resource-cleanup-fixture.ts';
68+
import { platformResourceCleanupFixture } from '../support/platform-resource-cleanup-fixture.ts';
6969
import {
7070
captureSnapshotThroughLegacyDispatchFixture,
7171
legacyDispatchCapture,
@@ -79,7 +79,7 @@ function handleCloseCommand(
7979
) {
8080
return handleProductionCloseCommand({
8181
...params,
82-
platformResourceCleanup,
82+
platformResourceCleanup: platformResourceCleanupFixture(),
8383
inspectFacts: inspectLifecycleRuntimeFacts,
8484
bindDevice: bindLifecycleRuntime,
8585
});

‎src/daemon/__tests__/replay-repair/session-replay-repair-transaction.fixtures.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
bindLifecycleRuntime,
1313
inspectLifecycleRuntimeFacts,
1414
} from '../application-lifecycle-runtime-harness.ts';
15-
import { noopPlatformResourceCleanup as platformResourceCleanup } from '../support/platform-resource-cleanup-fixture.ts';
15+
import { platformResourceCleanupFixture } from '../support/platform-resource-cleanup-fixture.ts';
1616
import { freshEvidence } from './session-replay-repair.fixtures.ts';
1717

1818
/**
@@ -50,7 +50,7 @@ export function handleCloseCommand(
5050
) {
5151
return handleProductionCloseCommand({
5252
...params,
53-
platformResourceCleanup,
53+
platformResourceCleanup: platformResourceCleanupFixture(),
5454
inspectFacts: inspectLifecycleRuntimeFacts,
5555
bindDevice: bindLifecycleRuntime,
5656
});

‎src/daemon/__tests__/support/command-surface-fake.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import type {
1313
* `src/__tests__/daemon-composition/` behind the real `testCreateCommandSurface`, where its
1414
* assertions keep their meaning.
1515
*/
16-
export const fakeCommandSurface: DaemonCommandSurface = {
16+
const fakeCommandSurface: DaemonCommandSurface = {
1717
capture: {
1818
screenshot: vi.fn(async () => ({ path: '/tmp/fake-screenshot.png' })),
1919
snapshot: vi.fn(async () => ({ nodes: [] })),
Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,31 @@
1-
import { vi } from 'vitest';
1+
import { vi, type Mock } from 'vitest';
22
import type { PlatformResourceCleanup } from '../../platform-resource-cleanup.ts';
33

4+
/** Every member observable as a spy, which is how the daemon suites read the fixture back. */
5+
export type PlatformResourceCleanupFixture = {
6+
[K in keyof PlatformResourceCleanup]: Mock<PlatformResourceCleanup[K]>;
7+
};
8+
49
/**
510
* The `PlatformResourceCleanup` port as the daemon suites need it. Daemon tests assert which
611
* finalization the neutral orchestration asked for and with which arguments — snapshot-helper
712
* stop on close, managed-browser close on web teardown, host retention on shutdown — never how
813
* a platform performs it; the concrete snapshot-helper, managed-browser, and runner-host
9-
* teardown mechanics belong to the platform packages. A suite that needs a failure or a
10-
* specific answer overrides the single member it cares about, the same way production wiring
11-
* replaces one composed capability.
14+
* teardown mechanics belong to the platform packages and are asserted root-owned under
15+
* `src/__tests__/daemon-composition/`. Each member is a `vi.fn`, so a suite both injects and
16+
* observes it: read calls off the returned members. An override replaces one capability's
17+
* behavior (a rejection, a specific retention answer) and stays spy-visible — the same shape
18+
* production wiring takes when it composes a different capability.
1219
*/
1320
export function platformResourceCleanupFixture(
1421
overrides: Partial<PlatformResourceCleanup> = {},
15-
): PlatformResourceCleanup {
22+
): PlatformResourceCleanupFixture {
1623
return Object.freeze({
17-
stopSnapshotHelper: vi.fn(async () => {}),
18-
closeManagedBrowser: vi.fn(async () => {}),
19-
cleanupSessionlessExecutionHost: vi.fn(async () => {}),
20-
retainExecutionHostAfterClose: vi.fn(() => false),
21-
...overrides,
22-
});
24+
stopSnapshotHelper: vi.fn(overrides.stopSnapshotHelper ?? (async () => {})),
25+
closeManagedBrowser: vi.fn(overrides.closeManagedBrowser ?? (async () => {})),
26+
cleanupSessionlessExecutionHost: vi.fn(
27+
overrides.cleanupSessionlessExecutionHost ?? (async () => {}),
28+
),
29+
retainExecutionHostAfterClose: vi.fn(overrides.retainExecutionHostAfterClose ?? (() => false)),
30+
}) as PlatformResourceCleanupFixture;
2331
}
24-
25-
/**
26-
* The shared no-op cleanup for suites that only need the capability to exist and never assert
27-
* on it. Prefer {@link platformResourceCleanupFixture} per test when the suite observes calls.
28-
*/
29-
export const noopPlatformResourceCleanup: PlatformResourceCleanup = Object.freeze({
30-
stopSnapshotHelper: async () => {},
31-
closeManagedBrowser: async () => {},
32-
cleanupSessionlessExecutionHost: async () => {},
33-
retainExecutionHostAfterClose: () => false,
34-
});
Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,32 @@
1-
import crypto from 'node:crypto';
21
import type { DaemonProviderCredentials } from '@agent-device/daemon-contracts/provider-credentials';
32

43
/**
54
* The `DaemonProviderCredentials` port as the daemon suites need it. The daemon only compares
65
* the fingerprint a client reports against the one this port computes from the daemon's startup
7-
* environment — the digests are opaque to daemon policy, which asserts refusal, reuse, and
8-
* passthrough, never digest content. The real reader's provider/manifest-aware variable
9-
* selection and digest semantics are pinned root-owned (request-router-provider-credentials,
10-
* lease-provider-credentials). This fixture digests the whole given environment so distinct
11-
* environments produce distinct fingerprints and an empty environment produces `undefined` —
12-
* the whole contract the daemon suites observe, without reading provider declarations.
6+
* environment — the fingerprints are opaque to daemon policy, which asserts refusal, reuse, and
7+
* passthrough, never fingerprint content. So the fake builds a deterministic opaque key from
8+
* the sorted defined pairs rather than reproducing the real reader's digest format (the real
9+
* provider/manifest-aware selection and digest semantics are pinned root-owned in
10+
* request-router-provider-credentials and lease-provider-credentials). Distinct environments
11+
* produce distinct keys and an empty environment produces `undefined` — the whole contract the
12+
* daemon suites observe.
1313
*/
1414
export function providerCredentialsFixture(
1515
env: Readonly<Record<string, string | undefined>> = {},
1616
stateDir = '/tmp',
1717
): DaemonProviderCredentials {
1818
const startupEnv = { ...env };
1919
return {
20-
fingerprint: () => digest(startupEnv),
20+
fingerprint: () => opaqueFingerprint(startupEnv),
2121
stateDir,
2222
};
2323
}
2424

25-
function digest(values: Readonly<Record<string, string | undefined>>): string | undefined {
25+
function opaqueFingerprint(
26+
values: Readonly<Record<string, string | undefined>>,
27+
): string | undefined {
2628
const pairs = Object.entries(values)
2729
.filter((pair): pair is [string, string] => pair[1] !== undefined)
2830
.sort(([left], [right]) => left.localeCompare(right));
29-
if (pairs.length === 0) return undefined;
30-
const hash = crypto.createHash('sha256').update(JSON.stringify(pairs)).digest('hex');
31-
return `v1:${hash.slice(0, 16)}`;
31+
return pairs.length === 0 ? undefined : JSON.stringify(pairs);
3232
}

0 commit comments

Comments
 (0)