From d7b2350866de48ec17dba50e50c45948b49e6b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 10:22:11 +0100 Subject: [PATCH 01/12] fix(daemon): defer artifact cleanup until active downloads close --- .../daemon/src/resources/artifact-tracking.ts | 71 +++++++---- .../server/downloadable-artifact-http.test.ts | 118 ++++++++++++++++++ .../src/server/downloadable-artifact-http.ts | 9 +- website/docs/docs/remote-proxy.md | 3 + 4 files changed, 175 insertions(+), 26 deletions(-) create mode 100644 packages/daemon/src/server/downloadable-artifact-http.test.ts diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 16db460766..61c7665cc0 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -43,6 +43,8 @@ type ArtifactEntry = { createdAt: number; directoryArchive?: DirectoryArchive; directoryArchivePromise?: Promise; + activeDownloads: number; + cleanupRequested: boolean; timer: ReturnType; }; @@ -57,10 +59,8 @@ const artifactTracking = (): ArtifactTrackingState => ARTIFACT_TRACKING_SLOT, (): ArtifactTrackingState => ({ artifacts: new Map(), uploads: new Map() }), (state) => { - for (const entry of state.artifacts.values()) { - clearTimeout(entry.timer); - cleanupDirectoryArchive(entry); - if (entry.deleteAfterDownload) removeBestEffort(entry.artifactPath); + for (const [id, entry] of state.artifacts) { + requestArtifactCleanup(state.artifacts, id, entry); } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); @@ -85,7 +85,7 @@ export type DownloadableArtifactRegistration = { export type TrackDownloadableArtifact = (registration: DownloadableArtifactRegistration) => string; -export type PreparedDownloadableArtifact = { +type PreparedDownloadableArtifact = { artifactPath: string; fileName?: string; mimeType: string; @@ -114,6 +114,8 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), ...(params.sessionName !== undefined ? { sessionName: params.sessionName } : {}), deleteAfterDownload: params.deleteAfterDownload !== false, + activeDownloads: 0, + cleanupRequested: false, createdAt, timer, }); @@ -130,20 +132,33 @@ function findTrackedArtifactId( return undefined; } -export async function prepareDownloadableArtifact( +export async function openDownloadableArtifact( artifactId: string, tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, -): Promise { +): Promise { + const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); - const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); - if (!payload) { - throw new AppError( - 'COMMAND_FAILED', - `Artifact path is not a regular file or directory: ${entry.artifactPath}`, - ); + entry.activeDownloads += 1; + const release = () => { + entry.activeDownloads -= 1; + if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); + }; + try { + const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + if (!payload) { + throw new AppError( + 'COMMAND_FAILED', + `Artifact path is not a regular file or directory: ${entry.artifactPath}`, + ); + } + const stream = fs.createReadStream(payload.artifactPath); + stream.once('close', release); + return { ...payload, stream }; + } catch (error) { + release(); + throw error; } - return payload; } export async function listDownloadableArtifacts( @@ -161,7 +176,7 @@ export async function listDownloadableArtifacts( continue; } const payload = await prepareArtifactPayloadForInventory(id, entry, stat, hostEnv); - if (!payload) continue; + if (!payload || entry.cleanupRequested) continue; artifacts.push({ id, ...(entry.artifactType !== undefined ? { artifactType: entry.artifactType } : {}), @@ -201,6 +216,9 @@ function readDownloadableArtifactEntry( tenantId, DOWNLOADABLE_ARTIFACT_RESOURCE, ); + if (entry.cleanupRequested) { + throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); + } let stat: fs.Stats; try { stat = fs.statSync(entry.artifactPath); @@ -299,9 +317,8 @@ async function createDirectoryArchive( fileName, sizeBytes: fs.statSync(archivePath).size, }; - // The artifact may be consumed or expire while tar is still archiving. - if (pendingArtifacts().get(artifactId) !== entry) { - fs.rmSync(tempDir, { recursive: true, force: true }); + // Inventory can expire while tar is still archiving. + if (entry.cleanupRequested && entry.activeDownloads === 0) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } entry.directoryArchive = archive; @@ -325,8 +342,7 @@ function archiveFilename(fileName: string): string { } function canReadArtifact(entry: ArtifactEntry, tenantId: string | undefined): boolean { - if (!entry.tenantId) return true; - return entry.tenantId === tenantId; + return !entry.cleanupRequested && (!entry.tenantId || entry.tenantId === tenantId); } function safeArtifactFilename(fileName: string | undefined, fallback: string): string { @@ -345,10 +361,21 @@ function hasUnsafeFilenameCharacter(fileName: string): boolean { } export function cleanupDownloadableArtifact(artifactId: string): void { - const entry = pendingArtifacts().get(artifactId); + const artifacts = pendingArtifacts(); + const entry = artifacts.get(artifactId); if (!entry) return; + requestArtifactCleanup(artifacts, artifactId, entry); +} + +function requestArtifactCleanup( + artifacts: Map, + artifactId: string, + entry: ArtifactEntry, +): void { + entry.cleanupRequested = true; clearTimeout(entry.timer); - pendingArtifacts().delete(artifactId); + if (entry.activeDownloads > 0 || artifacts.get(artifactId) !== entry) return; + artifacts.delete(artifactId); cleanupDirectoryArchive(entry); if (entry.deleteAfterDownload) removeBestEffort(entry.artifactPath); } diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts new file mode 100644 index 0000000000..187794a992 --- /dev/null +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -0,0 +1,118 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { runCmdSync } from '@agent-device/host-kit/command'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { trackDownloadableArtifact } from '../resources/artifact-tracking.ts'; +import { createDaemonHttpServer } from './http/http-server.ts'; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +test.each(['another download completes', 'expiry fires'] as const)( + 'a directory download keeps its archive until its delayed file open finishes when %s', + async (trigger) => { + const root = mkdtempForTestSync('fu-art-download-'); + const source = path.join(root, 'profile.trace'); + fs.mkdirSync(source); + const expected = crypto.randomBytes(64 * 1024).toString('hex'); + fs.writeFileSync(path.join(source, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + const headers = { authorization: 'Bearer fu-art-secret' }; + const timer = vi.spyOn(globalThis, 'setTimeout'); + const artifactId = runtime.run(() => + trackDownloadableArtifact({ + artifactPath: source, + artifactType: 'trace-log', + }), + ); + const expire = timer.mock.calls[0]![0]; + timer.mockRestore(); + const url = `http://127.0.0.1:${port}/artifacts/${artifactId}`; + const opened = deferred(); + const release = deferred(); + const createReadStream = fs.createReadStream; + const cleanup = vi.spyOn(fs, 'rmSync'); + let archivePath = ''; + const streams: fs.ReadStream[] = []; + const spy = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => { + archivePath = String(file); + const stream = createReadStream(file, { + ...(typeof options === 'object' ? options : {}), + fs: { + ...fs, + open: (filePath, flags, mode, callback) => { + opened.resolve(); + void release.promise.then(() => fs.open(filePath, flags, mode, callback)); + }, + }, + }); + streams.push(stream); + return stream; + }); + const download = () => + fetch(url, { headers }).then(async (response) => { + if (response.status !== 200) { + await response.body?.cancel(); + return { status: response.status, bytes: Buffer.alloc(0) }; + } + return { status: response.status, bytes: Buffer.from(await response.arrayBuffer()) }; + }); + const pending = download(); + try { + await opened.promise; + spy.mockRestore(); + let first: Awaited> | undefined; + if (trigger === 'another download completes') { + first = await download(); + expect(first.status).toBe(200); + } else { + runtime.run(expire); + } + const archiveDir = path.dirname(archivePath); + expect(fs.existsSync(archivePath)).toBe(true); + expect(fs.existsSync(source)).toBe(true); + expect((await fetch(url, { headers })).status).toBe(404); + const inventory = await fetch(`http://127.0.0.1:${port}/artifacts`, { headers }); + expect(await inventory.json()).toEqual({ artifacts: [] }); + release.resolve(); + const delayed = await pending; + expect(delayed.status).toBe(200); + if (first) expect(delayed.bytes).toEqual(first.bytes); + const downloaded = path.join(root, 'download.tar.gz'); + fs.writeFileSync(downloaded, delayed.bytes); + expect(runCmdSync('tar', ['-xOzf', downloaded, 'profile.trace/payload']).stdout).toBe( + expected, + ); + await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false)); + expect(fs.existsSync(source)).toBe(false); + for (const target of [source, archiveDir]) { + expect(cleanup.mock.calls.filter(([removed]) => removed === target)).toHaveLength(1); + } + } finally { + release.resolve(); + spy.mockRestore(); + cleanup.mockRestore(); + for (const stream of streams) stream.destroy(); + await Promise.allSettled([pending]); + await closeLoopbackServer(server); + runtime.dispose(); + } + }, +); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 854afe1a5a..5df1ab0550 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -1,11 +1,10 @@ -import fs from 'node:fs'; import http from 'node:http'; import { normalizeError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, - prepareDownloadableArtifact, + openDownloadableArtifact, } from '../resources/artifact-tracking.ts'; import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; @@ -92,9 +91,9 @@ async function handleArtifactDownload( }); if (!auth) return; - const artifact = await prepareDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); + const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); const retainArtifactAfterDownload = options.retainArtifacts === true; - const stream = fs.createReadStream(artifact.artifactPath); + const { stream } = artifact; res.statusCode = 200; res.setHeader('content-type', artifact.mimeType); res.setHeader('content-length', String(artifact.sizeBytes)); @@ -124,10 +123,12 @@ async function handleArtifactDownload( stream.on('end', cleanupCompletedDownload); res.on('finish', cleanupCompletedDownload); res.on('close', () => { + stream.destroy(); if (res.writableFinished) { cleanupCompletedDownload(); } }); + if (res.destroyed) stream.destroy(); stream.pipe(res); } catch (error) { sendRestJsonError(res, normalizeError(error)); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 18975a9141..3179b94f61 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -84,6 +84,9 @@ the daemon. When you specify an output path through the CLI, SDK, or MCP, it sel destination on your machine. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. +Artifacts leave the inventory after download or after 15 minutes. Downloads already in progress +can finish before their files are removed, including overlapping downloads of a directory archive. + Remote requests ignore `meta.cwd`. They refuse host tooling paths, `--launch-console`, and script publication with reason `REMOTE_HOST_INPUT_DENIED`. They also refuse daemon host paths as `install` and `reinstall` binaries, `push` payload files, and xctrace template files. Upload binaries with the From b3d9ee5b16d24c30fa6d7960372183726888a81b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 11:01:46 +0100 Subject: [PATCH 02/12] fix(daemon): close artifact streams when HTTP setup fails --- .../server/downloadable-artifact-http.test.ts | 52 +++++++++++++++++++ .../src/server/downloadable-artifact-http.ts | 9 ++-- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index 187794a992..392da88835 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -16,6 +16,58 @@ function deferred() { return { promise, resolve }; } +test('a directory artifact expires after download header setup throws', async () => { + const root = mkdtempForTestSync('fu-art-header-error-'); + const source = path.join(root, 'profile.trace'); + fs.mkdirSync(source); + fs.writeFileSync(path.join(source, 'payload'), 'trace payload'); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + const timer = vi.spyOn(globalThis, 'setTimeout'); + const artifactId = runtime.run(() => + trackDownloadableArtifact({ + artifactPath: source, + artifactType: 'trace-log', + fileName: 'trace-💥', + }), + ); + const expire = timer.mock.calls[0]![0]; + timer.mockRestore(); + const streams = vi.spyOn(fs, 'createReadStream'); + try { + const response = await fetch(`http://127.0.0.1:${port}/artifacts/${artifactId}`, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(500); + await response.body?.cancel(); + const stream = streams.mock.results[0]!.value as fs.ReadStream; + const archiveDir = path.dirname(String(stream.path)); + runtime.run(expire); + await vi.waitFor(() => expect(fs.existsSync(source)).toBe(false)); + expect(stream.closed).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(false); + } finally { + for (const result of streams.mock.results) { + const stream = result.value as fs.ReadStream; + if (stream.closed) continue; + const closed = new Promise((resolve) => stream.once('close', resolve)); + stream.destroy(); + await closed; + } + streams.mockRestore(); + await closeLoopbackServer(server); + runtime.dispose(); + } +}); + test.each(['another download completes', 'expiry fires'] as const)( 'a directory download keeps its archive until its delayed file open finishes when %s', async (trigger) => { diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 5df1ab0550..15b805c4c1 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -80,6 +80,7 @@ async function handleArtifactDownload( return; } + let acquiredStream: { destroy(): void } | undefined; try { const auth = await authorize({ req, @@ -94,6 +95,10 @@ async function handleArtifactDownload( const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); const retainArtifactAfterDownload = options.retainArtifacts === true; const { stream } = artifact; + acquiredStream = stream; + stream.on('error', (error) => { + failStreamedHttpResponse(res, error); + }); res.statusCode = 200; res.setHeader('content-type', artifact.mimeType); res.setHeader('content-length', String(artifact.sizeBytes)); @@ -103,9 +108,6 @@ async function handleArtifactDownload( `attachment; filename="${artifact.fileName.replace(/"/g, '')}"`, ); } - stream.on('error', (error) => { - failStreamedHttpResponse(res, error); - }); let didCleanupArtifact = false; const cleanupCompletedDownload = () => { if (didCleanupArtifact || retainArtifactAfterDownload) return; @@ -131,6 +133,7 @@ async function handleArtifactDownload( if (res.destroyed) stream.destroy(); stream.pipe(res); } catch (error) { + acquiredStream?.destroy(); sendRestJsonError(res, normalizeError(error)); } } From a6afbed03a8cb4fce3668cec7c3bbf4ce570ea17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 11:05:57 +0100 Subject: [PATCH 03/12] chore(gates): record artifact download wire compatibility --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 7eb63460e7..b4f41e8808 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:9f51e86c19cd4f5d8097f1c5ce38dc1daa795b803a6afc89d16cd556371ea037", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:dada24ddd55e0852300cab779f69ba3f742940346f9b6c3478fc04346ae66c3e", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:9f51e86c19cd4f5d8097f1c5ce38dc1daa795b803a6afc89d16cd556371ea037", - "rationale": "#3753 threads the daemon runtime's host environment into the directory-archive spawn instead of the module reading process.env. Request parsing, authorization, response framing, headers, and cleanup are unchanged; no peer-visible field moves." + "digest": "sha256:dada24ddd55e0852300cab779f69ba3f742940346f9b6c3478fc04346ae66c3e", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 holds reader ownership through stream close, defers cleanup while readers remain, and destroys the acquired stream if HTTP setup throws. Request parsing, authorization, status codes, response headers, error JSON, and archive framing are unchanged, so released peers parse the same payloads." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", From 0e526615e5bcdf570a9dca908824623aff1f1580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 11:16:11 +0100 Subject: [PATCH 04/12] fix(daemon): close artifact readers before response completion --- .../src/server/downloadable-artifact-http.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 15b805c4c1..f3434ba3ec 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -1,3 +1,4 @@ +import type { ReadStream } from 'node:fs'; import http from 'node:http'; import { normalizeError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; @@ -131,13 +132,26 @@ async function handleArtifactDownload( } }); if (res.destroyed) stream.destroy(); - stream.pipe(res); + pipeArtifactDownload(stream, res); } catch (error) { acquiredStream?.destroy(); sendRestJsonError(res, normalizeError(error)); } } +function pipeArtifactDownload(stream: ReadStream, res: http.ServerResponse): void { + // The owner releases its reader on close; Content-Length must not let the client finish sooner. + let lastChunk: string | Buffer | undefined; + stream.on('data', (chunk: string | Buffer) => { + if (lastChunk !== undefined && !res.write(lastChunk)) stream.pause(); + lastChunk = chunk; + }); + res.on('drain', () => stream.resume()); + stream.once('close', () => { + if (stream.readableEnded) res.end(lastChunk); + }); +} + async function handleArtifactInventory( req: http.IncomingMessage, res: http.ServerResponse, From 56cf7bb7389fd112fbd97ef4591e2b8cc6e95d54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 11:16:11 +0100 Subject: [PATCH 05/12] chore(gates): acknowledge artifact completion ordering --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index b4f41e8808..57ede7e222 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:dada24ddd55e0852300cab779f69ba3f742940346f9b6c3478fc04346ae66c3e", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:a6a1f529093941ca65a57d67af3060001c64c1076c02e66419ccfda2cc9fc590", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:dada24ddd55e0852300cab779f69ba3f742940346f9b6c3478fc04346ae66c3e", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 holds reader ownership through stream close, defers cleanup while readers remain, and destroys the acquired stream if HTTP setup throws. Request parsing, authorization, status codes, response headers, error JSON, and archive framing are unchanged, so released peers parse the same payloads." + "digest": "sha256:a6a1f529093941ca65a57d67af3060001c64c1076c02e66419ccfda2cc9fc590", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 holds reader ownership through stream close, defers cleanup while readers remain, destroys the acquired stream if HTTP setup throws, and holds the final response chunk until the reader closes so cleanup still precedes client completion. Request parsing, authorization, status codes, response headers, error JSON, and archive bytes are unchanged, so released peers parse the same payloads." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", From 4a4caea8c4628844dd1efcd806cecaa288446dfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 11:54:31 +0100 Subject: [PATCH 06/12] fix(daemon): preserve artifact sources across re-registration --- .../src/resources/artifact-tracking.test.ts | 78 ++++++++++++++++++- .../daemon/src/resources/artifact-tracking.ts | 34 +++++++- website/docs/docs/remote-proxy.md | 3 +- 3 files changed, 109 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index c0c013e4f1..f3600372f8 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -1,9 +1,17 @@ import fs from 'node:fs'; +import { once } from 'node:events'; import path from 'node:path'; +import { buffer } from 'node:stream/consumers'; +import { gunzipSync } from 'node:zlib'; import { expect, test } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; -import { trackDownloadableArtifact, trackUploadedArtifact } from './artifact-tracking.ts'; +import { + cleanupDownloadableArtifact, + openDownloadableArtifact, + trackDownloadableArtifact, + trackUploadedArtifact, +} from './artifact-tracking.ts'; test('disposing a runtime removes the temporary files it still tracks', () => { const root = mkdtempForTestSync('agent-device-artifact-dispose-'); @@ -49,3 +57,71 @@ test('a file tracked twice for one tenant keeps one id, and another tenant gets expect(again).toBe(first); expect(otherTenant).not.toBe(first); }); + +test.each( + (['old-first', 'new-first'] as const).flatMap((order) => + [true, false].map((deleteAfterDownload) => ({ order, deleteAfterDownload })), + ), +)( + 're-registering a directory during deferred cleanup keeps both downloads alive ($order, deleteAfterDownload=$deleteAfterDownload)', + async ({ order, deleteAfterDownload }) => { + const root = mkdtempForTestSync('fu-art-register-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + const payloadPath = path.join(artifactPath, 'payload'); + fs.writeFileSync(payloadPath, 'original capture marker'); + const runtime = createRuntimeStateHandle(); + const streams: fs.ReadStream[] = []; + const track = (deleteAfterDownload = true) => + runtime.run(() => + trackDownloadableArtifact({ + artifactPath, + artifactType: 'trace-log', + tenantId: 'tenant-a', + deleteAfterDownload, + }), + ); + const open = async (id: string) => { + const artifact = await runtime.run(() => + openDownloadableArtifact(id, 'tenant-a', process.env), + ); + streams.push(artifact.stream); + return artifact.stream; + }; + const read = async (stream: fs.ReadStream, expected: string) => { + const closed = once(stream, 'close'); + const bytes = await buffer(stream); + await closed; + expect(gunzipSync(bytes).includes(Buffer.from(expected))).toBe(true); + expect(fs.existsSync(path.dirname(String(stream.path)))).toBe(false); + }; + try { + const firstId = track(); + const first = await open(firstId); + runtime.run(() => cleanupDownloadableArtifact(firstId)); + fs.writeFileSync(payloadPath, 'replacement capture marker'); + const nextId = track(deleteAfterDownload); + expect(nextId).not.toBe(firstId); + if (order === 'old-first') { + await read(first, 'original capture marker'); + expect(fs.existsSync(artifactPath)).toBe(true); + } + const next = await open(nextId); + runtime.run(() => cleanupDownloadableArtifact(nextId)); + await read(next, 'replacement capture marker'); + if (order === 'new-first') { + expect(fs.existsSync(artifactPath)).toBe(true); + await read(first, 'original capture marker'); + } + expect(fs.existsSync(artifactPath)).toBe(!deleteAfterDownload); + } finally { + for (const stream of streams) { + if (stream.closed) continue; + const closed = once(stream, 'close'); + stream.destroy(); + await closed; + } + runtime.dispose(); + } + }, +); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 61c7665cc0..2fae510f4e 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -32,6 +32,11 @@ type DirectoryArchive = { sizeBytes: number; }; +type ArtifactSourceCleanup = { + remainingEntries: number; + deleteAfterDownload: boolean; +}; + type ArtifactEntry = { artifactPath: string; tenantId?: string; @@ -39,7 +44,7 @@ type ArtifactEntry = { fileName?: string; displayRotation?: DeviceRotation; sessionName?: string; - deleteAfterDownload: boolean; + sourceCleanup: ArtifactSourceCleanup; createdAt: number; directoryArchive?: DirectoryArchive; directoryArchivePromise?: Promise; @@ -106,6 +111,12 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati cleanupDownloadableArtifact(artifactId); }, ARTIFACT_CLEANUP_TIMEOUT_MS); timer.unref(); + const sourceCleanup = findArtifactSourceCleanup(params.artifactPath) ?? { + remainingEntries: 0, + deleteAfterDownload: true, + }; + sourceCleanup.remainingEntries += 1; + sourceCleanup.deleteAfterDownload &&= params.deleteAfterDownload !== false; pendingArtifacts().set(artifactId, { artifactPath: params.artifactPath, tenantId: params.tenantId, @@ -113,7 +124,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati fileName: params.fileName, ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), ...(params.sessionName !== undefined ? { sessionName: params.sessionName } : {}), - deleteAfterDownload: params.deleteAfterDownload !== false, + sourceCleanup, activeDownloads: 0, cleanupRequested: false, createdAt, @@ -127,7 +138,19 @@ function findTrackedArtifactId( tenantId: string | undefined, ): string | undefined { for (const [artifactId, entry] of pendingArtifacts()) { - if (entry.artifactPath === artifactPath && entry.tenantId === tenantId) return artifactId; + if ( + !entry.cleanupRequested && + entry.artifactPath === artifactPath && + entry.tenantId === tenantId + ) + return artifactId; + } + return undefined; +} + +function findArtifactSourceCleanup(artifactPath: string): ArtifactSourceCleanup | undefined { + for (const entry of pendingArtifacts().values()) { + if (entry.artifactPath === artifactPath) return entry.sourceCleanup; } return undefined; } @@ -377,7 +400,10 @@ function requestArtifactCleanup( if (entry.activeDownloads > 0 || artifacts.get(artifactId) !== entry) return; artifacts.delete(artifactId); cleanupDirectoryArchive(entry); - if (entry.deleteAfterDownload) removeBestEffort(entry.artifactPath); + entry.sourceCleanup.remainingEntries -= 1; + if (entry.sourceCleanup.remainingEntries === 0 && entry.sourceCleanup.deleteAfterDownload) { + removeBestEffort(entry.artifactPath); + } } function removeBestEffort(targetPath: string): void { diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 3179b94f61..d44cdb073b 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -84,7 +84,8 @@ the daemon. When you specify an output path through the CLI, SDK, or MCP, it sel destination on your machine. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. -Artifacts leave the inventory after download or after 15 minutes. Downloads already in progress +By default, artifacts leave the inventory after download or after 15 minutes. +`AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. Remote requests ignore `meta.cwd`. They refuse host tooling paths, `--launch-console`, and script From 1d0d58dabf614c22e4b4beb5aa09dee02ef8fbf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 12:18:45 +0100 Subject: [PATCH 07/12] fix(daemon): settle and bound artifact download pipelines --- .../src/resources/artifact-tracking.test.ts | 26 ++- .../daemon/src/resources/artifact-tracking.ts | 79 ++++++- .../server/downloadable-artifact-http.test.ts | 210 +++++++++++++++++- .../src/server/downloadable-artifact-http.ts | 106 +++++---- .../http/http-server-remote-output.test.ts | 12 +- website/docs/docs/remote-proxy.md | 2 + 6 files changed, 352 insertions(+), 83 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index f3600372f8..11cf95af54 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -11,6 +11,7 @@ import { openDownloadableArtifact, trackDownloadableArtifact, trackUploadedArtifact, + type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; test('disposing a runtime removes the temporary files it still tracks', () => { @@ -71,7 +72,7 @@ test.each( const payloadPath = path.join(artifactPath, 'payload'); fs.writeFileSync(payloadPath, 'original capture marker'); const runtime = createRuntimeStateHandle(); - const streams: fs.ReadStream[] = []; + const downloads: OpenedDownloadableArtifact[] = []; const track = (deleteAfterDownload = true) => runtime.run(() => trackDownloadableArtifact({ @@ -82,16 +83,19 @@ test.each( }), ); const open = async (id: string) => { - const artifact = await runtime.run(() => + const artifact: OpenedDownloadableArtifact = await runtime.run(() => openDownloadableArtifact(id, 'tenant-a', process.env), ); - streams.push(artifact.stream); - return artifact.stream; + downloads.push(artifact); + return artifact; }; - const read = async (stream: fs.ReadStream, expected: string) => { + const read = async (download: OpenedDownloadableArtifact, expected: string) => { + const { stream } = download; const closed = once(stream, 'close'); const bytes = await buffer(stream); await closed; + download.release(); + download.release(); expect(gunzipSync(bytes).includes(Buffer.from(expected))).toBe(true); expect(fs.existsSync(path.dirname(String(stream.path)))).toBe(false); }; @@ -115,11 +119,13 @@ test.each( } expect(fs.existsSync(artifactPath)).toBe(!deleteAfterDownload); } finally { - for (const stream of streams) { - if (stream.closed) continue; - const closed = once(stream, 'close'); - stream.destroy(); - await closed; + for (const download of downloads) { + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); } runtime.dispose(); } diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 2fae510f4e..89c94abc9d 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -3,6 +3,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; +import { finished } from 'node:stream/promises'; import { AppError } from '@agent-device/kernel/errors'; import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; @@ -17,6 +18,7 @@ import { // --- Downloadable artifact tracking --- const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; +const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; const DOWNLOADABLE_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { label: 'Artifact', @@ -37,6 +39,12 @@ type ArtifactSourceCleanup = { deleteAfterDownload: boolean; }; +type ArtifactDownload = { + controller: AbortController; + stream?: fs.ReadStream; + release: () => void; +}; + type ArtifactEntry = { artifactPath: string; tenantId?: string; @@ -48,7 +56,8 @@ type ArtifactEntry = { createdAt: number; directoryArchive?: DirectoryArchive; directoryArchivePromise?: Promise; - activeDownloads: number; + archiveAbortController?: AbortController; + activeDownloads: Set; cleanupRequested: boolean; timer: ReturnType; }; @@ -66,6 +75,7 @@ const artifactTracking = (): ArtifactTrackingState => (state) => { for (const [id, entry] of state.artifacts) { requestArtifactCleanup(state.artifacts, id, entry); + for (const download of entry.activeDownloads) cancelArtifactDownload(id, entry, download); } for (const entry of state.uploads.values()) { clearTimeout(entry.timer); @@ -97,6 +107,13 @@ type PreparedDownloadableArtifact = { sizeBytes: number; }; +export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { + stream: fs.ReadStream; + signal: AbortSignal; + /** Release ownership after the download pipeline settles, including failure. */ + release: () => void; +}; + /** * Registers one file for download and returns its id. A file the same tenant can already download * returns its existing entry unchanged: two ids for one file would each delete it after their own @@ -125,7 +142,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati ...(params.displayRotation !== undefined ? { displayRotation: params.displayRotation } : {}), ...(params.sessionName !== undefined ? { sessionName: params.sessionName } : {}), sourceCleanup, - activeDownloads: 0, + activeDownloads: new Set(), cleanupRequested: false, createdAt, timer, @@ -159,16 +176,26 @@ export async function openDownloadableArtifact( artifactId: string, tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, -): Promise { +): Promise { const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); - entry.activeDownloads += 1; - const release = () => { - entry.activeDownloads -= 1; - if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); + const download: ArtifactDownload = { + controller: new AbortController(), + release: () => { + if (!entry.activeDownloads.delete(download)) return; + clearTimeout(deadline); + if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); + }, }; + entry.activeDownloads.add(download); + const deadline = setTimeout( + () => cancelArtifactDownload(artifactId, entry, download), + ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, + ); + deadline.unref(); try { const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + download.controller.signal.throwIfAborted(); if (!payload) { throw new AppError( 'COMMAND_FAILED', @@ -176,14 +203,31 @@ export async function openDownloadableArtifact( ); } const stream = fs.createReadStream(payload.artifactPath); - stream.once('close', release); - return { ...payload, stream }; + download.stream = stream; + return { ...payload, stream, signal: download.controller.signal, release: download.release }; } catch (error) { - release(); + download.release(); throw error; } } +function cancelArtifactDownload( + artifactId: string, + entry: ArtifactEntry, + download: ArtifactDownload, +): void { + if (!entry.activeDownloads.has(download)) return; + const reason = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); + download.controller.abort(reason); + if (!download.stream) { + entry.archiveAbortController?.abort(reason); + return; + } + const closed = finished(download.stream, { cleanup: true }).catch(() => {}); + download.stream.destroy(); + void closed.then(download.release); +} + export async function listDownloadableArtifacts( tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, @@ -316,6 +360,8 @@ async function createDirectoryArchive( path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), ); const archivePath = path.join(tempDir, fileName); + const controller = new AbortController(); + entry.archiveAbortController = controller; try { await runCmd( 'tar', @@ -328,12 +374,15 @@ async function createDirectoryArchive( path.basename(entry.artifactPath), ], { + signal: controller.signal, + timeoutMs: ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, env: { ...hostEnv, COPYFILE_DISABLE: '1', }, }, ); + controller.signal.throwIfAborted(); const archive = { archivePath, tempDir, @@ -341,13 +390,14 @@ async function createDirectoryArchive( sizeBytes: fs.statSync(archivePath).size, }; // Inventory can expire while tar is still archiving. - if (entry.cleanupRequested && entry.activeDownloads === 0) { + if (entry.cleanupRequested && entry.activeDownloads.size === 0) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } entry.directoryArchive = archive; return archive; } catch (error) { fs.rmSync(tempDir, { recursive: true, force: true }); + if (controller.signal.aborted) throw controller.signal.reason; if (error instanceof AppError) throw error; throw new AppError( 'COMMAND_FAILED', @@ -355,6 +405,8 @@ async function createDirectoryArchive( { artifactPath: entry.artifactPath }, error instanceof Error ? error : undefined, ); + } finally { + if (entry.archiveAbortController === controller) entry.archiveAbortController = undefined; } } @@ -397,7 +449,10 @@ function requestArtifactCleanup( ): void { entry.cleanupRequested = true; clearTimeout(entry.timer); - if (entry.activeDownloads > 0 || artifacts.get(artifactId) !== entry) return; + if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; + entry.archiveAbortController?.abort( + expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), + ); artifacts.delete(artifactId); cleanupDirectoryArchive(entry); entry.sourceCleanup.remainingEntries -= 1; diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index 392da88835..c0615b6638 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; import { expect, test, vi } from 'vitest'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; @@ -16,6 +17,204 @@ function deferred() { return { promise, resolve }; } +type DownloadFixture = { + source: string; + runtime: ReturnType; + streams: fs.ReadStream[]; + start(): void; + abortClient(): void; + failResponse(): void; + outcome(): 'pending' | 'complete' | 'failed'; + cleanupCount(): number; + expire(): void; + fireDeadlines(): void; +}; + +async function withDownloadFixture( + run: (fixture: DownloadFixture) => Promise, + configureStream: (stream: fs.ReadStream) => void, +): Promise { + const root = mkdtempForTestSync('fu-art-pipeline-'); + const source = path.join(root, 'capture.trace'); + fs.mkdirSync(source); + fs.writeFileSync(path.join(source, 'payload'), crypto.randomBytes(256 * 1024)); + const runtime = createRuntimeStateHandle(); + const server = await runtime.run(() => + createDaemonHttpServer({ + token: 'fu-art-secret', + handleRequest: async () => ({ ok: true, data: {} }), + env: process.env, + cwd: process.cwd(), + }), + ); + const port = await listenOnLoopback(server); + let activeResponse: http.ServerResponse | undefined; + server.on('request', (_request, response) => { + activeResponse = response; + }); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log' }), + ); + const expire = timers.mock.calls[0]![0]; + const removed = vi.spyOn(fs, 'rmSync'); + const streams: fs.ReadStream[] = []; + const createReadStream = fs.createReadStream; + const reads = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => { + const stream = createReadStream(file, options); + streams.push(stream); + configureStream(stream); + return stream; + }); + const agent = new http.Agent({ keepAlive: true }); + let request: http.ClientRequest | undefined; + let outcome: 'pending' | 'complete' | 'failed' = 'pending'; + try { + await run({ + source, + runtime, + streams, + start: () => { + request = http.get( + `http://127.0.0.1:${port}/artifacts/${id}`, + { + agent, + headers: { authorization: 'Bearer fu-art-secret' }, + }, + (response) => { + response.on('end', () => { + outcome = 'complete'; + }); + response.on('aborted', () => { + outcome = 'failed'; + }); + response.on('error', () => { + outcome = 'failed'; + }); + response.resume(); + }, + ); + request.on('error', () => { + outcome = 'failed'; + }); + }, + abortClient: () => request?.destroy(), + failResponse: () => activeResponse?.destroy(new Error('injected response failure')), + outcome: () => outcome, + cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, + expire: () => runtime.run(expire), + fireDeadlines: () => { + for (const [index, [callback, delay]] of timers.mock.calls.entries()) { + const handle = timers.mock.results[index]!.value; + if ( + delay !== 15 * 60 * 1000 || + clearedTimers.mock.calls.some(([cleared]) => cleared === handle) + ) + continue; + runtime.run(callback); + } + }, + }); + } finally { + request?.destroy(); + agent.destroy(); + for (const stream of streams) { + if (stream.closed) continue; + const closed = new Promise((resolve) => stream.once('close', resolve)); + stream.destroy(); + await closed; + } + reads.mockRestore(); + timers.mockRestore(); + clearedTimers.mockRestore(); + await closeLoopbackServer(server); + runtime.dispose(); + removed.mockRestore(); + } +} + +test.each(['destroyed', 'truncated', 'errored'] as const)( + 'a %s artifact read terminates the HTTP response', + async (failure) => { + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => { + if (failure === 'truncated') { + stream.once('open', () => + fs.truncateSync(String(stream.path), fs.statSync(String(stream.path)).size - 1), + ); + } else { + let chunks = 0; + stream.on('data', () => { + if (++chunks === 2) + stream.destroy( + failure === 'errored' ? new Error('injected read failure') : undefined, + ); + }); + } + }, + ); + }, +); + +test.each(['deadline', 'runtime disposal'] as const)( + '%s cancels an active download and removes its files', + async (trigger) => { + const started = deferred(); + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await started.promise; + if (trigger === 'deadline') fixture.fireDeadlines(); + else fixture.runtime.dispose(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.streams.every((stream) => stream.closed)).toBe(true); + expect(fixture.cleanupCount()).toBe(1); + for (const stream of fixture.streams) { + expect(fs.existsSync(path.dirname(String(stream.path)))).toBe(false); + } + }, + (stream) => + stream.once('data', () => { + stream.pause(); + started.resolve(); + }), + ); + }, +); + +test.each(['client abort', 'response error'] as const)( + '%s releases an active download before expiry cleanup', + async (failure) => { + const started = deferred(); + await withDownloadFixture( + async (fixture) => { + fixture.start(); + await started.promise; + if (failure === 'client abort') fixture.abortClient(); + else fixture.failResponse(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => + stream.once('data', () => { + stream.pause(); + started.resolve(); + }), + ); + }, +); + test('a directory artifact expires after download header setup throws', async () => { const root = mkdtempForTestSync('fu-art-header-error-'); const source = path.join(root, 'profile.trace'); @@ -42,12 +241,20 @@ test('a directory artifact expires after download header setup throws', async () const expire = timer.mock.calls[0]![0]; timer.mockRestore(); const streams = vi.spyOn(fs, 'createReadStream'); + const controller = new AbortController(); try { const response = await fetch(`http://127.0.0.1:${port}/artifacts/${artifactId}`, { headers: { authorization: 'Bearer fu-art-secret' }, + signal: controller.signal, }); expect(response.status).toBe(500); - await response.body?.cancel(); + let body: unknown; + const consumed = response.json().then((value: unknown) => { + body = value; + }); + void consumed.catch(() => {}); + await vi.waitFor(() => expect(body).toMatchObject({ ok: false })); + await consumed; const stream = streams.mock.results[0]!.value as fs.ReadStream; const archiveDir = path.dirname(String(stream.path)); runtime.run(expire); @@ -55,6 +262,7 @@ test('a directory artifact expires after download header setup throws', async () expect(stream.closed).toBe(true); expect(fs.existsSync(archiveDir)).toBe(false); } finally { + controller.abort(); for (const result of streams.mock.results) { const stream = result.value as fs.ReadStream; if (stream.closed) continue; diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index f3434ba3ec..15cce2fd2a 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -1,13 +1,14 @@ -import type { ReadStream } from 'node:fs'; import http from 'node:http'; -import { normalizeError } from '@agent-device/kernel/errors'; +import { Transform } from 'node:stream'; +import { finished, pipeline } from 'node:stream/promises'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { DaemonRequest } from '../core/daemon-request.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, openDownloadableArtifact, } from '../resources/artifact-tracking.ts'; -import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; +import { sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; type DownloadableArtifactHttpRoute = @@ -81,7 +82,6 @@ async function handleArtifactDownload( return; } - let acquiredStream: { destroy(): void } | undefined; try { const auth = await authorize({ req, @@ -94,64 +94,60 @@ async function handleArtifactDownload( if (!auth) return; const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); - const retainArtifactAfterDownload = options.retainArtifacts === true; const { stream } = artifact; - acquiredStream = stream; - stream.on('error', (error) => { - failStreamedHttpResponse(res, error); - }); - res.statusCode = 200; - res.setHeader('content-type', artifact.mimeType); - res.setHeader('content-length', String(artifact.sizeBytes)); - if (artifact.fileName) { - res.setHeader( - 'content-disposition', - `attachment; filename="${artifact.fileName.replace(/"/g, '')}"`, - ); - } - let didCleanupArtifact = false; - const cleanupCompletedDownload = () => { - if (didCleanupArtifact || retainArtifactAfterDownload) return; - didCleanupArtifact = true; - cleanupDownloadableArtifact(artifactId); - }; - // Consume before the final chunk is written to the client: fetch treats a - // download as complete once content-length bytes arrive, which can happen - // before this stream emits 'end' (that needs one more threadpool read). - let bytesSent = 0; - stream.on('data', (chunk: string | Buffer) => { - bytesSent += chunk.length; - if (bytesSent >= artifact.sizeBytes) cleanupCompletedDownload(); - }); - stream.on('end', cleanupCompletedDownload); - res.on('finish', cleanupCompletedDownload); - res.on('close', () => { - stream.destroy(); - if (res.writableFinished) { - cleanupCompletedDownload(); + const closed = finished(stream, { cleanup: true }).catch(() => {}); + try { + res.statusCode = 200; + res.setHeader('content-type', artifact.mimeType); + res.setHeader('content-length', String(artifact.sizeBytes)); + if (artifact.fileName) { + res.setHeader( + 'content-disposition', + `attachment; filename="${artifact.fileName.replace(/"/g, '')}"`, + ); } - }); - if (res.destroyed) stream.destroy(); - pipeArtifactDownload(stream, res); + let bytesRead = 0; + const checked = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + bytesRead += chunk.length; + if (bytesRead >= artifact.sizeBytes && options.retainArtifacts !== true) { + cleanupDownloadableArtifact(artifactId); + } + callback(null, chunk); + }, + flush(callback) { + if (bytesRead !== artifact.sizeBytes) { + callback( + new AppError('COMMAND_FAILED', 'Artifact read did not match its declared size', { + reason: 'artifact_size_mismatch', + expectedBytes: artifact.sizeBytes, + actualBytes: bytesRead, + }), + ); + return; + } + if (options.retainArtifacts !== true) cleanupDownloadableArtifact(artifactId); + callback(); + }, + }); + await pipeline(stream, checked, res, { signal: artifact.signal }); + } finally { + stream.destroy(); + await closed; + artifact.release(); + } } catch (error) { - acquiredStream?.destroy(); + if (res.destroyed) return; + if (res.headersSent) { + res.destroy(error instanceof Error ? error : undefined); + return; + } + res.removeHeader('content-length'); + res.removeHeader('content-disposition'); sendRestJsonError(res, normalizeError(error)); } } -function pipeArtifactDownload(stream: ReadStream, res: http.ServerResponse): void { - // The owner releases its reader on close; Content-Length must not let the client finish sooner. - let lastChunk: string | Buffer | undefined; - stream.on('data', (chunk: string | Buffer) => { - if (lastChunk !== undefined && !res.write(lastChunk)) stream.pause(); - lastChunk = chunk; - }); - res.on('drain', () => stream.resume()); - stream.once('close', () => { - if (stream.readableEnded) res.end(lastChunk); - }); -} - async function handleArtifactInventory( req: http.IncomingMessage, res: http.ServerResponse, diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index 5a67b854fb..3762f2e7d1 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -688,7 +688,7 @@ test.each( ); expect(reportDownload.status).toBe(200); expect(await reportDownload.text()).toBe('generated-report'); - } else expect(fs.existsSync(output)).toBe(false); + } else await vi.waitFor(() => expect(fs.existsSync(output)).toBe(false)); }); }, ); @@ -837,7 +837,7 @@ test.each(['./capture.log', undefined])( }); expect(download.status).toBe(200); expect(await download.text()).toContain('generated-trace'); - expect(fs.existsSync(output)).toBe(false); + await vi.waitFor(() => expect(fs.existsSync(output)).toBe(false)); }); }, ); @@ -930,7 +930,7 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(download.status).toBe(200); const archive = gunzipSync(Buffer.from(await download.arrayBuffer())); expect(archive.includes(Buffer.from('tenant-a-private-marker'))).toBe(false); - expect(fs.existsSync(secondPath)).toBe(false); + await vi.waitFor(() => expect(fs.existsSync(secondPath)).toBe(false)); expect(fs.readFileSync(path.join(firstPath, 'private-a.txt'), 'utf8')).toBe( 'tenant-a-private-marker', ); @@ -947,8 +947,10 @@ test('remote suite artifacts belong to fresh tenant/session invocations despite expect(own.status).toBe(200); await own.arrayBuffer(); } - expect(fs.existsSync(firstPath)).toBe(false); - expect(fs.existsSync(registrations[2]!.path)).toBe(false); + await vi.waitFor(() => { + expect(fs.existsSync(firstPath)).toBe(false); + expect(fs.existsSync(registrations[2]!.path)).toBe(false); + }); }, env, ); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index d44cdb073b..c27d1a11f6 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -87,6 +87,8 @@ destination on your machine. Direct RPC callers receive artifact IDs and downloa By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. +Each download has a 15-minute maximum lifetime. When it reaches that limit, the daemon cancels it +and cleans up after its pipeline stops. Remote requests ignore `meta.cwd`. They refuse host tooling paths, `--launch-console`, and script publication with reason `REMOTE_HOST_INPUT_DENIED`. They also refuse daemon host paths as `install` From f401c7d121cff19933aa22ca707c8918b2c08a80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 12:18:45 +0100 Subject: [PATCH 08/12] chore(gates): record bounded artifact pipeline compatibility --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 57ede7e222..5bdc64ce92 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:a6a1f529093941ca65a57d67af3060001c64c1076c02e66419ccfda2cc9fc590", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:15ad1dc0bbdf1a54060836f5fcb2144c45532c9328db4ce1ea2a326e1b88aef2", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:a6a1f529093941ca65a57d67af3060001c64c1076c02e66419ccfda2cc9fc590", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 holds reader ownership through stream close, defers cleanup while readers remain, destroys the acquired stream if HTTP setup throws, and holds the final response chunk until the reader closes so cleanup still precedes client completion. Request parsing, authorization, status codes, response headers, error JSON, and archive bytes are unchanged, so released peers parse the same payloads." + "digest": "sha256:15ad1dc0bbdf1a54060836f5fcb2144c45532c9328db4ce1ea2a326e1b88aef2", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. A setup error clears artifact-only headers before writing the existing JSON error. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", From a74ce4427110f039a410a3c1c24637414ae81859 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 12:44:18 +0100 Subject: [PATCH 09/12] fix(daemon): wait for artifact readiness before HTTP framing --- .../server/downloadable-artifact-http.test.ts | 18 ++++++++++++++++++ .../src/server/downloadable-artifact-http.ts | 4 ++++ 2 files changed, 22 insertions(+) diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index c0615b6638..fc200de553 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -18,6 +18,7 @@ function deferred() { } type DownloadFixture = { + url: string; source: string; runtime: ReturnType; streams: fs.ReadStream[]; @@ -72,6 +73,7 @@ async function withDownloadFixture( let outcome: 'pending' | 'complete' | 'failed' = 'pending'; try { await run({ + url: `http://127.0.0.1:${port}/artifacts/${id}`, source, runtime, streams, @@ -164,6 +166,22 @@ test.each(['destroyed', 'truncated', 'errored'] as const)( }, ); +test('an artifact open failure returns a complete JSON error before streaming starts', async () => { + await withDownloadFixture( + async (fixture) => { + const response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toBe('application/json'); + expect(await response.json()).toMatchObject({ ok: false }); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + }, + (stream) => fs.unlinkSync(String(stream.path)), + ); +}); + test.each(['deadline', 'runtime disposal'] as const)( '%s cancels an active download and removes its files', async (trigger) => { diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 15cce2fd2a..c6b4238783 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -1,4 +1,5 @@ import http from 'node:http'; +import { once } from 'node:events'; import { Transform } from 'node:stream'; import { finished, pipeline } from 'node:stream/promises'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; @@ -97,6 +98,9 @@ async function handleArtifactDownload( const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); try { + artifact.signal.throwIfAborted(); + if (stream.errored) throw stream.errored; + if (stream.pending) await once(stream, 'ready', { signal: artifact.signal }); res.statusCode = 200; res.setHeader('content-type', artifact.mimeType); res.setHeader('content-length', String(artifact.sizeBytes)); From 89f63cbca95dac8f6233825eec389bc4141acdcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 12:44:18 +0100 Subject: [PATCH 10/12] chore(gates): record artifact readiness wire compatibility --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 5bdc64ce92..cb7b48b017 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:15ad1dc0bbdf1a54060836f5fcb2144c45532c9328db4ce1ea2a326e1b88aef2", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:15ad1dc0bbdf1a54060836f5fcb2144c45532c9328db4ce1ea2a326e1b88aef2", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. A setup error clears artifact-only headers before writing the existing JSON error. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field." + "digest": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", From 3a4f1582ae989b722b3c428c90fa2a232b1a6ab1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 13:12:14 +0100 Subject: [PATCH 11/12] test(daemon): prove deferred artifact cleanup survives disposal --- .../src/resources/artifact-tracking.test.ts | 142 +++++++++++++++++- 1 file changed, 141 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 11cf95af54..8318c6ae99 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -3,7 +3,7 @@ import { once } from 'node:events'; import path from 'node:path'; import { buffer } from 'node:stream/consumers'; import { gunzipSync } from 'node:zlib'; -import { expect, test } from 'vitest'; +import { expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import { @@ -14,6 +14,146 @@ import { type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; +function holdArtifactReads() { + const pending: Array<{ file: string; complete: () => void }> = []; + const createReadStream = fs.createReadStream; + let held = true; + const spy = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => + createReadStream(file, { + ...(typeof options === 'string' ? { encoding: options } : options), + fs: { + open: fs.open, + close: fs.close, + read(fd, buffer, offset, length, position, callback) { + fs.read(fd, buffer, offset, length, position, (error, bytesRead, readBuffer) => { + const complete = () => callback(error, bytesRead, readBuffer); + if (held) pending.push({ file: String(file), complete }); + else complete(); + }); + }, + }, + }), + ); + return { + pending, + release: () => { + held = false; + for (const { complete } of pending.splice(0)) complete(); + }, + restore: () => spy.mockRestore(), + }; +} + +test.each(['old-first', 'new-first'] as const)( + 'disposing two deferred registrations cleans their shared source after pending reads close (%s)', + async (order) => { + const root = mkdtempForTestSync('fu-art-shared-dispose-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'shared source marker'); + const runtime = createRuntimeStateHandle(); + const reads = holdArtifactReads(); + const removed = vi.spyOn(fs, 'rmSync'); + const downloads: OpenedDownloadableArtifact[] = []; + const track = () => + runtime.run(() => trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' })); + try { + const firstId = track(); + downloads.push( + await runtime.run(() => openDownloadableArtifact(firstId, undefined, process.env)), + ); + runtime.run(() => cleanupDownloadableArtifact(firstId)); + const secondId = track(); + expect(secondId).not.toBe(firstId); + downloads.push( + await runtime.run(() => openDownloadableArtifact(secondId, undefined, process.env)), + ); + runtime.run(() => cleanupDownloadableArtifact(secondId)); + for (const download of downloads) download.stream.resume(); + await vi.waitFor(() => expect(reads.pending).toHaveLength(2)); + runtime.dispose(); + expect(fs.existsSync(artifactPath)).toBe(true); + for (const download of downloads) expect(download.stream.closed).toBe(false); + const firstToClose = downloads[order === 'old-first' ? 0 : 1]!; + const pendingIndex = reads.pending.findIndex( + ({ file }) => file === String(firstToClose.stream.path), + ); + expect(pendingIndex).toBeGreaterThanOrEqual(0); + reads.pending.splice(pendingIndex, 1)[0]!.complete(); + await vi.waitFor(() => + expect(downloads.filter(({ stream }) => stream.closed)).toHaveLength(1), + ); + expect(firstToClose.stream.closed).toBe(true); + expect(fs.existsSync(artifactPath)).toBe(true); + reads.release(); + await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); + for (const download of downloads) { + expect(download.stream.closed).toBe(true); + const archiveDir = path.dirname(String(download.stream.path)); + expect(fs.existsSync(archiveDir)).toBe(false); + expect(removed.mock.calls.filter(([target]) => target === archiveDir)).toHaveLength(1); + } + expect(removed.mock.calls.filter(([target]) => target === artifactPath)).toHaveLength(1); + } finally { + reads.release(); + runtime.dispose(); + for (const { stream } of downloads) { + if (!stream.closed) await once(stream, 'close'); + } + reads.restore(); + removed.mockRestore(); + } + }, +); + +test('expiry defers a stalled directory read until its own deadline closes and cleans it', async () => { + const root = mkdtempForTestSync('fu-art-stalled-expiry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'stalled source marker'); + const runtime = createRuntimeStateHandle(); + const reads = holdArtifactReads(); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const removed = vi.spyOn(fs, 'rmSync'); + let download: OpenedDownloadableArtifact | undefined; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const expire = timers.mock.calls.at(-1)![0]; + const timerIndex = timers.mock.calls.length; + const opening = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + const deadline = timers.mock.calls[timerIndex]![0]; + download = await opening; + const archiveDir = path.dirname(String(download.stream.path)); + download.stream.resume(); + await vi.waitFor(() => expect(reads.pending).toHaveLength(1)); + runtime.run(expire); + expect(download.stream.destroyed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + runtime.run(deadline); + expect(download.signal.aborted).toBe(true); + expect(download.stream.destroyed).toBe(true); + expect(download.stream.closed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + reads.release(); + await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); + expect(download.stream.closed).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(false); + for (const target of [artifactPath, archiveDir]) { + expect(removed.mock.calls.filter(([removedPath]) => removedPath === target)).toHaveLength(1); + } + } finally { + reads.release(); + runtime.dispose(); + if (download && !download.stream.closed) await once(download.stream, 'close'); + timers.mockRestore(); + reads.restore(); + removed.mockRestore(); + } +}); + test('disposing a runtime removes the temporary files it still tracks', () => { const root = mkdtempForTestSync('agent-device-artifact-dispose-'); const artifactPath = path.join(root, 'artifact.txt'); From e4ad2f37e3381dc09ad1b382e1ffe17e3599d5f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 13:37:54 +0100 Subject: [PATCH 12/12] fix(daemon): preserve archive builds for uncancelled downloads --- .../src/resources/artifact-tracking.test.ts | 229 ++++++++++++++---- .../daemon/src/resources/artifact-tracking.ts | 4 +- .../server/downloadable-artifact-http.test.ts | 91 ++++++- 3 files changed, 271 insertions(+), 53 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 8318c6ae99..84a3170300 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -6,6 +6,7 @@ import { gunzipSync } from 'node:zlib'; import { expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import * as command from '@agent-device/host-kit/command'; import { cleanupDownloadableArtifact, openDownloadableArtifact, @@ -14,6 +15,127 @@ import { type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; +test('cancelling the archive builder preserves a second download waiting for its full archive', async () => { + const root = mkdtempForTestSync('fu-art-shared-build-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + const expected = 'complete shared capture payload\n'.repeat(4096); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + let continueArchive!: () => void; + const blocked = new Promise((resolve) => { + continueArchive = resolve; + }); + let archiveStarted!: () => void; + const started = new Promise((resolve) => { + archiveStarted = resolve; + }); + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveStarted(); + await blocked; + return await runCmd(...args); + }); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const timerIndex = timers.mock.calls.length; + const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(first); + void first.catch(() => {}); + const cancelFirst = timers.mock.calls[timerIndex]![0]; + await started; + const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(second); + void second.catch(() => {}); + runtime.run(cancelFirst); + continueArchive(); + const download = await second; + const closed = once(download.stream, 'close'); + const bytes = await buffer(download.stream); + await closed; + download.release(); + expect(bytes).toHaveLength(download.sizeBytes); + expect(gunzipSync(bytes).includes(Buffer.from(expected))).toBe(true); + await expect(first).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); + expect(archive).toHaveBeenCalledTimes(1); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(download.stream.path)))).toBe(false); + } finally { + continueArchive(); + const results = await Promise.allSettled(openings); + for (const result of results) { + if (result.status !== 'fulfilled') continue; + const download = result.value; + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); + } + runtime.dispose(); + timers.mockRestore(); + archive.mockRestore(); + } +}); + +test('disposing every archive waiter aborts the shared build and removes its temporary directory', async () => { + const root = mkdtempForTestSync('fu-art-cancel-all-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'cancelled archive payload'); + const runtime = createRuntimeStateHandle(); + let continueArchive!: () => void; + const blocked = new Promise((resolve) => { + continueArchive = resolve; + }); + let archiveStarted!: () => void; + const started = new Promise((resolve) => { + archiveStarted = resolve; + }); + let archiveDir = ''; + let archiveSignal: AbortSignal | undefined; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveDir = path.dirname(String(args[1]?.[1])); + archiveSignal = args[2]?.signal; + archiveStarted(); + await blocked; + return await runCmd(...args); + }); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); + await started; + openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); + for (const opening of openings) void opening.catch(() => {}); + runtime.dispose(); + expect(archiveSignal?.aborted).toBe(true); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + continueArchive(); + for (const opening of openings) { + await expect(opening).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); + } + expect(archive).toHaveBeenCalledTimes(1); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(archiveDir)).toBe(false); + } finally { + continueArchive(); + await Promise.allSettled(openings); + runtime.dispose(); + archive.mockRestore(); + } +}); + function holdArtifactReads() { const pending: Array<{ file: string; complete: () => void }> = []; const createReadStream = fs.createReadStream; @@ -106,53 +228,68 @@ test.each(['old-first', 'new-first'] as const)( }, ); -test('expiry defers a stalled directory read until its own deadline closes and cleans it', async () => { - const root = mkdtempForTestSync('fu-art-stalled-expiry-'); - const artifactPath = path.join(root, 'capture.trace'); - fs.mkdirSync(artifactPath); - fs.writeFileSync(path.join(artifactPath, 'payload'), 'stalled source marker'); - const runtime = createRuntimeStateHandle(); - const reads = holdArtifactReads(); - const timers = vi.spyOn(globalThis, 'setTimeout'); - const removed = vi.spyOn(fs, 'rmSync'); - let download: OpenedDownloadableArtifact | undefined; - try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); - const expire = timers.mock.calls.at(-1)![0]; - const timerIndex = timers.mock.calls.length; - const opening = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); - const deadline = timers.mock.calls[timerIndex]![0]; - download = await opening; - const archiveDir = path.dirname(String(download.stream.path)); - download.stream.resume(); - await vi.waitFor(() => expect(reads.pending).toHaveLength(1)); - runtime.run(expire); - expect(download.stream.destroyed).toBe(false); - expect(fs.existsSync(artifactPath)).toBe(true); - expect(fs.existsSync(archiveDir)).toBe(true); - runtime.run(deadline); - expect(download.signal.aborted).toBe(true); - expect(download.stream.destroyed).toBe(true); - expect(download.stream.closed).toBe(false); - expect(fs.existsSync(artifactPath)).toBe(true); - reads.release(); - await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); - expect(download.stream.closed).toBe(true); - expect(fs.existsSync(archiveDir)).toBe(false); - for (const target of [artifactPath, archiveDir]) { - expect(removed.mock.calls.filter(([removedPath]) => removedPath === target)).toHaveLength(1); +test.each(['expiry-first', 'deadline-first'] as const)( + 'a stalled directory read cleans up after registration expiry and its own deadline (%s)', + async (order) => { + const root = mkdtempForTestSync('fu-art-stalled-expiry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'stalled source marker'); + const runtime = createRuntimeStateHandle(); + const reads = holdArtifactReads(); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); + const removed = vi.spyOn(fs, 'rmSync'); + let download: OpenedDownloadableArtifact | undefined; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const expire = timers.mock.calls.at(-1)![0]; + const expiryTimer = timers.mock.results.at(-1)!.value; + const timerIndex = timers.mock.calls.length; + const opening = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + const deadline = timers.mock.calls[timerIndex]![0]; + download = await opening; + const archiveDir = path.dirname(String(download.stream.path)); + download.stream.resume(); + await vi.waitFor(() => expect(reads.pending).toHaveLength(1)); + if (order === 'expiry-first') runtime.run(expire); + expect(download.stream.destroyed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + runtime.run(deadline); + expect(download.signal.aborted).toBe(true); + expect(download.stream.destroyed).toBe(true); + expect(download.stream.closed).toBe(false); + expect(fs.existsSync(artifactPath)).toBe(true); + reads.release(); + await vi.waitFor(() => expect(download!.stream.closed).toBe(true)); + if (order === 'deadline-first') { + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(true); + expect(clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer)).toBe(false); + runtime.run(expire); + } + await vi.waitFor(() => expect(fs.existsSync(artifactPath)).toBe(false)); + expect(download.stream.closed).toBe(true); + expect(fs.existsSync(archiveDir)).toBe(false); + for (const target of [artifactPath, archiveDir]) { + expect(removed.mock.calls.filter(([removedPath]) => removedPath === target)).toHaveLength( + 1, + ); + } + } finally { + reads.release(); + runtime.dispose(); + if (download && !download.stream.closed) await once(download.stream, 'close'); + timers.mockRestore(); + clearedTimers.mockRestore(); + reads.restore(); + removed.mockRestore(); } - } finally { - reads.release(); - runtime.dispose(); - if (download && !download.stream.closed) await once(download.stream, 'close'); - timers.mockRestore(); - reads.restore(); - removed.mockRestore(); - } -}); + }, +); test('disposing a runtime removes the temporary files it still tracks', () => { const root = mkdtempForTestSync('agent-device-artifact-dispose-'); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 89c94abc9d..4bc868a76f 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -220,7 +220,9 @@ function cancelArtifactDownload( const reason = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); download.controller.abort(reason); if (!download.stream) { - entry.archiveAbortController?.abort(reason); + if ([...entry.activeDownloads].every(({ controller }) => controller.signal.aborted)) { + entry.archiveAbortController?.abort(reason); + } return; } const closed = finished(download.stream, { cleanup: true }).catch(() => {}); diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index fc200de553..aa8e14bccc 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -2,11 +2,12 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; +import { gunzipSync } from 'node:zlib'; import { expect, test, vi } from 'vitest'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; -import { runCmdSync } from '@agent-device/host-kit/command'; +import * as command from '@agent-device/host-kit/command'; import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; -import { trackDownloadableArtifact } from '../resources/artifact-tracking.ts'; +import * as artifactTracking from '../resources/artifact-tracking.ts'; import { createDaemonHttpServer } from './http/http-server.ts'; function deferred() { @@ -28,6 +29,7 @@ type DownloadFixture = { outcome(): 'pending' | 'complete' | 'failed'; cleanupCount(): number; expire(): void; + expiryPending(): boolean; fireDeadlines(): void; }; @@ -56,9 +58,10 @@ async function withDownloadFixture( const timers = vi.spyOn(globalThis, 'setTimeout'); const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log' }), + artifactTracking.trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log' }), ); const expire = timers.mock.calls[0]![0]; + const expiryTimer = timers.mock.results[0]!.value; const removed = vi.spyOn(fs, 'rmSync'); const streams: fs.ReadStream[] = []; const createReadStream = fs.createReadStream; @@ -106,6 +109,7 @@ async function withDownloadFixture( outcome: () => outcome, cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, expire: () => runtime.run(expire), + expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), fireDeadlines: () => { for (const [index, [callback, delay]] of timers.mock.calls.entries()) { const handle = timers.mock.results[index]!.value; @@ -136,6 +140,50 @@ async function withDownloadFixture( } } +test('a client abort during a shared archive build preserves the other HTTP download', async () => { + const started = deferred(); + const proceed = deferred(); + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + started.resolve(); + await proceed.promise; + return await runCmd(...args); + }); + const opens = vi.spyOn(artifactTracking, 'openDownloadableArtifact'); + try { + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + fixture.start(); + await started.promise; + const second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); + void second.catch(() => {}); + try { + await vi.waitFor(() => expect(opens).toHaveBeenCalledTimes(2)); + fixture.abortClient(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + proceed.resolve(); + const response = await second; + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + expect(archive).toHaveBeenCalledTimes(1); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + } finally { + proceed.resolve(); + await Promise.allSettled([second]); + } + }, + () => {}, + ); + } finally { + proceed.resolve(); + opens.mockRestore(); + archive.mockRestore(); + } +}); + test.each(['destroyed', 'truncated', 'errored'] as const)( 'a %s artifact read terminates the HTTP response', async (failure) => { @@ -182,6 +230,37 @@ test('an artifact open failure returns a complete JSON error before streaming st ); }); +test('a truncated directory archive preserves the source and expires without leaking its cached archive', async () => { + await withDownloadFixture( + async (fixture) => { + const payloadPath = path.join(fixture.source, 'payload'); + const expected = fs.readFileSync(payloadPath); + fixture.start(); + await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); + const stream = fixture.streams[0]!; + await vi.waitFor(() => expect(stream.closed).toBe(true)); + const archiveDir = path.dirname(String(stream.path)); + expect(fs.readFileSync(payloadPath)).toEqual(expected); + expect(fs.existsSync(archiveDir)).toBe(true); + expect(fixture.expiryPending()).toBe(true); + const inventory = await fetch(fixture.url.slice(0, fixture.url.lastIndexOf('/')), { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(await inventory.json()).toMatchObject({ + artifacts: [{ id: fixture.url.split('/').at(-1) }], + }); + fixture.expire(); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fs.existsSync(archiveDir)).toBe(false); + expect(fixture.cleanupCount()).toBe(1); + }, + (stream) => + stream.once('open', () => + fs.truncateSync(String(stream.path), fs.statSync(String(stream.path)).size - 1), + ), + ); +}); + test.each(['deadline', 'runtime disposal'] as const)( '%s cancels an active download and removes its files', async (trigger) => { @@ -250,7 +329,7 @@ test('a directory artifact expires after download header setup throws', async () const port = await listenOnLoopback(server); const timer = vi.spyOn(globalThis, 'setTimeout'); const artifactId = runtime.run(() => - trackDownloadableArtifact({ + artifactTracking.trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log', fileName: 'trace-💥', @@ -315,7 +394,7 @@ test.each(['another download completes', 'expiry fires'] as const)( const headers = { authorization: 'Bearer fu-art-secret' }; const timer = vi.spyOn(globalThis, 'setTimeout'); const artifactId = runtime.run(() => - trackDownloadableArtifact({ + artifactTracking.trackDownloadableArtifact({ artifactPath: source, artifactType: 'trace-log', }), @@ -375,7 +454,7 @@ test.each(['another download completes', 'expiry fires'] as const)( if (first) expect(delayed.bytes).toEqual(first.bytes); const downloaded = path.join(root, 'download.tar.gz'); fs.writeFileSync(downloaded, delayed.bytes); - expect(runCmdSync('tar', ['-xOzf', downloaded, 'profile.trace/payload']).stdout).toBe( + expect(command.runCmdSync('tar', ['-xOzf', downloaded, 'profile.trace/payload']).stdout).toBe( expected, ); await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false));