From 0d6d9e79cb548337592d6694b11db94dd0df07fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 6 Dec 2026 11:36:15 +0100 Subject: [PATCH 1/2] fix(daemon): collect a suite recording its script closed early A remote `test --record-video` whose script ends with `close` answered `success: true` with no `recordingArtifacts`, and the attempt folder in the `test-artifacts` download had no `recording.mp4`, while the MP4 stayed on the daemon host. That close retires the attempt session inside the replay action, so suite cleanup resolved no session for the attempt and returned before collecting the export its close had just committed. Cleanup now settles against the attempt's last pinned ref, which still names the session directory and the lifetime the committed export is guarded by, and the attempt keeps that ref instead of overwriting it with an unresolvable pin. --- ...y-command-closed-session-recording.test.ts | 128 ++++++++++++++++++ .../handlers/session-replay-command.ts | 32 +++-- 2 files changed, 152 insertions(+), 8 deletions(-) create mode 100644 packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts diff --git a/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts new file mode 100644 index 00000000000..bdbfcbac794 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts @@ -0,0 +1,128 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { errorResponse } from '@agent-device/kernel/contracts'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger'; +import { getReplayExecution } from '@agent-device/replay-port/replay-backend-registry'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + handleSessionCommands, + mockBindDeviceRuntime, +} from '../../__tests__/support/handlers/session-command-harness.ts'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; +import { makeAndroidSession } from '../../__tests__/support/session-factories.ts'; +import { makeRecordRuntimeHarness } from './__tests__/record-runtime.fixtures.ts'; +import { + cleanupDownloadableArtifact, + listDownloadableArtifacts, +} from '../../resources/artifact-tracking.ts'; +import { expectOkData } from '../__tests__/replay-suite/session-test-suite.fixtures.ts'; + +test('a remote suite delivers the recording its script closed during the attempt', async () => { + await getReplayExecution(); + const root = mkdtempForTestSync('suite-recording-script-close-'); + const script = path.join(root, 'flow.ad'); + fs.writeFileSync(script, 'context platform=android\nopen "Demo"\nclose\n'); + const { sessionStore, runtime } = makeRecordRuntimeHarness('suite-recording-script-close-'); + const finish = runtime.finish.getMockImplementation()!; + runtime.finish.mockImplementation(async () => { + const finished = await finish(); + fs.writeFileSync(finished.result.outPath, 'video-exported-by-script-close'); + const telemetryPath = deriveRecordingTelemetryPath(finished.result.outPath); + fs.writeFileSync(telemetryPath, '{}'); + return { ...finished, result: { ...finished.result, telemetryPath } }; + }); + const platformResourceCleanup = platformResourceCleanupFixture(); + const tenantId = 'closing-suite'; + const clientRoot = path.join(root, 'client'); + const bindDevice: NonNullable[0]['bindDevice']> = async ( + device, + use, + ) => + [...use.required, ...(use.preferred ?? [])].some((operation) => + operation.startsWith('screenRecording'), + ) + ? await runtime.bindDevice(device, use) + : await mockBindDeviceRuntime(device, use); + const shared = { + host: createTestHostEnvironment({ cwd: root, env: {} }), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + platformResourceCleanup, + sessionStore, + bindDevice, + bindExactDevice: runtime.bindExactDevice, + screenRecordingAdmissionLedger: createScreenRecordingAdmissionLedger(), + throwIfCanceled: () => {}, + logPath: path.join(root, 'daemon.log'), + }; + + const response = await handleSessionCommands({ + ...shared, + req: { + token: 'fixture', + session: 'suite', + command: 'test', + positionals: [script], + flags: { platform: 'android', recordVideo: true }, + meta: { cwd: root, tenantId, clientArtifactPaths: { artifactsDir: clientRoot } }, + internal: { publicNetworkOnly: true }, + }, + sessionName: 'suite', + invoke: async (req) => { + if (req.command === 'open') { + const ref = sessionStore.publish(req.session, makeAndroidSession(req.session)); + req.internal?.onLifetimePublished?.(ref.address, ref.lifetime); + const beforeOpen = await req.internal?.openLifecycle?.beforeDispatch?.(); + if (beforeOpen && !beforeOpen.ok) return beforeOpen; + return { ok: true, data: { session: req.session } }; + } + // The suite's own `close` retires the attempt session on the production route, and its + // teardown is the stop that commits the recording export. + if (req.command === 'close') { + return ( + (await handleSessionCommands({ + ...shared, + req: { ...req, command: 'close', positionals: [], flags: {} }, + sessionName: req.session, + invoke: async () => ({ ok: true, data: {} }), + })) ?? errorResponse('INTERNAL_ERROR', 'The close route answered nothing') + ); + } + return { ok: true, data: { session: req.session } }; + }, + }); + + const data = expectOkData(response); + expect(data.passed).toBe(1); + const outputPath = runtime.start.mock.calls[0]![0].outputPath; + expect(fs.readFileSync(outputPath, 'utf8')).toBe('video-exported-by-script-close'); + const archiveRoot = data.artifacts?.[0]?.path; + expect(archiveRoot).toBeTypeOf('string'); + const archiveRecording = fs + .readdirSync(archiveRoot!, { recursive: true }) + .map(String) + .find((file) => path.basename(file) === 'recording.mp4'); + const inventory = await listDownloadableArtifacts({ tenantId }, {}); + try { + const output = inventory.find((artifact) => artifact.artifactType === 'screen-recording'); + expect(archiveRecording).toBeTypeOf('string'); + expect(fs.readFileSync(path.join(archiveRoot!, archiveRecording!), 'utf8')).toBe( + 'video-exported-by-script-close', + ); + expect(data.recordingArtifacts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + artifactId: output?.id, + path: expect.stringMatching(/client\/.*\/attempt-1\/recording\.mp4$/), + }), + ]), + ); + } finally { + for (const artifact of inventory) cleanupDownloadableArtifact(artifact.id); + } + expect(fs.existsSync(outputPath)).toBe(false); +}); diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 789d2fa0b5b..bc33b4f8143 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -137,6 +137,15 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ return ref && sessionStore.resolveCurrent(ref) ? sessionStore.refresh(ref) : undefined; }; const completed = (name: string) => (attempts.get(name)?.running ? undefined : pinned(name)); + /** + * The attempt's session as cleanup sees it: the live one, or the last ref pinned for it once the + * script's own `close` retired it. A retired ref still names the session's directory and the + * lifetime its committed recording is guarded by, so that export can still join the archive. + */ + const settled = (name: string) => { + const attempt = attempts.get(name); + return attempt?.running ? undefined : (pinned(name) ?? attempt?.ref); + }; const recordingOutputs = new Map(); const video = createReplayTestVideoOwner({ suiteRequest: req, @@ -212,16 +221,19 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ }, }, }); - if (attempt && isRunning(name)) attempt.ref = coordinator.pin(req, name); + // The attempt keeps the newest ref it can pin, and the last one it saw once a script's own + // `close` retires the session: the recording that close committed is still collected later. + const pinnedAfterAction = isRunning(name) ? coordinator.pin(req, name) : undefined; + if (attempt && pinnedAfterAction) attempt.ref = pinnedAfterAction; return result; }, req), dependencies: replayDaemonDependencies, cleanupSession: async (name, artifactPaths) => { - // A timed-out attempt can still hold the lock. Its late cleanup runs after it settles. - const lifetime = completed(name)?.lifetime; + // A timed-out attempt can still hold the lock. Its late cleanup runs after it settles, and a + // script that closed its own session settles it with the attempt's ref already retired. + const lifetime = settled(name)?.lifetime; if (!lifetime) return []; let acquiring = true; - let closingRef: SessionRef | undefined; const closePinned = (signal?: AbortSignal) => withSessionExecutionLock( name, @@ -230,7 +242,6 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ if (ref?.lifetime !== lifetime) return []; await holdDevice(ref.session.device.id); acquiring = false; - closingRef = ref; return await closeReplayTestSession({ host, req, @@ -273,9 +284,14 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ } }; const warnings = await closeWithRetry(); - // Detached cleanup can close the session after the archive has already been published. + // Detached cleanup can reach this point after the archive was already published. A script's + // own `close` retires the session earlier, and its teardown is what commits the recording; + // the attempt's last ref still names the session directory and the guarded lifetime, so the + // export is collected against that ref. + const closed = settled(name); if ( - !closingRef || + !closed || + closed.lifetime !== lifetime || !artifactPaths || !video || !req.flags?.recordVideo || @@ -284,7 +300,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ return warnings; } const { collectSuiteRecordingOutputs } = await import('../recording-outputs.ts'); - const outputs = await collectSuiteRecordingOutputs(sessionStore, closingRef); + const outputs = await collectSuiteRecordingOutputs(sessionStore, closed); if (outputs === null) { return [ ...warnings, From a33ad0d2aced82cb6c03563958e165d3cad87fab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 6 Dec 2026 12:12:54 +0100 Subject: [PATCH 2/2] test(daemon): verify closed-suite recording telemetry delivery --- ...y-command-closed-session-recording.test.ts | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts index bdbfcbac794..16b000fe432 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command-closed-session-recording.test.ts @@ -27,12 +27,13 @@ test('a remote suite delivers the recording its script closed during the attempt const script = path.join(root, 'flow.ad'); fs.writeFileSync(script, 'context platform=android\nopen "Demo"\nclose\n'); const { sessionStore, runtime } = makeRecordRuntimeHarness('suite-recording-script-close-'); + const telemetryContents = JSON.stringify({ gestures: [] }); const finish = runtime.finish.getMockImplementation()!; runtime.finish.mockImplementation(async () => { const finished = await finish(); fs.writeFileSync(finished.result.outPath, 'video-exported-by-script-close'); const telemetryPath = deriveRecordingTelemetryPath(finished.result.outPath); - fs.writeFileSync(telemetryPath, '{}'); + fs.writeFileSync(telemetryPath, telemetryContents); return { ...finished, result: { ...finished.result, telemetryPath } }; }); const platformResourceCleanup = platformResourceCleanupFixture(); @@ -102,25 +103,36 @@ test('a remote suite delivers the recording its script closed during the attempt expect(fs.readFileSync(outputPath, 'utf8')).toBe('video-exported-by-script-close'); const archiveRoot = data.artifacts?.[0]?.path; expect(archiveRoot).toBeTypeOf('string'); - const archiveRecording = fs - .readdirSync(archiveRoot!, { recursive: true }) - .map(String) - .find((file) => path.basename(file) === 'recording.mp4'); + const archivedFiles = fs.readdirSync(archiveRoot!, { recursive: true }).map(String); const inventory = await listDownloadableArtifacts({ tenantId }, {}); try { - const output = inventory.find((artifact) => artifact.artifactType === 'screen-recording'); - expect(archiveRecording).toBeTypeOf('string'); - expect(fs.readFileSync(path.join(archiveRoot!, archiveRecording!), 'utf8')).toBe( - 'video-exported-by-script-close', - ); - expect(data.recordingArtifacts).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - artifactId: output?.id, - path: expect.stringMatching(/client\/.*\/attempt-1\/recording\.mp4$/), - }), - ]), - ); + for (const { name, type, contents } of [ + { + name: 'recording.mp4', + type: 'screen-recording', + contents: 'video-exported-by-script-close', + }, + { + name: 'recording.gesture-telemetry.json', + type: 'screen-recording-telemetry', + contents: telemetryContents, + }, + ]) { + const archivedPath = archivedFiles.find((file) => path.basename(file) === name); + expect(archivedPath).toBeTypeOf('string'); + expect(fs.readFileSync(path.join(archiveRoot!, archivedPath!), 'utf8')).toBe(contents); + + const artifact = inventory.find((entry) => entry.artifactType === type); + expect(artifact?.id).toBeTypeOf('string'); + expect(data.recordingArtifacts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + artifactId: artifact!.id, + path: path.join(clientRoot, path.basename(archiveRoot!), archivedPath!), + }), + ]), + ); + } } finally { for (const artifact of inventory) cleanupDownloadableArtifact(artifact.id); }