Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
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 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, telemetryContents);
return { ...finished, result: { ...finished.result, telemetryPath } };
});
const platformResourceCleanup = platformResourceCleanupFixture();
const tenantId = 'closing-suite';
const clientRoot = path.join(root, 'client');
const bindDevice: NonNullable<Parameters<typeof handleSessionCommands>[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 archivedFiles = fs.readdirSync(archiveRoot!, { recursive: true }).map(String);
const inventory = await listDownloadableArtifacts({ tenantId }, {});
try {
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);
}
expect(fs.existsSync(outputPath)).toBe(false);
});
32 changes: 24 additions & 8 deletions packages/daemon/src/sessions/handlers/session-replay-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ReplaySuiteRecordingArtifact>();
const video = createReplayTestVideoOwner({
suiteRequest: req,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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 ||
Expand All @@ -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,
Expand Down
Loading