Skip to content

Commit fa96af6

Browse files
authored
fix(daemon): keep a recording downloadable when its lease ends (#3955)
* fix(daemon): keep a recording downloadable when its lease ends Lease-end teardown finished an active recording but dropped the completion, so a remote caller's export stayed in the daemon temp directory with no artifact id: the client's later record stop failed with the lease gone and the files leaked. - A leased session's teardown (lease expiry, release, or close) registers a committed remote-temp export and its telemetry as downloadable artifacts of the lease's tenant, with the standard delete-after-download and 15-minute expiry. If registration fails, it deletes the files. A failed finish keeps its forced cleanup and registers nothing. - The /artifacts inventory carries an optional public sessionName so clients sharing a tenant can find their own recording. - trackDownloadableArtifact returns the entry that already tracks a file for the same tenant unchanged, so a record stop replay serves the same ids instead of two ids racing to delete one file. - record stop artifacts are built in one place for the reply and the teardown. Lease-end half of #2281. * fix(daemon): load leased recording retention on demand - session-teardown.ts imports the retention module only when the session holds a lease, so the daemon entry keeps its merge-base eager closure (eager-closure-budgets, which failed the Coverage job). - The registration-failure rollback removes each file best-effort, so one failed removal does not leak the rest. - The unleased-teardown test also checks the tenant inventory. - Docs: ADR 0007 names close as a teardown that keeps the recording, ADR 0024 scopes forced cleanup to the teardown finish, and the remote-proxy sessionName wording matches the contract.
1 parent 8708b48 commit fa96af6

14 files changed

Lines changed: 482 additions & 28 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'agent-device': patch
3+
---
4+
5+
Keep a remote recording downloadable when its leased session ends mid-recording (lease expiry, release, or `close`). Teardown finishes the recording and registers the video and gesture telemetry as downloadable artifacts of the lease's tenant, instead of leaving them unreachable in the daemon's temp directory. `GET /artifacts` entries now carry an optional `sessionName` for such artifacts. A later `record stop` replay returns the same artifact ids.

‎docs/adr/0007-remote-device-leases.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Idle reap then shuts the daemon down within one more idle window.
7676

7777
A session cannot outlive the lease under which it was opened.
7878
When the lease is released or expires, the daemon tears the session down under its execution locks and clears its device claim.
79+
Any teardown of a leased session, including `close`, finishes an active recording. A finished export at a remote temp path then belongs to the lease's tenant as a downloadable artifact, like the artifact of any `record stop` (ADR 0024 2.5).
7980
This applies even when the device no longer answers.
8081
A release is a tenant `lease_release` or a host `DELETE /admin/leases/<lease-id>`.
8182
The daemon sweeps for expired leases every second.

‎docs/adr/0024-screen-recording-provable-signal.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,12 @@ Artifact cleanup is a separate, explicit decision (rule 6).
342342
Session teardown and failed-start rollback dispose through the backend under the fence.
343343
They do this only after the manifest records that no recoverable export is lost.
344344

345+
A leased session's teardown that commits an export at a remote temp path registers it, and its telemetry, as downloadable artifacts of the lease's tenant (rule 1, #2281).
346+
The inventory names the session, and the usual delete-after-download and 15-minute expiry apply.
347+
A later `record stop` replay of that manifest serves the same artifact ids.
348+
If registration fails, teardown deletes the files.
349+
A failed teardown finish still runs forced cleanup (disposal intent) and registers nothing.
350+
345351
### 2.6 Native markers
346352

347353
These markers cover the windows between the spawn of a native recorder and the publication of the manifest that names it:

‎packages/contracts/src/cloud-artifacts.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ export type DaemonArtifactInventoryEntry = {
4848
expiresAt: string;
4949
/** Display rotation a screenshot was rendered in; absent when the capture reported none. */
5050
displayRotation?: DeviceRotation;
51+
/**
52+
* Public name of the session that produced the artifact, without a tenant prefix. Present on an
53+
* artifact the daemon registered outside a request reply, such as a recording kept when its
54+
* leased session was torn down.
55+
*/
56+
sessionName?: string;
5157
};
5258

5359
export type DaemonArtifactsResult = {

‎packages/daemon/src/core/session-tenant-scope.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ export function tenantScopedSessionName(tenant: string, session: string): string
4141
return isTenantOwnedSessionName(tenant, session) ? session : `${tenant}:${session}`;
4242
}
4343

44+
/** The tenant-relative name that addresses this session under tenant scoping. */
45+
export function tenantPublicSessionName(tenant: string, session: string): string {
46+
return isTenantOwnedSessionName(tenant, session) ? session.slice(tenant.length + 1) : session;
47+
}
48+
4449
/**
4550
* Whether a caller in `namespace` may address `sessionName` by name — the read
4651
* counterpart of `scopeRequestSession`'s naming decision, and the only tenant

‎packages/daemon/src/resources/artifact-tracking.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,25 @@ test('disposing a runtime removes the temporary files it still tracks', () => {
2727
expect(fs.existsSync(uploadDir)).toBe(false);
2828
expect(fs.existsSync(artifactPath)).toBe(false);
2929
});
30+
31+
test('a file tracked twice for one tenant keeps one id, and another tenant gets its own', () => {
32+
const root = mkdtempForTestSync('agent-device-artifact-reuse-');
33+
const artifactPath = path.join(root, 'recording.mp4');
34+
fs.writeFileSync(artifactPath, 'video');
35+
const runtime = createRuntimeStateHandle();
36+
37+
const [first, again, otherTenant] = runtime.run(() => {
38+
const track = (tenantId: string) =>
39+
trackDownloadableArtifact({
40+
artifactPath,
41+
tenantId,
42+
artifactType: 'screen-recording',
43+
fileName: 'recording.mp4',
44+
});
45+
return [track('tenant-a'), track('tenant-a'), track('tenant-b')];
46+
});
47+
runtime.dispose();
48+
49+
expect(again).toBe(first);
50+
expect(otherTenant).not.toBe(first);
51+
});

‎packages/daemon/src/resources/artifact-tracking.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ type ArtifactEntry = {
3838
artifactType: DaemonArtifactType | undefined;
3939
fileName?: string;
4040
displayRotation?: DeviceRotation;
41+
sessionName?: string;
4142
deleteAfterDownload: boolean;
4243
createdAt: number;
4344
directoryArchive?: DirectoryArchive;
@@ -77,6 +78,8 @@ export type DownloadableArtifactRegistration = {
7778
artifactType: DaemonArtifactType | undefined;
7879
fileName?: string;
7980
displayRotation?: DeviceRotation;
81+
/** Public session name, for an artifact registered outside a request reply. */
82+
sessionName?: string;
8083
};
8184

8285
export type TrackDownloadableArtifact = (registration: DownloadableArtifactRegistration) => string;
@@ -88,9 +91,16 @@ export type PreparedDownloadableArtifact = {
8891
sizeBytes: number;
8992
};
9093

94+
/**
95+
* Registers one file for download and returns its id. A file the same tenant can already download
96+
* returns its existing entry unchanged: two ids for one file would each delete it after their own
97+
* download.
98+
*/
9199
export function trackDownloadableArtifact(
92100
params: DownloadableArtifactRegistration & { deleteAfterDownload?: boolean },
93101
): string {
102+
const existingId = findTrackedArtifactId(params.artifactPath, params.tenantId);
103+
if (existingId) return existingId;
94104
const artifactId = crypto.randomUUID();
95105
const createdAt = Date.now();
96106
const timer = setTimeout(() => {
@@ -103,13 +113,24 @@ export function trackDownloadableArtifact(
103113
artifactType: params.artifactType,
104114
fileName: params.fileName,
105115
...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}),
116+
...(params.sessionName !== undefined ? { sessionName: params.sessionName } : {}),
106117
deleteAfterDownload: params.deleteAfterDownload !== false,
107118
createdAt,
108119
timer,
109120
});
110121
return artifactId;
111122
}
112123

124+
function findTrackedArtifactId(
125+
artifactPath: string,
126+
tenantId: string | undefined,
127+
): string | undefined {
128+
for (const [artifactId, entry] of pendingArtifacts()) {
129+
if (entry.artifactPath === artifactPath && entry.tenantId === tenantId) return artifactId;
130+
}
131+
return undefined;
132+
}
133+
113134
export async function prepareDownloadableArtifact(
114135
artifactId: string,
115136
tenantId: string | undefined,
@@ -151,6 +172,7 @@ export async function listDownloadableArtifacts(
151172
createdAt: new Date(entry.createdAt).toISOString(),
152173
expiresAt: new Date(entry.createdAt + ARTIFACT_CLEANUP_TIMEOUT_MS).toISOString(),
153174
...(entry.displayRotation !== undefined ? { displayRotation: entry.displayRotation } : {}),
175+
...(entry.sessionName !== undefined ? { sessionName: entry.sessionName } : {}),
154176
});
155177
}
156178
return artifacts;

0 commit comments

Comments
 (0)