From c3e68fdc57be279ec1aab6d7e6f42fa6875f0bf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:30:16 +0100 Subject: [PATCH 01/13] fix(remote): bind client artifact destinations to capture identity --- docs/agents/security.md | 5 +- packages/contracts/src/recording.ts | 2 + packages/daemon-client/src/index.ts | 8 +- .../src/core/capture-identity-refusal.ts | 30 + .../src/core/session-capture-binding.ts | 3 +- packages/daemon/src/core/session-state.ts | 2 + .../handlers/__tests__/trace-runtime.test.ts | 41 +- .../src/sessions/handlers/trace-runtime.ts | 22 +- .../__tests__/session-perf-runtime.test.ts | 22 +- .../internal/session-perf-runtime.ts | 24 +- packages/kernel/src/contracts.ts | 2 + packages/kernel/src/errors.ts | 12 + .../capture-destination-record.test.ts | 928 ++++++++++++++++++ .../daemon-artifacts-capture.test.ts | 73 +- .../daemon-artifacts-record-download.test.ts | 31 +- .../remote/src/capture-destination-record.ts | 432 ++++++++ packages/remote/src/daemon-artifacts.ts | 76 +- src/commands/schema/cli-help-workflows.ts | 1 + test/wire-compat/ledger.json | 32 +- website/docs/docs/error-reasons.md | 8 + website/docs/docs/remote-proxy.md | 17 +- 21 files changed, 1683 insertions(+), 88 deletions(-) create mode 100644 packages/daemon/src/core/capture-identity-refusal.ts create mode 100644 packages/remote/src/__tests__/capture-destination-record.test.ts create mode 100644 packages/remote/src/capture-destination-record.ts diff --git a/docs/agents/security.md b/docs/agents/security.md index f64ef197f22..64d0a59ca7b 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -2,7 +2,10 @@ The CLI client trusts its caller to choose local destinations. The client trusts a remote daemon for data and validated identifiers. -Scripts and remote record stop reject daemon paths (#4518). Trace and perf take them. +Scripts and remote record stop reject daemon paths (#4518). +For pathless remote trace and perf stops, reuse a saved caller path only when the daemon confirms its capture ID. +Give unnamed remote artifacts unique names in the client working directory. +If the saved capture ID identifies a foreign live capture, refuse a pathless stop. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/contracts/src/recording.ts b/packages/contracts/src/recording.ts index bad1c4e1ad9..9002dc82f0a 100644 --- a/packages/contracts/src/recording.ts +++ b/packages/contracts/src/recording.ts @@ -69,9 +69,11 @@ export type TraceCommandResult = | { trace: 'started'; outPath: string; + clientCaptureId?: string; } | { trace: 'stopped'; outPath: string; artifacts: DaemonArtifact[]; + clientCaptureId?: string; }; diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 128bfa7972a..143a4268157 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -19,6 +19,7 @@ import { resolveCommandTimeoutPolicy } from '@agent-device/command-registry/regi import { resolveCommandRequestTimeoutMs } from '@agent-device/command-registry/timeout-policy'; import { prepareRemoteRequestArtifacts, + sendRemoteCapture, sendRemoteScriptOpen, type PreparedRemoteRequest, } from '@agent-device/remote/daemon-artifacts'; @@ -186,9 +187,10 @@ async function sendToDaemonOnHost( ...(options.leaseCheckedByAdmission ? { leaseCheckedByAdmission: true } : {}), }, ); - if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript) - return await send(request); - return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); + if (!info.baseUrl) return await send(request); + if (request.meta?.clientArtifactPaths?.savedScript) + return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); + return await sendRemoteCapture(info.baseUrl, request, settings.paths.baseDir, send); }, { requestId, command: req.command }, ); diff --git a/packages/daemon/src/core/capture-identity-refusal.ts b/packages/daemon/src/core/capture-identity-refusal.ts new file mode 100644 index 00000000000..f21621efe46 --- /dev/null +++ b/packages/daemon/src/core/capture-identity-refusal.ts @@ -0,0 +1,30 @@ +import { errorResponse, type DaemonResponse } from '@agent-device/kernel/contracts'; +import { CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; + +type CaptureKind = 'trace' | 'native perf'; +type CaptureRefusal = 'already-active' | 'mismatch'; + +const messages = { + trace: { + 'already-active': 'trace already in progress', + mismatch: 'trace capture identity changed', + }, + 'native perf': { + 'already-active': 'native perf capture already in progress', + mismatch: 'native perf capture identity changed', + }, +} as const; + +export function captureIdentityRefusal( + kind: CaptureKind, + refusal: CaptureRefusal, + clientCaptureId?: string, +): DaemonResponse { + return errorResponse('INVALID_ARGS', messages[kind][refusal], { + reason: + refusal === 'already-active' + ? CAPTURE_IDENTITY_REASONS.alreadyActive.reason + : CAPTURE_IDENTITY_REASONS.mismatch.reason, + ...(refusal === 'already-active' ? { clientCaptureId } : {}), + }); +} diff --git a/packages/daemon/src/core/session-capture-binding.ts b/packages/daemon/src/core/session-capture-binding.ts index 79a809d6512..4b84035e171 100644 --- a/packages/daemon/src/core/session-capture-binding.ts +++ b/packages/daemon/src/core/session-capture-binding.ts @@ -39,12 +39,13 @@ export function bindSessionPerfCapture( sessionStore: SessionStore, ref: SessionRef, clientOutPath?: string, + clientCaptureId?: string, ) { return bindSessionCapture(sessionStore, ref, { read: (session) => session.perfCapture, write: (perfCapture) => { sessionStore.update(ref, { - perfCapture: perfCapture ? { ...perfCapture, clientOutPath } : undefined, + perfCapture: perfCapture ? { ...perfCapture, clientOutPath, clientCaptureId } : undefined, }); }, }); diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index 0a12367c0e7..aef1385b1e2 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -224,6 +224,7 @@ export type SessionState = { snapshotDiagnostics?: SnapshotDiagnosticsState; trace?: { outPath: string; + clientCaptureId?: string; clientOutPath?: string; remoteCaptureOutputPath?: string; remoteCaptureTenantId?: string; @@ -231,6 +232,7 @@ export type SessionState = { }; /** Native profiling mechanics stay behind one exact-owner durable handle. */ perfCapture?: { + clientCaptureId?: string; clientOutPath?: string; handle: PerfNativeCaptureLiveHandle; envelope: DurableResourceEnvelope<'perf-capture'>; diff --git a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts index 95db10173f2..99ea84bcd7f 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts @@ -36,14 +36,21 @@ function fixture() { return { root, session, sessionStore }; } -function request(positionals: string[], clientOutPath?: string): DaemonRequest { +function request(positionals: string[], clientOutPath?: string, captureId?: string): DaemonRequest { return { token: 'token', session: 'trace-session', command: 'trace', positionals, flags: {}, - ...(clientOutPath ? { meta: { clientArtifactPaths: { outPath: clientOutPath } } } : {}), + ...(clientOutPath || captureId + ? { + meta: { + ...(clientOutPath ? { clientArtifactPaths: { outPath: clientOutPath } } : {}), + ...(captureId ? { captureId } : {}), + }, + } + : {}), }; } @@ -69,6 +76,36 @@ test('starts and stops one trace through the session-owned trace slot', () => { expect(session.trace).toBeUndefined(); }); +test('a stale client capture identity cannot stop a reopened trace', () => { + const { session, sessionStore } = fixture(); + const host = createTestHostEnvironment(); + const started = handleTraceCommand({ + host, + req: request(['start'], undefined, 'capture-b'), + sessionName: session.name, + sessionStore, + }); + expect(started).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); + const stale = handleTraceCommand({ + host, + req: request(['stop'], undefined, 'capture-a'), + sessionName: session.name, + sessionStore, + }); + expect(stale).toMatchObject({ + ok: false, + error: { details: { reason: 'capture-identity-mismatch' } }, + }); + expect(session.trace).toBeDefined(); + const stopped = handleTraceCommand({ + host, + req: request(['stop'], undefined, 'capture-b'), + sessionName: session.name, + sessionStore, + }); + expect(stopped).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); +}); + test('relocates trace output and projects the client artifact path', () => { const { root, session, sessionStore } = fixture(); const original = path.join(root, 'original.trace'); diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index 556240ea0b3..846fbd18ed1 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -3,11 +3,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import fs from 'node:fs'; import path from 'node:path'; -import { - parseTraceAction, - TRACE_ACTION_REQUIRED_MESSAGE, - type TraceCommandResult, -} from '@agent-device/contracts/recording'; +import { parseTraceAction, TRACE_ACTION_REQUIRED_MESSAGE } from '@agent-device/contracts/recording'; import type { SessionStore } from '../../core/session-store.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { requestCwd } from '../../core/context.ts'; @@ -15,6 +11,8 @@ import type { SessionRef } from '../../core/session-state.ts'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; +import { captureIdentityRefusal } from '../../core/capture-identity-refusal.ts'; +import type { TraceCommandResult } from '@agent-device/contracts/recording'; export function handleTraceCommand(params: { host: HostEnvironment; @@ -38,7 +36,8 @@ function startTrace( ref: SessionRef, ): DaemonResponse { const session = sessionStore.requireCurrent(ref); - if (session.trace) return errorResponse('INVALID_ARGS', 'trace already in progress'); + if (session.trace) + return captureIdentityRefusal('trace', 'already-active', session.trace.clientCaptureId); const outPath = expandSessionPath( req.positionals?.[1] ?? sessionStore.defaultTracePath(session), requestCwd(req, host), @@ -47,6 +46,7 @@ function startTrace( fs.appendFileSync(outPath, ''); session.trace = { outPath, + clientCaptureId: req.meta?.captureId, startedAt: Date.now(), clientOutPath: req.meta?.clientArtifactPaths?.outPath, ...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}), @@ -55,7 +55,11 @@ function startTrace( recordSessionAction(sessionStore, ref, req, req.command, { action: 'start', outPath }); return { ok: true, - data: { trace: 'started', outPath } satisfies TraceCommandResult, + data: { + trace: 'started', + outPath, + ...(req.meta?.captureId ? { clientCaptureId: req.meta.captureId } : {}), + } satisfies TraceCommandResult, }; } @@ -67,6 +71,9 @@ function stopTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); + if (req.meta?.captureId && req.meta.captureId !== session.trace.clientCaptureId) + return captureIdentityRefusal('trace', 'mismatch'); + const clientCaptureId = session.trace.clientCaptureId; const outPath = relocateTraceOutput( requestCwd(req, host), session.trace.outPath, @@ -86,6 +93,7 @@ function stopTrace( { trace: 'stopped', outPath, + ...(clientCaptureId ? { clientCaptureId } : {}), artifacts: [ { field: 'outPath', diff --git a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts index 8e39b68059c..fc5951a685f 100644 --- a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts +++ b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts @@ -213,10 +213,11 @@ test('perf native capture is adopted durably and stop uses the live handle witho command: 'perf', positionals: ['trace', 'start', 'xctrace'], flags: { out: '/tmp/app.trace' }, - meta: { clientArtifactPaths: { outPath: '/client/app.trace' } }, + meta: { clientArtifactPaths: { outPath: '/client/app.trace' }, captureId: 'capture-b' }, }, }); assert.equal(startResponse?.ok, true, JSON.stringify(startResponse)); + assert.equal(startResponse?.data?.clientCaptureId, 'capture-b'); assert.ok(sessionStore.get('android')?.perfCapture); assert.deepEqual( sessionStore.get('android')?.actions.map(({ command }) => command), @@ -245,6 +246,23 @@ test('perf native capture is adopted durably and stop uses the live handle witho assert.ok(sessionStore.get('android')?.perfCapture); assert.equal(sessionStore.get('android')?.actions.length, 1); + const staleStop = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId: 'capture-a' }, + }, + }); + assert.equal(staleStop?.ok, false); + if (staleStop && !staleStop.ok) + assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); + assert.equal(finish.mock.calls.length, 0); + const stopResponse = await handleSessionObservabilityCommands({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -254,10 +272,12 @@ test('perf native capture is adopted durably and stop uses the live handle witho session: 'android', command: 'perf', positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId: 'capture-b' }, }, }); assert.equal(stopResponse?.ok, true, JSON.stringify(stopResponse)); if (stopResponse?.ok) assert.equal(stopResponse.data?.clientOutPath, '/client/app.trace'); + if (stopResponse?.ok) assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); assert.equal(finish.mock.calls.length, 1); assert.deepEqual(runtime.uses, [['perfNativeCaptureStart']]); assert.equal(sessionStore.get('android')?.perfCapture, undefined); diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index ca212de1b16..a5bfffa32df 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -39,6 +39,7 @@ import { requestCwd } from '../../../core/context.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { bindSessionPerfCapture } from '../../../core/session-capture-binding.ts'; import { withCaptureOutputOwnership } from '../../../core/capture-output-ownership.ts'; +import { captureIdentityRefusal } from '../../../core/capture-identity-refusal.ts'; import { recordSessionAction } from '../../../core/session-action-recorder.ts'; import { admitRuntimePlan, @@ -216,7 +217,11 @@ async function startPerfCapture( request: Extract, ): Promise { if (session.perfCapture) { - return errorResponse('INVALID_ARGS', 'native perf capture already in progress'); + return captureIdentityRefusal( + 'native perf', + 'already-active', + session.perfCapture.clientCaptureId, + ); } if (!session.appBundleId) { return errorResponse('COMMAND_FAILED', 'No app is associated with this session.', { @@ -243,6 +248,7 @@ async function startPerfCapture( params.sessionStore, params.ref, params.req.meta?.clientArtifactPaths?.outPath, + params.req.meta?.captureId, ); binding.assertAdoptable(); const started = await runtime.operations @@ -292,7 +298,13 @@ async function startPerfCapture( : started.envelope, throwIfCanceled: params.throwIfCanceled, }); - return { ok: true, data: started.response }; + return { + ok: true, + data: { + ...started.response, + ...(params.req.meta?.captureId ? { clientCaptureId: params.req.meta.captureId } : {}), + }, + }; } function requirePerfCaptureAdmissionLedger( @@ -311,6 +323,8 @@ async function stopPerfCapture( ): Promise { const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); + if (params.req.meta?.captureId && params.req.meta.captureId !== capture.clientCaptureId) + return captureIdentityRefusal('native perf', 'mismatch'); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); if (mismatchMessage) return errorResponse('INVALID_ARGS', mismatchMessage); @@ -335,7 +349,11 @@ async function stopPerfCapture( return { ok: true, data: withCaptureOutputOwnership( - { ...completion, ...(clientOutPath ? { clientOutPath } : {}) }, + { + ...completion, + ...(clientOutPath ? { clientOutPath } : {}), + ...(capture.clientCaptureId ? { clientCaptureId: capture.clientCaptureId } : {}), + }, capture.envelope.metadata?.remoteCaptureOutputPath === completion.outPath ? 'daemon' : 'caller', diff --git a/packages/kernel/src/contracts.ts b/packages/kernel/src/contracts.ts index 10e0790444f..2d9927f5190 100644 --- a/packages/kernel/src/contracts.ts +++ b/packages/kernel/src/contracts.ts @@ -181,6 +181,8 @@ export type DaemonRequestMeta = { sessionIsolation?: SessionIsolationMode; uploadedArtifactId?: string; clientArtifactPaths?: Record; + /** Opaque caller capture identity; older daemons may ignore it. */ + captureId?: string; /** The ID a remote client minted for its `open --save-script`; each script version carries it. */ scriptPublicationId?: string; installSource?: DaemonInstallSource; diff --git a/packages/kernel/src/errors.ts b/packages/kernel/src/errors.ts index 6b820574013..75b9654f375 100644 --- a/packages/kernel/src/errors.ts +++ b/packages/kernel/src/errors.ts @@ -496,6 +496,18 @@ export const DURABLE_RESOURCE_REASONS = { transportNotReattachable: { reason: 'transport-not-reattachable' }, } as const satisfies ReasonTable<'durable captures'>; +/** Refusals that identify the live trace or native perf capture without trusting an output path. */ +export const CAPTURE_IDENTITY_REASONS = { + // A capture already runs for this session; the response names its live capture ID when one was minted. + alreadyActive: { reason: 'capture-already-active' }, + // The daemon refuses a stop with the wrong capture ID. + // The client also refuses a pathless stop when a settled record identifies a foreign live capture. + // An explicit caller path can still stop it. + mismatch: { reason: 'capture-identity-mismatch' }, + // The local capture destination record is unreadable or malformed, so no remote capture command is sent. + recordInvalid: { reason: 'capture-record-invalid' }, +} as const satisfies ReasonTable<'capture identity'>; + const REQUEST_CANCELED_HINT = 'The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.'; diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts new file mode 100644 index 00000000000..07e642d817d --- /dev/null +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -0,0 +1,928 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { test, expect } from 'vitest'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; +import { + confirmedCaptureStopRequest, + sendRemoteCapture, + retireSuccessfulCaptureStop, +} from '../capture-destination-record.ts'; +import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; + +const endpoint = 'https://capture.example.test/api'; +const success = { ok: true as const, data: {} }; +const confirmed = (req: DaemonWireRequest) => ({ + ok: true as const, + data: { clientCaptureId: req.meta?.captureId }, +}); + +function request( + action: 'start' | 'stop', + outPath?: string, + options: { + family?: 'trace' | 'perf'; + perfKind?: 'perfetto' | 'xctrace'; + tenantId?: string; + runId?: string; + leaseId?: string; + session?: string; + } = {}, +): DaemonWireRequest { + return { + token: 'test', + command: options.family ?? 'trace', + session: options.session ?? 'device-a', + positionals: + options.family === 'perf' ? ['trace', action, options.perfKind ?? 'perfetto'] : [action], + meta: { + tenantId: options.tenantId ?? 'tenant-a', + runId: options.runId ?? 'run-a', + leaseId: options.leaseId ?? 'lease-a', + ...(outPath ? { clientArtifactPaths: { outPath } } : {}), + }, + }; +} + +function captureRecordPath(stateDir: string): string { + const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); + const [scope] = fs.readdirSync(root); + if (!scope) throw new Error('Missing capture session record directory'); + const [recordName] = fs.readdirSync(path.join(root, scope)); + if (!recordName) throw new Error('Missing capture record'); + return path.join(root, scope, recordName); +} + +test.each(['trace', 'perf'] as const)( + '%s stop replays its own start path and retires it', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const destination = '/client/captures/owned.trace'; + await sendRemoteCapture( + endpoint, + request('start', destination, { family }), + stateDir, + async (req) => confirmed(req), + ); + const sent: DaemonWireRequest[] = []; + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + sent.push(req); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe(destination); + await materializeRemoteArtifacts( + { baseUrl: endpoint, token: 'test' }, + req, + answer, + createTestHostEnvironment(), + stateDir, + ); + return answer; + }, + ); + expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[0]?.meta?.captureId).toBeTypeOf('string'); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + sent.push(req); + return success; + }, + ); + expect(sent[1]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(sent[1]?.meta?.captureId).toBeUndefined(); + }, +); + +test('a pathless new start replaces an older destination without reusing its path', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + let newCaptureId: string | undefined; + await sendRemoteCapture(endpoint, request('start'), stateDir, async (start) => { + newCaptureId = start.meta?.captureId; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + return confirmed(start); + }); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newCaptureId); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test.each(['returned', 'thrown'] as const)( + 'a forged undispatched %s failure cannot restore the old destination', + async (failure) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => confirmed(req), + ); + const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + if (failure === 'thrown') throw { details: { dispatched: 'no' } }; + return { + ok: false, + error: { code: 'COMMAND_FAILED', message: 'refused', details: { dispatched: 'no' } }, + }; + }); + if (failure === 'thrown') + await expect(start).rejects.toMatchObject({ details: { dispatched: 'no' } }); + else expect((await start).ok).toBe(false); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + }, +); + +test.each(['trace', 'perf'] as const)( + '%s rejected repeat start preserves the confirmed destination', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/first.trace', { family }), + stateDir, + async (req) => { + firstCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + const refused = await sendRemoteCapture( + endpoint, + request('start', '/client/second.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: firstCaptureId }, + }, + }), + ); + expect(refused.ok).toBe(false); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }, + ); + }, +); + +test.each(['trace', 'perf'] as const)( + '%s HTTP refusal of a repeat start preserves the confirmed destination and original error', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let activeId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/first.trace', { family }), + stateDir, + async (req) => { + activeId = req.meta?.captureId; + return confirmed(req); + }, + ); + const refusal = new AppError('INVALID_ARGS', 'capture already active', { + reason: 'capture-already-active', + clientCaptureId: activeId, + }); + await expect( + sendRemoteCapture( + endpoint, + request('start', '/client/second.trace', { family }), + stateDir, + async () => { + throw refusal; + }, + ), + ).rejects.toBe(refusal); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBe(activeId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }, + ); + }, +); + +test.each(['trace', 'perf'] as const)( + '%s refuses a pathless stop after a foreign capture claims the session', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family }), + stateDir, + async (req) => confirmed(req), + ); + const refusal = await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: 'foreign-capture' }, + }, + }), + ); + expect(refusal.ok).toBe(false); + expect(JSON.parse(fs.readFileSync(captureRecordPath(stateDir), 'utf8')).certainty).toBe( + 'foreign', + ); + let dispatched = false; + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async () => { + dispatched = true; + return success; + }), + ).rejects.toMatchObject({ details: { reason: 'capture-identity-mismatch' } }); + expect(dispatched).toBe(false); + const failedExplicitStop = await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace', { family }), + stateDir, + async () => ({ ok: false, error: { code: 'COMMAND_FAILED', message: 'stop failed' } }), + ); + expect(failedExplicitStop.ok).toBe(false); + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async () => { + dispatched = true; + return success; + }), + ).rejects.toMatchObject({ details: { reason: 'capture-identity-mismatch' } }); + expect(dispatched).toBe(false); + await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace', { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/explicit.trace'); + return success; + }, + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + return success; + }, + ); + }, +); + +test('a late explicit-stop reply cannot clear a newer confirmed capture', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + request('start', '/client/retry.trace'), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: 'foreign-capture' }, + }, + }), + ); + let stopSent!: () => void; + const stopReachedDaemon = new Promise((resolve) => (stopSent = resolve)); + let finishStop!: () => void; + const stopCanFinish = new Promise((resolve) => (finishStop = resolve)); + const explicitStop = sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace'), + stateDir, + async () => { + stopSent(); + await stopCanFinish; + return success; + }, + ); + await stopReachedDaemon; + let newerId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async (req) => { + newerId = req.meta?.captureId; + return confirmed(req); + }, + ); + finishStop(); + await explicitStop; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test.each(['trace', 'perf'] as const)( + '%s keeps a timed-out own start unknown when a retry names its ID', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstId: string | undefined; + await expect( + sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family }), + stateDir, + async (req) => { + firstId = req.meta?.captureId; + throw new Error('timeout after dispatch'); + }, + ), + ).rejects.toThrow('timeout after dispatch'); + expect(firstId).toBeTypeOf('string'); + await sendRemoteCapture( + endpoint, + request('start', '/client/retry.trace', { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: firstId }, + }, + }), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + }, +); + +test.each(['trace', 'perf'] as const)( + '%s retains a confirmed unnamed capture ID across repeat-start refusal', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let activeId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', undefined, { family }), + stateDir, + async (req) => { + activeId = req.meta?.captureId; + return confirmed(req); + }, + ); + await sendRemoteCapture( + endpoint, + request('start', undefined, { family }), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: activeId }, + }, + }), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBe(activeId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + return answer; + }, + ); + }, +); + +test('a malformed capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.writeFileSync(file, '{invalid'); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { + details: { reason: 'capture-record-invalid' }, + }, + ); + expect(dispatched).toBe(false); + expect(fs.readFileSync(file, 'utf8')).toBe('{invalid'); +}); + +test('an unreadable capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.rmSync(file); + fs.mkdirSync(file); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { details: { reason: 'capture-record-invalid' } }, + ); + expect(dispatched).toBe(false); +}); + +test('a concurrent rejected start does not discard a newly confirmed start', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let releaseFirst!: () => void; + const firstReachedDaemon = new Promise((resolve) => (releaseFirst = resolve)); + let finishFirst!: () => void; + const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + let firstId: string | undefined; + const first = sendRemoteCapture( + endpoint, + request('start', '/client/first.trace'), + stateDir, + async (req) => { + firstId = req.meta?.captureId; + releaseFirst(); + await firstCanFinish; + return confirmed(req); + }, + ); + await firstReachedDaemon; + const second = sendRemoteCapture( + endpoint, + request('start', '/client/second.trace'), + stateDir, + async () => ({ + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture already active', + details: { reason: 'capture-already-active', clientCaptureId: firstId }, + }, + }), + ); + await second; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + finishFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/first.trace'); + return answer; + }); +}); + +test('successful close retires destinations before the same session address is reused', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test('failed close leaves the confirmed destination for a retry', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async () => ({ ok: false, error: { code: 'COMMAND_FAILED', message: 'close failed' } }), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/old.trace'); + return answer; + }); +}); + +test('a different client can reuse the session name without authorizing the old destination', async () => { + const firstStateDir = mkdtempForTestSync('capture-destination-a-'); + const secondStateDir = mkdtempForTestSync('capture-destination-b-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/a.trace'), + firstStateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + secondStateDir, + async () => success, + ); + let secondCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/b.trace'), + secondStateDir, + async (req) => { + secondCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + const oldStop = await sendRemoteCapture(endpoint, request('stop'), firstStateDir, async (req) => { + expect(req.meta?.captureId).not.toBe(secondCaptureId); + return { + ok: false, + error: { + code: 'INVALID_ARGS', + message: 'capture identity changed', + details: { reason: 'capture-identity-mismatch' }, + }, + }; + }); + expect(oldStop.ok).toBe(false); + await sendRemoteCapture(endpoint, request('stop'), firstStateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test.each(['trace', 'perf'] as const)( + '%s HTTP identity mismatch retires only the rejected capture', + async (family) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/stale.trace', { family }), + stateDir, + async (req) => confirmed(req), + ); + const refusal = new AppError('INVALID_ARGS', 'capture identity changed', { + reason: 'capture-identity-mismatch', + }); + await expect( + sendRemoteCapture(endpoint, request('stop', undefined, { family }), stateDir, async (req) => { + expect(req.meta?.captureId).toBeTypeOf('string'); + throw refusal; + }), + ).rejects.toBe(refusal); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + }, +); + +test('a later confirmed start clears an earlier uncertain start', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/failed.trace'), + stateDir, + async () => ({ ok: false, error: { code: 'SESSION_NOT_FOUND', message: 'not open' } }), + ); + await sendRemoteCapture( + endpoint, + request('start', '/client/current.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/current.trace'); + return answer; + }); +}); + +test('a late failed start cannot make a newer confirmed destination uncertain', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let firstSent!: () => void; + const firstReachedDaemon = new Promise((resolve) => (firstSent = resolve)); + let failFirst!: () => void; + const firstCanFail = new Promise((resolve) => (failFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async () => { + firstSent(); + await firstCanFail; + return { ok: false, error: { code: 'COMMAND_FAILED', message: 'uncertain' } }; + }, + ); + await firstReachedDaemon; + await sendRemoteCapture(endpoint, request('start', '/client/new.trace'), stateDir, async (req) => + confirmed(req), + ); + failFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test('a delayed close does not retire a capture confirmed after the close was sent', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => + confirmed(req), + ); + let releaseClose!: () => void; + const closeCanFinish = new Promise((resolve) => (releaseClose = resolve)); + let closeReachedDaemon!: () => void; + const closeWasSent = new Promise((resolve) => (closeReachedDaemon = resolve)); + const close = sendRemoteCapture( + endpoint, + { ...request('stop'), command: 'close', positionals: [] }, + stateDir, + async () => { + closeReachedDaemon(); + await closeCanFinish; + return success; + }, + ); + await closeWasSent; + await sendRemoteCapture(endpoint, request('start', '/client/new.trace'), stateDir, async (req) => + confirmed(req), + ); + releaseClose(); + await close; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test('missing or mismatched stop confirmation cannot select a saved path', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect( + (await confirmedCaptureStopRequest(req, success)).meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + expect( + (await confirmedCaptureStopRequest(req, { ok: true, data: { clientCaptureId: 'other' } })) + .meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + return success; + }); +}); + +test.each(['returned', 'thrown'] as const)( + 'repeated %s start failures keep one bounded fail-closed marker', + async (failure) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => confirmed(req), + ); + for (let attempt = 0; attempt < 40; attempt += 1) { + const start = sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async () => { + if (failure === 'thrown') throw new Error('transport uncertain'); + return { ok: false as const, error: { code: 'COMMAND_FAILED', message: 'uncertain' } }; + }, + ); + if (failure === 'thrown') await expect(start).rejects.toThrow('transport uncertain'); + else expect((await start).ok).toBe(false); + } + const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); + const [scope] = fs.readdirSync(root); + expect(scope).toBeDefined(); + if (!scope) throw new Error('Missing capture session record directory'); + const [recordName] = fs.readdirSync(path.join(root, scope)); + expect(recordName).toBeDefined(); + if (!recordName) throw new Error('Missing capture record'); + const record = JSON.parse(fs.readFileSync(path.join(root, scope, recordName), 'utf8')); + expect(record.pending).toEqual([]); + expect(record.certainty).toBe('unknown'); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + }, +); + +test('a late successful start cannot replace a newer confirmed destination', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let releaseFirst!: () => void; + const firstStarted = new Promise((resolve) => (releaseFirst = resolve)); + let finishFirst!: () => void; + const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => { + releaseFirst(); + await firstCanFinish; + return confirmed(req); + }, + ); + await firstStarted; + let newerCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async (req) => { + newerCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + finishFirst(); + await first; + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerCaptureId); + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/new.trace'); + return answer; + }); +}); + +test('scope and explicit stop path cannot borrow or override another capture destination', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { tenantId: 'tenant-b' }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); + await sendRemoteCapture( + endpoint, + request('stop', '/client/explicit.trace'), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/explicit.trace'); + await retireSuccessfulCaptureStop(req); + return success; + }, + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); +}); + +test('endpoint, tenant, run, lease, session, and capture kind each isolate destinations', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace', { family: 'perf' }), + stateDir, + async (req) => confirmed(req), + ); + const variants = [ + { baseUrl: `${endpoint}/other`, options: { family: 'perf' as const } }, + { baseUrl: endpoint, options: { family: 'perf' as const, tenantId: 'tenant-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, runId: 'run-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, leaseId: 'lease-b' } }, + { baseUrl: endpoint, options: { family: 'perf' as const, session: 'device-b' } }, + { baseUrl: endpoint, options: { family: 'trace' as const } }, + { baseUrl: endpoint, options: { family: 'perf' as const, perfKind: 'xctrace' as const } }, + ]; + for (const { baseUrl, options } of variants) { + await sendRemoteCapture(baseUrl, request('stop', undefined, options), stateDir, async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }); + } + await sendRemoteCapture( + endpoint, + request('stop', undefined, { family: 'perf' }), + stateDir, + async (req) => { + const answer = confirmed(req); + expect( + (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + ).toBe('/client/owned.trace'); + return answer; + }, + ); +}); diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 4698ce5a51b..6937762fbed 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -81,8 +81,10 @@ type MaterializationCase = { localPath: string; field?: string; fileName?: string; + artifactType?: string; expected?: string; generatedName?: RegExp; + protectedPath?: string; }; const posixNameCases: MaterializationCase[] = [ @@ -91,7 +93,7 @@ const posixNameCases: MaterializationCase[] = [ command: 'snapshot', localPath: 'outside/shot.png', fileName: 'C:shot.png', - expected: 'cwd/C:shot.png', + generatedName: /^C:shot-[0-9a-f-]{36}\.png$/, }, { name: 'POSIX keeps a colon in the generated basename', @@ -99,7 +101,7 @@ const posixNameCases: MaterializationCase[] = [ localPath: 'outside/shot.png', field: 'subdir/c:path', fileName: '', - generatedName: /^c:path-\d+$/, + generatedName: /^c:path-\d+-[0-9a-f-]{36}$/, }, ]; @@ -113,11 +115,34 @@ test.for([ expected: 'client/shot.png', }, { - name: 'an unregistered response localPath and file name stay in cwd', + name: 'an unregistered response name cannot replace an existing cwd file', command: 'snapshot', localPath: 'outside/x', fileName: '../../x', - expected: 'cwd/x', + generatedName: /^x-[0-9a-f-]{36}$/, + protectedPath: 'cwd/x', + }, + { + name: 'a long response name leaves room for the client suffix', + command: 'snapshot', + localPath: 'outside/long.mp4', + fileName: `${'a'.repeat(220)}.mp4`, + generatedName: /^a+-[0-9a-f-]{36}\.mp4$/, + }, + { + name: 'a long extension stays in the truncated response name', + command: 'snapshot', + localPath: 'outside/long', + fileName: `a.${'b'.repeat(230)}`, + generatedName: /^a\.b+-[0-9a-f-]{36}$/, + }, + { + name: 'a snapshot response cannot select directory extraction', + command: 'snapshot', + localPath: 'outside/archive.tar', + fileName: 'archive.tar', + artifactType: 'test-artifacts', + generatedName: /^archive-[0-9a-f-]{36}\.tar$/, }, { name: 'an omitted file name generates a destination in cwd', @@ -129,7 +154,7 @@ test.for([ command: 'close', localPath: 'outside/shot.png', fileName: 'shot.png', - expected: 'cwd/shot.png', + generatedName: /^shot-[0-9a-f-]{36}\.png$/, }, { name: 'a record start refuses a response localPath', @@ -137,21 +162,35 @@ test.for([ positionals: ['start'], localPath: 'outside/clip.mp4', fileName: 'clip.mp4', - expected: 'cwd/clip.mp4', + generatedName: /^clip-[0-9a-f-]{36}\.mp4$/, }, { - name: 'a perf cpu profile stop accepts the echo of its start destination', + name: 'a perf cpu profile stop ignores the daemon echo of its start destination', command: 'perf', positionals: ['cpu', 'profile', 'stop'], localPath: 'client/cpu.trace', fileName: 'cpu.trace', - expected: 'client/cpu.trace', + generatedName: /^cpu-[0-9a-f-]{36}\.trace$/, + protectedPath: 'cwd/cpu.trace', + }, + { + name: 'a trace stop ignores a daemon-selected client path', + command: 'trace', + positionals: ['stop'], + localPath: 'cwd/private.log', + fileName: 'trace.log', + generatedName: /^trace-[0-9a-f-]{36}\.log$/, + protectedPath: 'cwd/private.log', }, ...(process.platform === 'win32' ? [] : posixNameCases), ])('remote artifact materialization: $name', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-path-'); const inRoot = (relative: string) => path.join(root, relative); + if (c.protectedPath) { + fs.mkdirSync(path.dirname(inRoot(c.protectedPath)), { recursive: true }); + fs.writeFileSync(inRoot(c.protectedPath), 'protected'); + } const field = c.field ?? 'path'; const server = http.createServer((_req, res) => res.end('artifact-bytes')); try { @@ -175,7 +214,7 @@ test.for([ { artifactId: 'a1', field, - artifactType: 'screenshot', + artifactType: c.artifactType ?? 'screenshot', path: '/daemon/x', localPath: inRoot(c.localPath), ...(c.fileName === undefined ? {} : { fileName: c.fileName }), @@ -190,9 +229,11 @@ test.for([ expect(saved).toEqual(c.expected ? inRoot(c.expected) : expect.any(String)); if (!c.expected) { expect(path.dirname(String(saved))).toBe(inRoot('cwd')); - expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+$/); + expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+-[0-9a-f-]{36}$/); + expect(Buffer.byteLength(path.basename(String(saved)))).toBeLessThanOrEqual(255); } expect(fs.readFileSync(String(saved), 'utf8')).toBe('artifact-bytes'); + if (c.protectedPath) expect(fs.readFileSync(inRoot(c.protectedPath), 'utf8')).toBe('protected'); expect(fs.existsSync(inRoot('outside'))).toBe(false); } finally { await closeLoopbackServer(server); @@ -222,6 +263,18 @@ test.for([ fileName: '', platform: 'win32', }, + { + name: 'a Windows alternate data stream in the response basename', + field: 'path', + fileName: 'report.txt:trace.log', + platform: 'win32', + }, + { + name: 'a Windows alternate data stream in the generated basename', + field: 'report.txt:trace.log', + fileName: '', + platform: 'win32', + }, ])('a remote artifact with $name is dropped and the action result is kept', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-invalid-name-'); diff --git a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts index f0304edc06a..4d7824e6046 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts @@ -75,7 +75,9 @@ test('record stop ignores the daemon localPath and warns about the cwd download' await withRecordingServer(t, async (cwd, stop) => { const hostile = path.resolve(cwd, '../hostile.mp4'); const data = await stop([{ ...video, localPath: hostile }]); - const fallback = path.join(cwd, 'clip.mp4'); + const fallback = String(data?.outPath); + expect(path.dirname(fallback)).toBe(cwd); + expect(path.basename(fallback)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); expect(fs.existsSync(hostile)).toBe(false); expect(fs.readFileSync(fallback, 'utf8')).toBe('video'); expect(data).toMatchObject({ @@ -103,17 +105,19 @@ test('record stop uses the destination named in the current request', async (t) }); }); -test('record stop replaces a destination symlink without writing through it', async (t) => { +test('unnamed record stop leaves an existing destination symlink untouched', async (t) => { await withRecordingServer(t, async (cwd, stop) => { const destination = path.join(cwd, 'clip.mp4'); const target = path.resolve(cwd, '../target'); fs.writeFileSync(target, 'original'); fs.symlinkSync(target, destination); - await stop([video]); + const data = await stop([video]); + const saved = String(data?.outPath); expect(fs.readFileSync(target, 'utf8')).toBe('original'); - expect(fs.lstatSync(destination).isFile()).toBe(true); - expect(fs.readFileSync(destination, 'utf8')).toBe('video'); - expect(fs.readdirSync(cwd)).toEqual(['clip.mp4']); + expect(fs.lstatSync(destination).isSymbolicLink()).toBe(true); + expect(path.basename(saved)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); + expect(fs.readFileSync(saved, 'utf8')).toBe('video'); + expect(fs.readdirSync(cwd)).toHaveLength(2); }); }); @@ -125,6 +129,7 @@ test.for([ 'nested/clip.mp4', String.raw`x\clip.mp4`, 'x\n.mp4', + `${'a'.repeat(250)}.mp4`, ])('record stop generates a name in cwd for %j', async (fileName, t) => { await withRecordingServer(t, async (cwd, stop) => { const data = await stop([{ ...video, fileName }]); @@ -190,21 +195,25 @@ test('record stop downloads each chunk and telemetry to cwd', async (t) => { { index: 1, path: '/daemon/second.mp4' }, ], ); - const second = path.join(cwd, 'second.mp4'); - const telemetry = path.join(cwd, 'telemetry.json'); - expect(fs.readFileSync(path.join(cwd, 'clip.mp4'), 'utf8')).toBe('video'); + const first = String(data?.outPath); + const second = String((data?.chunks as Array<{ path: string }> | undefined)?.[1]?.path); + const telemetry = String(data?.telemetryPath); + expect(path.basename(first)).toMatch(/^clip-[0-9a-f-]{36}\.mp4$/); + expect(path.basename(second)).toMatch(/^second-[0-9a-f-]{36}\.mp4$/); + expect(path.basename(telemetry)).toMatch(/^telemetry-[0-9a-f-]{36}\.json$/); + expect(fs.readFileSync(first, 'utf8')).toBe('video'); expect(fs.readFileSync(second, 'utf8')).toBe('chunk'); expect(fs.readFileSync(telemetry, 'utf8')).toBe('telemetry'); expect(fs.existsSync(path.resolve(cwd, '../second.mp4'))).toBe(false); expect(fs.existsSync(path.resolve(cwd, '../telemetry.json'))).toBe(false); expect(data).toMatchObject({ chunks: [ - { index: 0, path: path.join(cwd, 'clip.mp4') }, + { index: 0, path: first }, { index: 1, path: second }, ], telemetryPath: telemetry, recordingDestinationWarnings: [ - { field: 'outPath', path: path.join(cwd, 'clip.mp4') }, + { field: 'outPath', path: first }, { field: 'chunkPath', path: second }, { field: 'telemetryPath', path: telemetry }, ], diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts new file mode 100644 index 00000000000..20ffe65394b --- /dev/null +++ b/packages/remote/src/capture-destination-record.ts @@ -0,0 +1,432 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; +import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { AppError, CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; +import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; + +type Capture = { action: 'start' | 'stop'; family: string }; +type Send = (req: DaemonWireRequest) => Promise; +type Active = { generation: string; destination?: string; order: number }; +type Pending = { generation: string; order: number }; +type CaptureCertainty = 'settled' | 'unknown' | 'foreign'; +type RecordState = { + active?: Active; + pending: Pending[]; + certainty: CaptureCertainty; + nextOrder: number; +}; +const stopGenerations = new WeakMap(); + +function captureOf(req: DaemonWireRequest): Capture | undefined { + if (req.command === 'trace') { + const action = req.positionals?.[0]?.toLowerCase(); + return action === 'start' || action === 'stop' ? { action, family: 'trace' } : undefined; + } + if (req.command !== 'perf') return undefined; + try { + const parsed = parsePerfRuntimeRequest({ + positionals: req.positionals, + outPath: req.flags?.out, + }); + if ((parsed.area === 'cpu' || parsed.area === 'trace') && parsed.action !== 'report') { + return { action: parsed.action, family: `perf:${parsed.area}:${parsed.kind}` }; + } + } catch { + // Let command dispatch report invalid grammar without touching capture state. + } + return undefined; +} + +function sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequest): string { + const scope = leaseScopeFromRequest(req); + const key = crypto + .createHash('sha256') + .update( + JSON.stringify([ + baseUrl.replace(/\/+$/, ''), + scope.tenantId ?? null, + scope.runId ?? null, + scope.leaseId ?? null, + req.session ?? null, + ]), + ) + .digest('hex'); + return path.join(stateDir, 'remote-connections', 'capture-destinations', key); +} + +function recordFile( + stateDir: string, + baseUrl: string, + req: DaemonWireRequest, + family: string, +): string { + const key = crypto.createHash('sha256').update(family).digest('hex'); + return path.join(sessionRecordDir(stateDir, baseUrl, req), `${key}.json`); +} + +function readRecord(file: string): RecordState | undefined { + let serialized: string; + try { + serialized = fs.readFileSync(file, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + invalidRecord(error); + } + let value: unknown; + try { + value = JSON.parse(serialized); + } catch (error) { + invalidRecord(error); + } + if (!isRecordState(value)) invalidRecord(); + return value; +} + +function isPending(value: unknown): value is Pending { + if (typeof value !== 'object' || value === null) return false; + const pending = value as Partial; + return ( + typeof pending.generation === 'string' && + Number.isSafeInteger(pending.order) && + (pending.order ?? 0) > 0 + ); +} + +function isActive(value: unknown): value is Active { + if (typeof value !== 'object' || value === null) return false; + const active = value as Partial; + return ( + typeof active.generation === 'string' && + (active.destination === undefined || + (typeof active.destination === 'string' && path.isAbsolute(active.destination))) && + Number.isSafeInteger(active.order) && + (active.order ?? 0) > 0 + ); +} + +function isRecordState(value: unknown): value is RecordState { + if (typeof value !== 'object' || value === null) return false; + const record = value as Partial; + return ( + Array.isArray(record.pending) && + record.pending.every(isPending) && + (record.certainty === 'settled' || + record.certainty === 'unknown' || + record.certainty === 'foreign') && + Number.isSafeInteger(record.nextOrder) && + (record.nextOrder ?? -1) >= 0 && + (record.active === undefined || isActive(record.active)) + ); +} + +function invalidRecord(cause?: unknown): never { + throw new AppError( + 'COMMAND_FAILED', + 'Remote capture destination record is invalid', + { reason: CAPTURE_IDENTITY_REASONS.recordInvalid.reason }, + cause, + ); +} + +function writeRecord(file: string, record: RecordState): void { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + publishFileSync({ destination: file, contents: `${JSON.stringify(record)}\n`, mode: 0o600 }); +} + +function settleRecord(file: string, record: RecordState): void { + if (!record.active && record.pending.length === 0 && record.certainty === 'settled') + fs.rmSync(file, { force: true }); + else writeRecord(file, record); +} + +function refusalDetails(response: DaemonResponse | undefined, failure: unknown) { + if (response?.ok === false) return response.error.details; + return failure instanceof AppError ? failure.details : undefined; +} + +function confirmedStartCapture( + response: Extract, + generation: string, + destination: string | undefined, + order: number, +): Active | undefined { + if (response.data?.clientCaptureId !== generation) return undefined; + return { + generation, + ...(typeof destination === 'string' && path.isAbsolute(destination) ? { destination } : {}), + order, + }; +} + +function activeAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + generation: string, + destination: string | undefined, + order: number, +): Active | undefined { + const active = current.active; + if (order < (active?.order ?? 0)) return active; + if (response?.ok === true) return confirmedStartCapture(response, generation, destination, order); + const details = refusalDetails(response, failure); + if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) + return details.clientCaptureId === active?.generation ? active : undefined; + return active; +} + +function recordAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + generation: string, + destination: string | undefined, + order: number, +): RecordState { + const active = activeAfterStart(current, response, failure, generation, destination, order); + return { + ...(active ? { active } : {}), + pending: current.pending.filter((candidate) => candidate.generation !== generation), + certainty: certaintyAfterStart(current, response, failure, generation, order), + nextOrder: current.nextOrder, + }; +} + +function certaintyAfterStart( + current: RecordState, + response: DaemonResponse | undefined, + failure: unknown, + generation: string, + order: number, +): CaptureCertainty { + if (order < (current.active?.order ?? 0)) return current.certainty; + if (response?.ok === true && response.data?.clientCaptureId === generation) return 'settled'; + const details = refusalDetails(response, failure); + if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) + return certaintyAfterAlreadyActive(current, details.clientCaptureId); + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; +} + +function certaintyAfterAlreadyActive( + current: RecordState, + clientCaptureId: unknown, +): CaptureCertainty { + if (current.active && clientCaptureId === current.active.generation) return current.certainty; + if (current.pending.some((pending) => pending.generation === clientCaptureId)) + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; + if (current.certainty === 'settled' && typeof clientCaptureId === 'string') return 'foreign'; + return current.certainty === 'foreign' ? 'foreign' : 'unknown'; +} + +async function withRecordLock(file: string, task: () => Promise): Promise { + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const { pid, startTime } = readCurrentOwnerIdentity(); + return await withProcessLock({ + acquire: () => + acquireProcessLock({ + lockDirPath: `${file}.lock`, + owner: { pid, startTime, acquiredAtMs: Date.now() }, + timeoutMs: 30_000, + description: 'remote capture destination', + }), + task, + }); +} + +/** Persists caller-authored start paths and replays them into later pathless stops. */ +export async function sendRemoteCapture( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, + send: Send, +): Promise { + const capture = captureOf(req); + if (!capture) return await sendWithoutCapture(baseUrl, req, stateDir, send); + const file = recordFile(stateDir, baseUrl, req, capture.family); + return capture.action === 'stop' + ? await sendCaptureStop(file, req, send) + : await sendCaptureStart(file, req, send); +} + +async function sendWithoutCapture( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, + send: Send, +): Promise { + const closedRecords = + req.command === 'close' ? await snapshotSessionCaptures(baseUrl, req, stateDir) : undefined; + const response = await send(req); + if (response.ok && closedRecords) await retireClosedSessionCaptures(closedRecords); + return response; +} + +async function sendCaptureStop( + file: string, + req: DaemonWireRequest, + send: Send, +): Promise { + const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; + const { active, foreignBeforeStop } = await withRecordLock(file, async () => { + const current = readRecord(file); + if (current?.certainty === 'foreign' && !hasExplicitPath) + throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); + return { + active: + current?.pending.length === 0 && current.certainty === 'settled' + ? current.active + : undefined, + foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, + }; + }); + if (!active) { + const response = await send(req); + if (response.ok && foreignBeforeStop) await clearForeignAfterStop(file, foreignBeforeStop); + return response; + } + const sent = hasExplicitPath + ? req + : { ...req, meta: { ...req.meta, captureId: active.generation } }; + stopGenerations.set(sent, { file, generation: active.generation }); + let response: DaemonResponse; + try { + response = await send(sent); + } catch (error) { + if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + await retireSuccessfulCaptureStop(sent); + throw error; + } + if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + await retireSuccessfulCaptureStop(sent); + return response; +} + +async function clearForeignAfterStop(file: string, beforeStop: string): Promise { + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current?.certainty === 'foreign' && JSON.stringify(current) === beforeStop) + settleRecord(file, { ...current, certainty: 'settled' }); + }); +} + +async function sendCaptureStart( + file: string, + req: DaemonWireRequest, + send: Send, +): Promise { + const generation = crypto.randomUUID(); + const order = await withRecordLock(file, async () => { + const current = readRecord(file); + const nextOrder = (current?.nextOrder ?? 0) + 1; + writeRecord(file, { + ...(current?.active ? { active: current.active } : {}), + pending: [...(current?.pending ?? []), { generation, order: nextOrder }], + certainty: current?.certainty ?? 'settled', + nextOrder, + }); + return nextOrder; + }); + let response: DaemonResponse | undefined; + let failure: unknown; + let threw = false; + try { + response = await send({ ...req, meta: { ...req.meta, captureId: generation } }); + } catch (error) { + threw = true; + failure = error; + } + const destination = req.meta?.clientArtifactPaths?.outPath; + await withRecordLock(file, async () => { + const current = readRecord(file); + if (!current?.pending.some((pending) => pending.generation === generation)) return; + settleRecord( + file, + recordAfterStart(current, response, failure, generation, destination, order), + ); + }); + if (threw) throw failure; + if (!response) throw new TypeError('Capture start settled without a response'); + return response; +} + +/** A successful daemon stop retires its generation before artifact download can fail. */ +export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promise { + const owned = stopGenerations.get(req); + if (!owned) return; + stopGenerations.delete(req); + await withRecordLock(owned.file, async () => { + const current = readRecord(owned.file); + if (current?.active?.generation === owned.generation) + settleRecord(owned.file, { + pending: current.pending, + certainty: current.certainty, + nextOrder: current.nextOrder, + }); + }); +} + +/** A response can use a saved path only when it confirms this client's live capture identity. */ +export async function confirmedCaptureStopRequest( + req: DaemonWireRequest, + response: Extract, +): Promise { + const owned = stopGenerations.get(req); + if (!owned || response.data?.clientCaptureId !== owned.generation) return req; + const active = await withRecordLock(owned.file, async () => { + const current = readRecord(owned.file); + return current?.pending.length === 0 && + current.certainty === 'settled' && + current.active?.generation === owned.generation + ? current.active + : undefined; + }); + if (!active?.destination || typeof req.meta?.clientArtifactPaths?.outPath === 'string') + return req; + return { + ...req, + meta: { + ...req.meta, + clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, + }, + }; +} + +async function snapshotSessionCaptures( + baseUrl: string, + req: DaemonWireRequest, + stateDir: string, +): Promise> { + const dir = sessionRecordDir(stateDir, baseUrl, req); + let entries: string[]; + try { + entries = fs.readdirSync(dir).filter((entry) => entry.endsWith('.json')); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Map(); + throw error; + } + const records = new Map(); + for (const entry of entries) { + const file = path.join(dir, entry); + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current) records.set(file, JSON.stringify(current)); + }); + } + return records; +} + +async function retireClosedSessionCaptures(records: ReadonlyMap): Promise { + for (const [file, beforeClose] of records) { + await withRecordLock(file, async () => { + const current = readRecord(file); + if (current && JSON.stringify(current) === beforeClose) fs.rmSync(file, { force: true }); + }); + } +} diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 8d6d546aed8..cd632c59fd7 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -492,6 +492,14 @@ export async function sendRemoteScriptOpen( return await scripts.sendRemoteScriptOpen(...args); } +/** Keeps one remote capture's caller destination across separate client requests. */ +export async function sendRemoteCapture( + ...args: Parameters +): Promise { + const captures = await import('./capture-destination-record.ts'); + return await captures.sendRemoteCapture(...args); +} + /** * Settles the batch delivery receipt a FAILED remote response names (ADR 0016, #4595): a batch that * stopped mid-plan still delivers what its completed steps wrote. The destination owner loads only @@ -526,10 +534,13 @@ export async function materializeRemoteArtifacts( stateDir: string, ): Promise { if (!info.baseUrl) return response; + const captures = await import('./capture-destination-record.ts'); + const downloadRequest = await captures.confirmedCaptureStopRequest(req, response); + await captures.retireSuccessfulCaptureStop(req); const endpoint = { baseUrl: info.baseUrl, token: info.token }; const artifacts = Array.isArray(response.data?.artifacts) ? response.data.artifacts : []; const download = (scripts?: SessionScriptDelivery) => - downloadResponseArtifacts(endpoint, req, response, host, scripts); + downloadResponseArtifacts(endpoint, downloadRequest, response, host, scripts); // A receipt is a delivery instruction of its own: a batch answer may carry one while naming no // publication and no script artifact of its own (#4595). if ( @@ -604,11 +615,13 @@ async function downloadOneArtifact( artifactId: artifact.artifactId, destinationPath: destination.path, requestScope: req.meta, - // #2246: `test-artifacts` is the one directory-shaped artifact type today — known from the - // response, before any bytes arrive, so cleanup-on-error can be decided up front instead of - // racing the response headers (a directory destination must never be `rm`'d wholesale; see - // `downloadRemoteArtifact`). - isDirectory: recording === undefined && artifact.artifactType === 'test-artifacts', + // #2246: Only a test request's artifactsDir may select directory extraction. Decide before + // bytes arrive so cleanup-on-error cannot remove a directory destination wholesale. + isDirectory: + recording === undefined && + req.command === 'test' && + artifact.field === 'artifactsDir' && + artifact.artifactType === 'test-artifacts', stagedFile: recording !== undefined, }); recording?.add(artifact.field, materializedPath, destination.fallback); @@ -722,29 +735,12 @@ function withoutScriptFieldOwner( return kept; } -/** - * Whether this request finishes a trace or perf capture whose destination the daemon echoes - * from an earlier request. The finishing actions mirror `request-finalization.ts`. - */ -function finishesEarlierClientCapture(req: DaemonWireRequest): boolean { - const [first, second, third] = (req.positionals ?? []).map((value) => value.toLowerCase()); - switch (req.command) { - case 'trace': - return first === 'stop'; - case 'perf': - return third === 'stop' || third === 'report' || (first === 'trace' && second === 'stop'); - default: - return false; - } -} - function isRecordStop(req: DaemonWireRequest): boolean { return req.command === 'record' && req.positionals?.[0]?.toLowerCase() === 'stop'; } /** - * A path from this request wins. A record stop without one can use only a plain name in cwd. - * Trace and perf stop or report can still use an echoed destination from an earlier request. + * A path from this request wins. Every unnamed artifact gets a unique client file in cwd. * A NUL in a response file name cannot provide a fallback destination. */ function resolveMaterializedArtifactPath( @@ -761,13 +757,33 @@ function resolveMaterializedArtifactPath( } if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined; const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`; - return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true }; - } - if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { - return { path: artifact.localPath, fallback: false }; + return { + path: uniqueClientArtifactPath(path.resolve(req.meta?.cwd ?? host.cwd, fileName)), + fallback: true, + }; } const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd); - return fallbackPath ? { path: fallbackPath, fallback: false } : undefined; + return fallbackPath + ? { path: uniqueClientArtifactPath(fallbackPath), fallback: false } + : undefined; +} + +function uniqueClientArtifactPath(candidate: string): string { + const rawExtension = path.extname(candidate); + const keepExtension = Buffer.byteLength(rawExtension) <= 64; + const extension = keepExtension ? rawExtension : ''; + const suffix = `-${crypto.randomUUID()}${extension}`; + const stemBudget = 255 - Buffer.byteLength(suffix); + let stem = ''; + let stemBytes = 0; + const rawStem = keepExtension ? path.basename(candidate, rawExtension) : path.basename(candidate); + for (const character of rawStem) { + const nextBytes = Buffer.byteLength(character); + if (stemBytes + nextBytes > stemBudget) break; + stem += character; + stemBytes += nextBytes; + } + return path.join(path.dirname(candidate), `${stem || 'artifact'}${suffix}`); } function resolveOrdinaryArtifactFallbackPath( @@ -782,7 +798,7 @@ function resolveOrdinaryArtifactFallbackPath( responseName && responseName !== '.' && responseName !== '..' ? responseName : `${pathRules.basename(artifact.field)}-${Date.now()}`; - if (pathRules === path.win32 && /^[a-z]:/i.test(fileName)) return undefined; + if (pathRules === path.win32 && fileName.includes(':')) return undefined; return pathRules.resolve(cwd, fileName); } diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 1ea3e535f9b..3ea25836e1c 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -149,6 +149,7 @@ Diagnostics and traces: agent-device press 'id="load-diagnostics"' agent-device trace stop ./traces/diagnostics.trace The trace path is positional. Do not use --path for trace start or trace stop. + For a remote capture, a stop without a path reuses the start destination saved in this client's state directory when the endpoint, session, lease, and capture kind match. Use perf xctrace only for Apple native CPU/profile or Animation Hitches artifacts: agent-device perf cpu profile start --kind xctrace --template "Time Profiler" --out ./artifacts/app.trace agent-device perf cpu profile stop --kind xctrace --out ./artifacts/app.trace diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index f33634a6690..97f806b803d 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -23,7 +23,7 @@ "packages/kernel/src/contracts.ts#DaemonInstallSource": "sha256:adfde90c81de72009bf0e092b95fcb41cece2ecd44e936dcb1f6beb220287f02", "packages/kernel/src/contracts.ts#DaemonLockPolicy": "sha256:f33d0ce7200a7d97c11e91bd2889b5d9bc7f35935a5370a29930118d091468f4", "packages/kernel/src/contracts.ts#DaemonRequest": "sha256:911d93245b8dc557db897c4cac051030db673711bf3af51baa8b82248d509c57", - "packages/kernel/src/contracts.ts#DaemonRequestMeta": "sha256:6606964fc548906460d800b7265f2f5bbfff56306fc6805c5b40ff0e08ca9fac", + "packages/kernel/src/contracts.ts#DaemonRequestMeta": "sha256:a89feccb277139aa9dd89072947818782d892052e698a31180320e0da33db28c", "packages/kernel/src/contracts.ts#DaemonResponse": "sha256:5f6cc08ed43f40c1cf17e33dd2b6b879dda1ac383de9c6c9a2c653929c21346b", "packages/kernel/src/contracts.ts#DaemonResponseData": "sha256:a5921503176f31ccab0cd1dc62aa315b7fab9b4dabedf420cf73922fc7c77c97", "packages/kernel/src/contracts.ts#JsonRpcId": "sha256:5a5fdff1cd85971214117d69a8278d0ecaf21a6fa3f4582155d9b3d9cad1fbd0", @@ -159,9 +159,9 @@ "packages/remote/src/daemon-artifacts.ts#buildDaemonArtifactUrl": "sha256:06dcde057809b507f70f7bb5cdef9bde6515be84b67e45865cf19e70b8636208", "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", - "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", - "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", + "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", + "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", @@ -243,7 +243,7 @@ "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", - "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:dd8726c99d2e5a4c63ad5f66392732d0116496af50251d7d03007d605b29012d", + "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:d8fcb526605e7a255198fb530fc6b22fcda0788ab30f0f83462559ba81a9ad0b", "packages/remote/src/daemon-artifacts.ts#DroppedArtifact": "sha256:c340f0a9a4b99d0664f8c32ac78b3a054c95e7f171cf3531331f7cdc143e0cfb", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", @@ -273,8 +273,8 @@ "compatibleChanges": [ { "declaration": "packages/kernel/src/contracts.ts#DaemonRequestMeta", - "digest": "sha256:6606964fc548906460d800b7265f2f5bbfff56306fc6805c5b40ff0e08ca9fac", - "rationale": "Adds the optional developerDir field: a local client's DEVELOPER_DIR, overlaid on the env of commands the daemon spawns for that request. A released daemon ignores the unknown meta key and keeps its own environment, exactly as before; a released client never sends it, so the new daemon inherits its own environment for that request. The remote HTTP surface strips it. Also adds the optional leaseRetainOnClose field, sent only on lease_allocate when the caller opts in: a released daemon ignores the unknown meta key and releases the lease on session close as before, and a released client never sends it. Adds the optional providerCredentialFingerprint field: a digest of the local caller's provider credential variables, which the daemon compares with its own on lease_allocate. A released daemon ignores the unknown meta key and allocates as before; a released client never sends it, so the new daemon skips the comparison. The client sends it only to a local daemon, and the remote HTTP surface strips it. #4511 adds the optional scriptPublicationId string, which a new client sends only on a remote open --save-script to a daemon that reports the script-artifacts capability. Any other request keeps its previous meta. Adds the optional coordinateUnit field ('native' | 'dp'). A released daemon ignores the unknown meta key and answers in native units with no coordinates label, and a new client sends it only after the daemon's /health reports android-dp-coordinates, refusing the call before the send with dp_coordinates_unsupported otherwise; a released client never sends it. Adds the optional coordinateDensity number. The daemon reads it only on a coordinateUnit dp request, which a new client sends only to a daemon that reports android-dp-coordinates; a released daemon ignores the unknown meta key, and a released client never sends it." + "digest": "sha256:a89feccb277139aa9dd89072947818782d892052e698a31180320e0da33db28c", + "rationale": "Adds the optional developerDir field: a local client's DEVELOPER_DIR, overlaid on the env of commands the daemon spawns for that request. A released daemon ignores the unknown meta key and keeps its own environment, exactly as before; a released client never sends it, so the new daemon inherits its own environment for that request. The remote HTTP surface strips it. Also adds the optional leaseRetainOnClose field, sent only on lease_allocate when the caller opts in: a released daemon ignores the unknown meta key and releases the lease on session close as before, and a released client never sends it. Adds the optional providerCredentialFingerprint field: a digest of the local caller's provider credential variables, which the daemon compares with its own on lease_allocate. A released daemon ignores the unknown meta key and allocates as before; a released client never sends it, so the new daemon skips the comparison. The client sends it only to a local daemon, and the remote HTTP surface strips it. #4511 adds the optional scriptPublicationId string, which a new client sends only on a remote open --save-script to a daemon that reports the script-artifacts capability. Any other request keeps its previous meta. Adds the optional coordinateUnit field ('native' | 'dp'). A released daemon ignores the unknown meta key and answers in native units with no coordinates label, and a new client sends it only after the daemon's /health reports android-dp-coordinates, refusing the call before the send with dp_coordinates_unsupported otherwise; a released client never sends it. Adds the optional coordinateDensity number. The daemon reads it only on a coordinateUnit dp request, which a new client sends only to a daemon that reports android-dp-coordinates; a released daemon ignores the unknown meta key, and a released client never sends it. Adds optional captureId metadata on trace and native perf start/stop. A released daemon ignores the unknown meta key and keeps its prior capture behavior; a released client omits it. The new daemon still completes a pathless stop from a released client, but can omit the saved destination when the capture identity was absent. The protocol-3 treatment of that destination change remains open. A new client reuses a saved destination only when the daemon response confirms the live capture identity. Routes, authentication, and framing are unchanged under ADR 0006." }, { "declaration": "packages/kernel/src/contracts.ts#DaemonArtifactKnownType", @@ -286,6 +286,16 @@ "digest": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "rationale": "#2246 selects a file or directory destination once. Directory downloads stage and safely extract beside the destination, propagate timeout cancellation through both operations, and atomically rename the complete top-level entry; returning that local path is client-only state. The GET /artifacts/:id request and response framing, and every existing file artifact call site's behavior, are unchanged. #4511 passes every download parameter, including the new client-local maxBytes, through to the downloader instead of copying each field. The GET /artifacts/:id request and response framing are unchanged." }, + { + "declaration": "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact", + "digest": "sha256:d8fcb526605e7a255198fb530fc6b22fcda0788ab30f0f83462559ba81a9ad0b", + "rationale": "Client-only artifact handling under ADR 0006: only a test response's artifactsDir field with test-artifacts type selects local directory extraction. Other artifacts use the existing GET /artifacts/:id request and file download. No request field, route, authentication rule, response framing, or daemon output changes. An older daemon's artifact record still parses; a new client only narrows its local extraction decision." + }, + { + "declaration": "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath", + "digest": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", + "rationale": "Client-only artifact destination selection under ADR 0006: a Windows file name containing a colon is refused before a local write, so a daemon cannot select an alternate data stream. The existing GET /artifacts/:id request, artifact record parsing, and response framing are unchanged. An unsafe artifact is dropped locally with a warning while the command result keeps its outcome." + }, { "declaration": "packages/daemon-client/src/daemon-client-rpc.ts#buildHttpRpcPayload", "digest": "sha256:8978ef89d3af866bd94fec52c586a0cbf3217ee9e60952fbc826e8208e5fa158", @@ -543,8 +553,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", - "rationale": "#4518 and #4661 change client-side destination selection. Authorized destinations keep precedence. Fallbacks reject NUL names, and ordinary captures reject explicit non-string names and Windows drive-qualified basenames under Windows path rules. Daemons send the same artifact fields with the same framing." + "digest": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", + "rationale": "Client-side materialization now chooses a unique filename for every unnamed remote artifact, including recordings, and still honors an explicit caller path. It ignores daemon-provided localPath as a destination and uses the daemon filename only as a sanitized stem. The daemon sends the same fields and framing, and an older peer can ignore this client's local destination choice." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", @@ -668,8 +678,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts", - "digest": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download. Which artifacts are requested is unchanged, and the wire fields are unchanged; the client no longer adds a repeat warning to its own output. The GET /artifacts/:id request, its headers and the response framing are unchanged, so a peer on the same protocol sees the same bytes." + "digest": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", + "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download, and retires a client-local capture destination before downloading a successful stop's artifacts. A pathless stop can carry the existing optional meta.clientArtifactPaths.outPath from client state; an older daemon can ignore that hint or use it as before. An older client receives the same response and retains its fallback. A new client uses the destination recorded with the confirmed live capture ID for a pathless stop; an unconfirmed response gets a fresh client cwd name. A released daemon ignores optional captureId metadata, so this client-only destination choice does not change peer parsing. The GET /artifacts/:id request, headers, artifact fields, and response framing are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#publishScriptVersion", diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index e3a89daa61d..35cc8cb8229 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -599,6 +599,14 @@ These reasons can come from more than one command. | `ARCHIVE_UNSAFE_ENTRY` | The archive holds a link, a special file, or an encrypted entry. | | `ARCHIVE_UNSAFE_PATH` | An archive entry's name is absolute, escaping, or otherwise not one relative path. | +### Capture identity + +| Reason | Meaning | +| --- | --- | +| `capture-already-active` | A capture already runs for this session; the response names its live capture ID when one was minted. | +| `capture-identity-mismatch` | The daemon refuses a stop with the wrong capture ID. The client also refuses a pathless stop when a settled record identifies a foreign live capture. An explicit caller path can still stop it. | +| `capture-record-invalid` | The local capture destination record is unreadable or malformed, so no remote capture command is sent. | + ### Command flags | Reason | Meaning | diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 0a71f2c0a50..a4bf9e1b122 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -94,14 +94,15 @@ The daemon itself cannot pick a device by these keys, so it refuses a named key Remote screenshots, recordings, performance captures, and trace logs use generated output paths on the daemon. When you specify an output path through the CLI, SDK, or MCP, it selects the download -destination on your machine. A recording is different: it downloads to the path named by the -`record stop` request, or otherwise to the working directory with a warning. The directory of a -`record start` path does not carry over; the working-directory fallback keeps only its file name. Direct RPC callers receive artifact IDs and download each result with -`GET /artifacts/` using the same authentication. - -For trace and performance stop or report, a destination on the current request wins. Without one, -the client uses a path the daemon echoes from an earlier start request when present. If neither -path is present, it downloads to the working directory using the artifact file name. +destination on your machine. A recording downloads to the path named by the `record stop` +request. Without one, it downloads to a unique file in the working directory with a warning. +The directory of a `record start` path does not carry over. Direct RPC callers receive artifact IDs +and download each result with `GET /artifacts/` using the same authentication. + +For an artifact without a destination on the current request, the client uses a recorded start path +for a trace or performance stop when one exists. Otherwise, it appends a unique suffix to the +artifact file name in its working directory. A daemon-provided name or path cannot select an +existing client file. 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 From 6fff8dc6f65dc4a1f22fdfcfa2325f815409a2d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:31:31 +0100 Subject: [PATCH 02/13] test(remote): expect unique recording download name --- .../provider-scenarios/remote-daemon-client.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/integration/provider-scenarios/remote-daemon-client.test.ts b/test/integration/provider-scenarios/remote-daemon-client.test.ts index ca2e0a2d1f4..bfbd23526c0 100644 --- a/test/integration/provider-scenarios/remote-daemon-client.test.ts +++ b/test/integration/provider-scenarios/remote-daemon-client.test.ts @@ -549,11 +549,15 @@ async function assertRecordingArtifactRoundTrip( assert.equal(fs.existsSync(paths.recordingPath), false); // #4518: a remote stop never writes to the daemon's localPath echo. It lands in the client cwd - // under the daemon's file name and reports that fallback. + // under a unique client filename and reports that fallback. const stop = await client.recording.record({ action: 'stop' }); assert.equal(stop.recording, 'stopped'); - const landed = path.join(paths.cwd, 'remote-recording.mp4'); - assert.equal(stop.outPath, landed); + const landed = stop.outPath; + assert.equal(path.dirname(landed), paths.cwd); + assert.match( + path.basename(landed), + /^remote-recording-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}\.mp4$/, + ); assert.deepEqual(fs.readFileSync(landed), RECORDING_BYTES); assert.equal(fs.existsSync(paths.recordingPath), false); assert.deepEqual( From 1585ca7e5fdc55b3eca42e9dcd44ee6764325a3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:00:05 +0100 Subject: [PATCH 03/13] docs: condense remote capture guidance --- docs/agents/security.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 64d0a59ca7b..49b8476b162 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -3,9 +3,8 @@ The CLI client trusts its caller to choose local destinations. The client trusts a remote daemon for data and validated identifiers. Scripts and remote record stop reject daemon paths (#4518). -For pathless remote trace and perf stops, reuse a saved caller path only when the daemon confirms its capture ID. -Give unnamed remote artifacts unique names in the client working directory. -If the saved capture ID identifies a foreign live capture, refuse a pathless stop. +Remote trace and perf stops reuse caller paths only after capture ID confirmation; they refuse foreign captures. +Unnamed remote artifacts get unique client filenames. The daemon admits its state directory. Nobody trusts the network or other local users. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. From 8de1e740b9b06608e534a34e0be0147391b85be8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:36:16 +0100 Subject: [PATCH 04/13] docs: remove redundant remote script guidance --- docs/agents/security.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 49b8476b162..df79ecdea77 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,11 +1,11 @@ # Security boundaries -The CLI client trusts its caller to choose local destinations. -The client trusts a remote daemon for data and validated identifiers. +The CLI caller chooses local destinations. +The client trusts daemon data and validated identifiers. Scripts and remote record stop reject daemon paths (#4518). -Remote trace and perf stops reuse caller paths only after capture ID confirmation; they refuse foreign captures. -Unnamed remote artifacts get unique client filenames. -The daemon admits its state directory. Nobody trusts the network or other local users. +For trace and perf stops, reuse caller paths only after capture ID confirmation. +Give unnamed artifacts unique client filenames. +The daemon admits its state directory; network and other users are untrusted. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. @@ -13,7 +13,6 @@ ADR 0041 owns credential transport. ADR 0016 judges caller-named script destinations on POSIX against the writing process's uid. Both script publishers commit in the judged directory. -Remote script delivery caps in-memory bytes and error answers. ## Proposed in #4669 From 3ee9563fa68649ad67263d8a6d6713cafe02d06f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 11:31:05 +0100 Subject: [PATCH 05/13] docs(security): retain script delivery limit --- docs/agents/security.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/agents/security.md b/docs/agents/security.md index df79ecdea77..f792109d6ff 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -13,6 +13,7 @@ ADR 0041 owns credential transport. ADR 0016 judges caller-named script destinations on POSIX against the writing process's uid. Both script publishers commit in the judged directory. +Remote script delivery caps in-memory bytes and error answers. ## Proposed in #4669 From ccb1a2c2451cbfd5d53e4e189209f59b3ed52bc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 11:50:43 +0100 Subject: [PATCH 06/13] docs(security): keep guidance within context budget --- docs/agents/security.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index f792109d6ff..8e26ce132fb 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -3,7 +3,7 @@ The CLI caller chooses local destinations. The client trusts daemon data and validated identifiers. Scripts and remote record stop reject daemon paths (#4518). -For trace and perf stops, reuse caller paths only after capture ID confirmation. +Trace and perf stops reuse caller paths only after capture ID confirmation. Give unnamed artifacts unique client filenames. The daemon admits its state directory; network and other users are untrusted. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. @@ -17,6 +17,6 @@ Remote script delivery caps in-memory bytes and error answers. ## Proposed in #4669 -#4669 proposes private writes for credentials, client state, and daemon state (#4649): create each under a verified state root, and never write through a link at the final name. +#4669 proposes private writes for credentials, client state, and daemon state (#4649) under a verified state root, without final-name links. Do not apply these before #4669 is approved. -Do not apply the ADR 0016 walk to other outputs. Screenshot `--out`, contact sheets, JUnit, traces, recordings keep a plain write to the path the caller names. +Do not apply the ADR 0016 walk to other outputs. Screenshot `--out`, contact sheets, JUnit, traces, and recordings use plain writes to caller paths. From ffee06e5f4630e8160a2911bddd307a2e8b2b36c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:38:30 +0100 Subject: [PATCH 07/13] fix(remote): tighten capture destination ownership and settlement --- docs/agents/security.md | 7 +- packages/daemon-client/src/index.ts | 8 +- .../src/core/session-capture-binding.ts | 5 +- packages/daemon/src/core/session-state.ts | 3 +- .../http/http-server-remote-output.test.ts | 18 +- .../handlers/__tests__/trace-runtime.test.ts | 36 +++ .../src/sessions/handlers/trace-runtime.ts | 16 +- .../__tests__/session-perf-runtime.test.ts | 256 ++++++++-------- .../internal/session-perf-runtime.ts | 20 +- .../capture-destination-record.test.ts | 287 +++++++++++------- .../remote/src/capture-destination-record.ts | 219 +++++++------ packages/remote/src/daemon-artifacts.ts | 6 +- src/commands/schema/cli-help-workflows.ts | 2 +- website/docs/docs/remote-proxy.md | 9 +- 14 files changed, 505 insertions(+), 387 deletions(-) diff --git a/docs/agents/security.md b/docs/agents/security.md index 8e26ce132fb..73094a46891 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -1,10 +1,9 @@ # Security boundaries -The CLI caller chooses local destinations. -The client trusts daemon data and validated identifiers. +The caller chooses local destinations. Scripts and remote record stop reject daemon paths (#4518). -Trace and perf stops reuse caller paths only after capture ID confirmation. -Give unnamed artifacts unique client filenames. +Pathless trace and perf stops require a matching capture ID to reuse start paths. +When the capture is foreign, specify a stop path. The daemon admits its state directory; network and other users are untrusted. Out of scope: same uid, hostile root, ACLs, mounts, untrusted filesystems. ADR 0041 owns credential transport. diff --git a/packages/daemon-client/src/index.ts b/packages/daemon-client/src/index.ts index 143a4268157..a13f69b6fb9 100644 --- a/packages/daemon-client/src/index.ts +++ b/packages/daemon-client/src/index.ts @@ -190,7 +190,13 @@ async function sendToDaemonOnHost( if (!info.baseUrl) return await send(request); if (request.meta?.clientArtifactPaths?.savedScript) return await sendRemoteScriptOpen(info, request, settings.paths.baseDir, send); - return await sendRemoteCapture(info.baseUrl, request, settings.paths.baseDir, send); + return await sendRemoteCapture( + info.baseUrl, + request, + settings.paths.baseDir, + send, + options.signal, + ); }, { requestId, command: req.command }, ); diff --git a/packages/daemon/src/core/session-capture-binding.ts b/packages/daemon/src/core/session-capture-binding.ts index 4b84035e171..6c6d4faa9fb 100644 --- a/packages/daemon/src/core/session-capture-binding.ts +++ b/packages/daemon/src/core/session-capture-binding.ts @@ -38,14 +38,13 @@ export function bindSessionAudioProbe(sessionStore: SessionStore, ref: SessionRe export function bindSessionPerfCapture( sessionStore: SessionStore, ref: SessionRef, - clientOutPath?: string, - clientCaptureId?: string, + captureIdentity?: { clientCaptureId: string; clientOutPath?: string }, ) { return bindSessionCapture(sessionStore, ref, { read: (session) => session.perfCapture, write: (perfCapture) => { sessionStore.update(ref, { - perfCapture: perfCapture ? { ...perfCapture, clientOutPath, clientCaptureId } : undefined, + perfCapture: perfCapture ? { ...perfCapture, captureIdentity } : undefined, }); }, }); diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index aef1385b1e2..8cc67bca357 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -232,8 +232,7 @@ export type SessionState = { }; /** Native profiling mechanics stay behind one exact-owner durable handle. */ perfCapture?: { - clientCaptureId?: string; - clientOutPath?: string; + captureIdentity?: { clientCaptureId: string; clientOutPath?: string }; handle: PerfNativeCaptureLiveHandle; envelope: DurableResourceEnvelope<'perf-capture'>; }; 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 3762f2e7d1c..efdce1ec64d 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 @@ -785,9 +785,13 @@ test('remote perf memory output reaches the runtime only as a session artifact a }); }); -test.each(['./capture.log', undefined])( - 'remote trace start/stop retains only a client destination (%s)', - async (destination) => { +test.each([ + { destination: './capture.log', stopId: 'capture-a' }, + { destination: './capture.log', stopId: undefined }, + { destination: undefined, stopId: 'capture-a' }, +])( + 'remote trace start/stop retains a client destination $destination only with ID $stopId', + async ({ destination, stopId }) => { const root = mkdtempForTestSync('remote-trace-client-'); const clientRoot = path.join(root, 'client'); const sessionStore = makeSessionStore('remote-trace-session-'); @@ -814,6 +818,7 @@ test.each(['./capture.log', undefined])( ...req, meta: { ...req.meta, + captureId: 'capture-a', ...(clientPath ? { clientArtifactPaths: { outPath: clientPath } } : {}), }, }); @@ -825,13 +830,14 @@ test.each(['./capture.log', undefined])( command: 'trace', session: 'capture', positionals: ['stop'], - meta: { cwd: clientRoot }, + meta: { cwd: clientRoot, captureId: stopId }, }; const stopped = await post(stopRequest); expect(stopped.result?.ok, JSON.stringify(stopped)).toBe(true); const artifact = stopped.result?.data?.artifacts?.[0]; - expect(artifact?.localPath).toBe(clientPath); - expect(artifact?.fileName).toBe(path.basename(clientPath ?? output)); + const expectedPath = stopId ? clientPath : undefined; + expect(artifact?.localPath).toBe(expectedPath); + expect(artifact?.fileName).toBe(path.basename(expectedPath ?? output)); const download = await fetch(`${baseUrl}/artifacts/${artifact?.artifactId}`, { headers: { authorization: 'Bearer test-token' }, }); diff --git a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts index 99ea84bcd7f..d0eaf357168 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts @@ -79,6 +79,16 @@ test('starts and stops one trace through the session-owned trace slot', () => { test('a stale client capture identity cannot stop a reopened trace', () => { const { session, sessionStore } = fixture(); const host = createTestHostEnvironment(); + for (const action of ['start', 'stop']) { + expect( + handleTraceCommand({ + host, + req: request([action], undefined, 'capture-a'), + sessionName: session.name, + sessionStore, + }), + ).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-a' } }); + } const started = handleTraceCommand({ host, req: request(['start'], undefined, 'capture-b'), @@ -106,6 +116,32 @@ test('a stale client capture identity cannot stop a reopened trace', () => { expect(stopped).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); }); +test('a pathless stop without a capture ID omits the prior client destination', () => { + const { root, session, sessionStore } = fixture(); + const host = createTestHostEnvironment(); + const clientPath = path.join(root, 'client.trace'); + const daemonPath = path.join(root, 'daemon.trace'); + handleTraceCommand({ + host, + req: request(['start', daemonPath], clientPath, 'capture-a'), + sessionName: session.name, + sessionStore, + }); + const stopped = handleTraceCommand({ + host, + req: request(['stop']), + sessionName: session.name, + sessionStore, + }); + expect(stopped).toMatchObject({ + ok: true, + data: { + clientCaptureId: 'capture-a', + artifacts: [{ localPath: daemonPath }], + }, + }); +}); + test('relocates trace output and projects the client artifact path', () => { const { root, session, sessionStore } = fixture(); const original = path.join(root, 'original.trace'); diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index 846fbd18ed1..fe475ea04f2 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -3,7 +3,11 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { expandSessionPath } from '@agent-device/host-kit/session-paths'; import fs from 'node:fs'; import path from 'node:path'; -import { parseTraceAction, TRACE_ACTION_REQUIRED_MESSAGE } from '@agent-device/contracts/recording'; +import { + parseTraceAction, + TRACE_ACTION_REQUIRED_MESSAGE, + type TraceCommandResult, +} from '@agent-device/contracts/recording'; import type { SessionStore } from '../../core/session-store.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { requestCwd } from '../../core/context.ts'; @@ -12,7 +16,6 @@ import { recordSessionAction } from '../../core/session-action-recorder.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; import { captureIdentityRefusal } from '../../core/capture-identity-refusal.ts'; -import type { TraceCommandResult } from '@agent-device/contracts/recording'; export function handleTraceCommand(params: { host: HostEnvironment; @@ -48,7 +51,7 @@ function startTrace( outPath, clientCaptureId: req.meta?.captureId, startedAt: Date.now(), - clientOutPath: req.meta?.clientArtifactPaths?.outPath, + clientOutPath: req.meta?.captureId ? req.meta.clientArtifactPaths?.outPath : undefined, ...(req.internal?.publicNetworkOnly ? { remoteCaptureOutputPath: outPath } : {}), remoteCaptureTenantId: session.lease?.tenantId ?? req.meta?.tenantId, }; @@ -71,9 +74,10 @@ function stopTrace( ): DaemonResponse { const session = sessionStore.requireCurrent(ref); if (!session.trace) return errorResponse('INVALID_ARGS', 'no active trace'); - if (req.meta?.captureId && req.meta.captureId !== session.trace.clientCaptureId) - return captureIdentityRefusal('trace', 'mismatch'); + const requestedCaptureId = req.meta?.captureId; const clientCaptureId = session.trace.clientCaptureId; + if (requestedCaptureId && requestedCaptureId !== clientCaptureId) + return captureIdentityRefusal('trace', 'mismatch'); const outPath = relocateTraceOutput( requestCwd(req, host), session.trace.outPath, @@ -83,7 +87,7 @@ function stopTrace( const tenantId = session.trace.remoteCaptureTenantId; const clientOutPath = req.meta?.clientArtifactPaths?.outPath ?? - session.trace.clientOutPath ?? + (requestedCaptureId ? session.trace.clientOutPath : undefined) ?? (req.internal?.publicNetworkOnly ? undefined : outPath); session.trace = undefined; recordSessionAction(sessionStore, ref, req, req.command, { action: 'stop', outPath }); diff --git a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts index fc5951a685f..d7a9de1f6ef 100644 --- a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts +++ b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts @@ -154,138 +154,144 @@ test('perf refuses from owner facts before binding', async () => { } }); -test('perf native capture is adopted durably and stop uses the live handle without rebinding', async () => { - const sessionStore = makeStore(); - const device = sessionStore.get('android')!.device; - const finish = vi.fn(async () => ({ - status: 'completed' as const, - result: { - kind: 'xctrace', - mode: 'trace', - state: 'stopped', - outPath: '/tmp/app.trace', - } as const, - })); - const handle: PerfNativeCaptureLiveHandle = { - inspect: () => ({ kind: 'xctrace', mode: 'trace', state: 'running' }), - setOutputPath: vi.fn(), - finish, - forceCleanup: async () => ({ status: 'cleaned' }), - [Symbol.asyncDispose]: async () => {}, - }; - const perfNativeCaptureStart = vi.fn( - async (input: Parameters[0]) => ({ - pendingHandle: new PendingTransferGuard(handle), - envelope: createDurableResourceEnvelope({ - resourceKind: 'perf-capture', - sessionId: input.sessionId, - device: deviceIdentity(device), - owner: localRuntimeOwner('android'), - fence: input.fence, - lifecycle: 'open', - descriptor: { version: 1, body: { kind: 'fixture' } }, - }), - response: { +test.each([ + { captureId: 'capture-b', expectedClientOutPath: '/client/app.trace' }, + { captureId: undefined, expectedClientOutPath: undefined }, +])( + 'perf stop with capture ID $captureId uses the adopted handle', + async ({ captureId, expectedClientOutPath }) => { + const sessionStore = makeStore(); + const device = sessionStore.get('android')!.device; + const finish = vi.fn(async () => ({ + status: 'completed' as const, + result: { kind: 'xctrace', mode: 'trace', - state: 'running', - outPath: input.outPath, + state: 'stopped', + outPath: '/tmp/app.trace', } as const, - }), - ); - const runtime = createPerfRuntime({ perfNativeCaptureStart }); - const common = { - sessionName: 'android', - sessionStore, - inspectFacts: runtime.inspectFacts, - bindDevice: runtime.bindDevice, - perfCaptureAdmissionLedger: createPerfCaptureAdmissionLedger(), - throwIfCanceled: () => {}, - }; - - const startResponse = await handleSessionObservabilityCommands({ - host: createTestHostEnvironment(), - platformServices: daemonPlatformServicesFixture(), - ...common, - req: { - token: 't', - session: 'android', - command: 'perf', - positionals: ['trace', 'start', 'xctrace'], - flags: { out: '/tmp/app.trace' }, - meta: { clientArtifactPaths: { outPath: '/client/app.trace' }, captureId: 'capture-b' }, - }, - }); - assert.equal(startResponse?.ok, true, JSON.stringify(startResponse)); - assert.equal(startResponse?.data?.clientCaptureId, 'capture-b'); - assert.ok(sessionStore.get('android')?.perfCapture); - assert.deepEqual( - sessionStore.get('android')?.actions.map(({ command }) => command), - ['perf'], - ); + })); + const handle: PerfNativeCaptureLiveHandle = { + inspect: () => ({ kind: 'xctrace', mode: 'trace', state: 'running' }), + setOutputPath: vi.fn(), + finish, + forceCleanup: async () => ({ status: 'cleaned' }), + [Symbol.asyncDispose]: async () => {}, + }; + const perfNativeCaptureStart = vi.fn( + async (input: Parameters[0]) => ({ + pendingHandle: new PendingTransferGuard(handle), + envelope: createDurableResourceEnvelope({ + resourceKind: 'perf-capture', + sessionId: input.sessionId, + device: deviceIdentity(device), + owner: localRuntimeOwner('android'), + fence: input.fence, + lifecycle: 'open', + descriptor: { version: 1, body: { kind: 'fixture' } }, + }), + response: { + kind: 'xctrace', + mode: 'trace', + state: 'running', + outPath: input.outPath, + } as const, + }), + ); + const runtime = createPerfRuntime({ perfNativeCaptureStart }); + const common = { + sessionName: 'android', + sessionStore, + inspectFacts: runtime.inspectFacts, + bindDevice: runtime.bindDevice, + perfCaptureAdmissionLedger: createPerfCaptureAdmissionLedger(), + throwIfCanceled: () => {}, + }; - const wrongModeResponse = await handleSessionObservabilityCommands({ - host: createTestHostEnvironment(), - platformServices: daemonPlatformServicesFixture(), - ...common, - req: { - token: 't', - session: 'android', - command: 'perf', - positionals: ['cpu', 'profile', 'stop', 'xctrace'], - }, - }); - assert.equal(wrongModeResponse?.ok, false); - if (wrongModeResponse && !wrongModeResponse.ok) { - assert.equal( - wrongModeResponse.error.message, - 'No xctrace cpu-profile is active for this session.', + const startResponse = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['trace', 'start', 'xctrace'], + flags: { out: '/tmp/app.trace' }, + meta: { clientArtifactPaths: { outPath: '/client/app.trace' }, captureId: 'capture-b' }, + }, + }); + assert.equal(startResponse?.ok, true, JSON.stringify(startResponse)); + assert.equal(startResponse?.data?.clientCaptureId, 'capture-b'); + assert.ok(sessionStore.get('android')?.perfCapture); + assert.deepEqual( + sessionStore.get('android')?.actions.map(({ command }) => command), + ['perf'], ); - } - assert.equal(finish.mock.calls.length, 0); - assert.ok(sessionStore.get('android')?.perfCapture); - assert.equal(sessionStore.get('android')?.actions.length, 1); - const staleStop = await handleSessionObservabilityCommands({ - host: createTestHostEnvironment(), - platformServices: daemonPlatformServicesFixture(), - ...common, - req: { - token: 't', - session: 'android', - command: 'perf', - positionals: ['trace', 'stop', 'xctrace'], - meta: { captureId: 'capture-a' }, - }, - }); - assert.equal(staleStop?.ok, false); - if (staleStop && !staleStop.ok) - assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); - assert.equal(finish.mock.calls.length, 0); + const wrongModeResponse = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['cpu', 'profile', 'stop', 'xctrace'], + }, + }); + assert.equal(wrongModeResponse?.ok, false); + if (wrongModeResponse && !wrongModeResponse.ok) { + assert.equal( + wrongModeResponse.error.message, + 'No xctrace cpu-profile is active for this session.', + ); + } + assert.equal(finish.mock.calls.length, 0); + assert.ok(sessionStore.get('android')?.perfCapture); + assert.equal(sessionStore.get('android')?.actions.length, 1); - const stopResponse = await handleSessionObservabilityCommands({ - host: createTestHostEnvironment(), - platformServices: daemonPlatformServicesFixture(), - ...common, - req: { - token: 't', - session: 'android', - command: 'perf', - positionals: ['trace', 'stop', 'xctrace'], - meta: { captureId: 'capture-b' }, - }, - }); - assert.equal(stopResponse?.ok, true, JSON.stringify(stopResponse)); - if (stopResponse?.ok) assert.equal(stopResponse.data?.clientOutPath, '/client/app.trace'); - if (stopResponse?.ok) assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); - assert.equal(finish.mock.calls.length, 1); - assert.deepEqual(runtime.uses, [['perfNativeCaptureStart']]); - assert.equal(sessionStore.get('android')?.perfCapture, undefined); - assert.deepEqual( - sessionStore.get('android')?.actions.map(({ command }) => command), - ['perf', 'perf'], - ); -}); + const staleStop = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId: 'capture-a' }, + }, + }); + assert.equal(staleStop?.ok, false); + if (staleStop && !staleStop.ok) + assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); + assert.equal(finish.mock.calls.length, 0); + + const stopResponse = await handleSessionObservabilityCommands({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + ...common, + req: { + token: 't', + session: 'android', + command: 'perf', + positionals: ['trace', 'stop', 'xctrace'], + meta: { captureId }, + }, + }); + assert.equal(stopResponse?.ok, true, JSON.stringify(stopResponse)); + if (stopResponse?.ok) assert.equal(stopResponse.data?.clientOutPath, expectedClientOutPath); + if (stopResponse?.ok) assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); + assert.equal(finish.mock.calls.length, 1); + assert.deepEqual(runtime.uses, [['perfNativeCaptureStart']]); + assert.equal(sessionStore.get('android')?.perfCapture, undefined); + assert.deepEqual( + sessionStore.get('android')?.actions.map(({ command }) => command), + ['perf', 'perf'], + ); + }, +); test.each([ { evidence: 'runtime descriptor', descriptor: { version: 1, body: { captureId: 'owned' } } }, diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index a5bfffa32df..2798a587434 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -220,7 +220,7 @@ async function startPerfCapture( return captureIdentityRefusal( 'native perf', 'already-active', - session.perfCapture.clientCaptureId, + session.perfCapture.captureIdentity?.clientCaptureId, ); } if (!session.appBundleId) { @@ -244,11 +244,13 @@ async function startPerfCapture( resourcePath, device: session.device, }); + const clientCaptureId = params.req.meta?.captureId; const binding = bindSessionPerfCapture( params.sessionStore, params.ref, - params.req.meta?.clientArtifactPaths?.outPath, - params.req.meta?.captureId, + clientCaptureId + ? { clientCaptureId, clientOutPath: params.req.meta?.clientArtifactPaths?.outPath } + : undefined, ); binding.assertAdoptable(); const started = await runtime.operations @@ -302,7 +304,7 @@ async function startPerfCapture( ok: true, data: { ...started.response, - ...(params.req.meta?.captureId ? { clientCaptureId: params.req.meta.captureId } : {}), + ...(clientCaptureId ? { clientCaptureId } : {}), }, }; } @@ -323,7 +325,9 @@ async function stopPerfCapture( ): Promise { const capture = session.perfCapture; if (!capture) return errorResponse('INVALID_ARGS', 'no active native perf capture'); - if (params.req.meta?.captureId && params.req.meta.captureId !== capture.clientCaptureId) + const requestedCaptureId = params.req.meta?.captureId; + const clientCaptureId = capture.captureIdentity?.clientCaptureId; + if (requestedCaptureId && requestedCaptureId !== clientCaptureId) return captureIdentityRefusal('native perf', 'mismatch'); const snapshot = capture.handle.inspect(); const mismatchMessage = perfCaptureStopMismatch(snapshot, request); @@ -341,7 +345,9 @@ async function stopPerfCapture( const profile = readProfileHandoff(completion); params.sessionStore.update(params.ref, { lastPerfProfile: profile }); } - const clientOutPath = params.req.meta?.clientArtifactPaths?.outPath ?? capture.clientOutPath; + const clientOutPath = + params.req.meta?.clientArtifactPaths?.outPath ?? + (requestedCaptureId ? capture.captureIdentity?.clientOutPath : undefined); const tenantId = typeof capture.envelope.metadata?.remoteCaptureTenantId === 'string' ? capture.envelope.metadata.remoteCaptureTenantId @@ -352,7 +358,7 @@ async function stopPerfCapture( { ...completion, ...(clientOutPath ? { clientOutPath } : {}), - ...(capture.clientCaptureId ? { clientCaptureId: capture.clientCaptureId } : {}), + ...(clientCaptureId ? { clientCaptureId } : {}), }, capture.envelope.metadata?.remoteCaptureOutputPath === completion.outPath ? 'daemon' diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 07e642d817d..518e3e2b96a 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -1,14 +1,23 @@ import fs from 'node:fs'; +import http from 'node:http'; import path from 'node:path'; -import { test, expect } from 'vitest'; -import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { test, expect, vi } from 'vitest'; +import { + closeLoopbackServer, + createTestHostEnvironment, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { acquireProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; -import { AppError } from '@agent-device/kernel/errors'; import { - confirmedCaptureStopRequest, - sendRemoteCapture, - retireSuccessfulCaptureStop, -} from '../capture-destination-record.ts'; + AppError, + createRequestCanceledError, + REQUEST_CANCELED_REASONS, +} from '@agent-device/kernel/errors'; +import { sendRemoteCapture, settleCaptureStop } from '../capture-destination-record.ts'; import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; const endpoint = 'https://capture.example.test/api'; @@ -28,10 +37,11 @@ function request( runId?: string; leaseId?: string; session?: string; + token?: string; } = {}, ): DaemonWireRequest { return { - token: 'test', + token: options.token ?? 'test', command: options.family ?? 'trace', session: options.session ?? 'device-a', positionals: @@ -49,56 +59,119 @@ function captureRecordPath(stateDir: string): string { const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); const [scope] = fs.readdirSync(root); if (!scope) throw new Error('Missing capture session record directory'); - const [recordName] = fs.readdirSync(path.join(root, scope)); + const recordName = fs + .readdirSync(path.join(root, scope)) + .find((entry) => entry.endsWith('.json')); if (!recordName) throw new Error('Missing capture record'); return path.join(root, scope, recordName); } -test.each(['trace', 'perf'] as const)( - '%s stop replays its own start path and retires it', - async (family) => { - const stateDir = mkdtempForTestSync('capture-destination-'); - const destination = '/client/captures/owned.trace'; - await sendRemoteCapture( - endpoint, - request('start', destination, { family }), - stateDir, - async (req) => confirmed(req), - ); - const sent: DaemonWireRequest[] = []; - await sendRemoteCapture( - endpoint, - request('stop', undefined, { family }), - stateDir, - async (req) => { - sent.push(req); - const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe(destination); - await materializeRemoteArtifacts( - { baseUrl: endpoint, token: 'test' }, - req, - answer, - createTestHostEnvironment(), - stateDir, - ); - return answer; - }, - ); - expect(sent[0]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); - expect(sent[0]?.meta?.captureId).toBeTypeOf('string'); - await sendRemoteCapture( +test('cancels a stop while another request owns the capture record lock', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start'), stateDir, async (req) => confirmed(req)); + const release = await acquireProcessLock({ + lockDirPath: captureRecordPath(stateDir) + '.lock', + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + }); + const controller = new AbortController(); + try { + const stop = sendRemoteCapture( endpoint, - request('stop', undefined, { family }), + request('stop'), stateDir, - async (req) => { - sent.push(req); - return success; + async () => { + throw new Error('stop should not be sent'); }, + controller.signal, ); - expect(sent[1]?.meta?.clientArtifactPaths?.outPath).toBeUndefined(); - expect(sent[1]?.meta?.captureId).toBeUndefined(); + controller.abort(); + await expect(stop).rejects.toMatchObject({ + details: { reason: REQUEST_CANCELED_REASONS.canceled.reason }, + }); + } finally { + await release(); + } +}); + +test('a canceled start reports cancellation while the record cleanup is contended', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const canceled = createRequestCanceledError(); + let release: (() => Promise) | undefined; + const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + release = await acquireProcessLock({ + lockDirPath: captureRecordPath(stateDir) + '.lock', + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + }); + throw canceled; + }); + try { + await expect(start).rejects.toBe(canceled); + } finally { + await release?.(); + } + const record = captureRecordPath(stateDir); + await vi.waitFor(() => { + expect(JSON.parse(fs.readFileSync(record, 'utf8'))).toMatchObject({ + pending: [], + certainty: 'unknown', + }); + }); +}); + +test.for(['trace', 'perf'] as const)( + '%s stop downloads to its own start path and retires it', + async (family, context) => { + if (await skipWhenLoopbackUnavailable(context, 'remote capture download')) return; + const stateDir = mkdtempForTestSync('capture-destination-'); + const destination = path.join(stateDir, 'owned.trace'); + const server = http.createServer((_req, res) => res.end('capture bytes')); + try { + const port = await listenOnLoopback(server); + const baseUrl = `http://127.0.0.1:${port}`; + await sendRemoteCapture( + baseUrl, + request('start', destination, { family }), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture( + baseUrl, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(req.meta?.captureId).toBeTypeOf('string'); + const response = await materializeRemoteArtifacts( + { baseUrl, token: 'test' }, + req, + { + ok: true, + data: { + clientCaptureId: req.meta?.captureId, + artifacts: [{ artifactId: 'capture', field: 'outPath', fileName: 'capture.trace' }], + }, + }, + createTestHostEnvironment({ cwd: stateDir }), + stateDir, + ); + expect(response).toMatchObject({ ok: true, data: { outPath: destination } }); + return response; + }, + ); + expect(fs.readFileSync(destination, 'utf8')).toBe('capture bytes'); + await sendRemoteCapture( + baseUrl, + request('stop', undefined, { family }), + stateDir, + async (req) => { + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + expect(req.meta?.captureId).toBeUndefined(); + return success; + }, + ); + } finally { + await closeLoopbackServer(server); + } }, ); @@ -186,9 +259,9 @@ test.each(['trace', 'perf'] as const)( stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/first.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/first.trace', + ); return answer; }, ); @@ -230,9 +303,9 @@ test.each(['trace', 'perf'] as const)( async (req) => { expect(req.meta?.captureId).toBe(activeId); const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/first.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/first.trace', + ); return answer; }, ); @@ -358,9 +431,9 @@ test('a late explicit-stop reply cannot clear a newer confirmed capture', async await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.captureId).toBe(newerId); const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/new.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); return answer; }); }); @@ -443,7 +516,7 @@ test.each(['trace', 'perf'] as const)( expect(req.meta?.captureId).toBe(activeId); const answer = confirmed(req); expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, + (await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath, ).toBeUndefined(); return answer; }, @@ -545,9 +618,9 @@ test('a concurrent rejected start does not discard a newly confirmed start', asy await first; await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/first.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/first.trace', + ); return answer; }); }); @@ -583,9 +656,9 @@ test('failed close leaves the confirmed destination for a retry', async () => { ); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/old.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/old.trace', + ); return answer; }); }); @@ -682,9 +755,9 @@ test('a later confirmed start clears an earlier uncertain start', async () => { ); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/current.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/current.trace', + ); return answer; }); }); @@ -713,9 +786,9 @@ test('a late failed start cannot make a newer confirmed destination uncertain', await first; await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/new.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); return answer; }); }); @@ -747,32 +820,32 @@ test('a delayed close does not retire a capture confirmed after the close was se await close; await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/new.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); return answer; }); }); -test('missing or mismatched stop confirmation cannot select a saved path', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture( - endpoint, - request('start', '/client/owned.trace'), - stateDir, - async (req) => confirmed(req), - ); - await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect( - (await confirmedCaptureStopRequest(req, success)).meta?.clientArtifactPaths?.outPath, - ).toBeUndefined(); - expect( - (await confirmedCaptureStopRequest(req, { ok: true, data: { clientCaptureId: 'other' } })) - .meta?.clientArtifactPaths?.outPath, - ).toBeUndefined(); - return success; - }); -}); +test.each([undefined, 'other'])( + 'stop confirmation %s cannot select a saved path', + async (clientCaptureId) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + const response = { ok: true as const, data: { clientCaptureId } }; + expect( + (await settleCaptureStop(req, response)).meta?.clientArtifactPaths?.outPath, + ).toBeUndefined(); + return response; + }); + }, +); test.each(['returned', 'thrown'] as const)( 'repeated %s start failures keep one bounded fail-closed marker', @@ -797,14 +870,7 @@ test.each(['returned', 'thrown'] as const)( if (failure === 'thrown') await expect(start).rejects.toThrow('transport uncertain'); else expect((await start).ok).toBe(false); } - const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); - const [scope] = fs.readdirSync(root); - expect(scope).toBeDefined(); - if (!scope) throw new Error('Missing capture session record directory'); - const [recordName] = fs.readdirSync(path.join(root, scope)); - expect(recordName).toBeDefined(); - if (!recordName) throw new Error('Missing capture record'); - const record = JSON.parse(fs.readFileSync(path.join(root, scope, recordName), 'utf8')); + const record = JSON.parse(fs.readFileSync(captureRecordPath(stateDir), 'utf8')); expect(record.pending).toEqual([]); expect(record.certainty).toBe('unknown'); await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { @@ -847,9 +913,9 @@ test('a late successful start cannot replace a newer confirmed destination', asy await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { expect(req.meta?.captureId).toBe(newerCaptureId); const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/new.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); return answer; }); }); @@ -878,7 +944,7 @@ test('scope and explicit stop path cannot borrow or override another capture des stateDir, async (req) => { expect(req.meta?.clientArtifactPaths?.outPath).toBe('/client/explicit.trace'); - await retireSuccessfulCaptureStop(req); + await settleCaptureStop(req); return success; }, ); @@ -889,7 +955,7 @@ test('scope and explicit stop path cannot borrow or override another capture des }); }); -test('endpoint, tenant, run, lease, session, and capture kind each isolate destinations', async () => { +test('endpoint, credential, tenant, run, lease, session, and capture kind each isolate destinations', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture( endpoint, @@ -899,6 +965,7 @@ test('endpoint, tenant, run, lease, session, and capture kind each isolate desti ); const variants = [ { baseUrl: `${endpoint}/other`, options: { family: 'perf' as const } }, + { baseUrl: endpoint, options: { family: 'perf' as const, token: 'other' } }, { baseUrl: endpoint, options: { family: 'perf' as const, tenantId: 'tenant-b' } }, { baseUrl: endpoint, options: { family: 'perf' as const, runId: 'run-b' } }, { baseUrl: endpoint, options: { family: 'perf' as const, leaseId: 'lease-b' } }, @@ -919,9 +986,9 @@ test('endpoint, tenant, run, lease, session, and capture kind each isolate desti stateDir, async (req) => { const answer = confirmed(req); - expect( - (await confirmedCaptureStopRequest(req, answer)).meta?.clientArtifactPaths?.outPath, - ).toBe('/client/owned.trace'); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/owned.trace', + ); return answer; }, ); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 20ffe65394b..db8ef389391 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -5,7 +5,11 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { AppError, CAPTURE_IDENTITY_REASONS } from '@agent-device/kernel/errors'; +import { + AppError, + CAPTURE_IDENTITY_REASONS, + isRequestCanceledDetails, +} from '@agent-device/kernel/errors'; import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; @@ -53,6 +57,7 @@ function sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequ scope.runId ?? null, scope.leaseId ?? null, req.session ?? null, + req.token, ]), ) .digest('hex'); @@ -163,23 +168,6 @@ function confirmedStartCapture( }; } -function activeAfterStart( - current: RecordState, - response: DaemonResponse | undefined, - failure: unknown, - generation: string, - destination: string | undefined, - order: number, -): Active | undefined { - const active = current.active; - if (order < (active?.order ?? 0)) return active; - if (response?.ok === true) return confirmedStartCapture(response, generation, destination, order); - const details = refusalDetails(response, failure); - if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) - return details.clientCaptureId === active?.generation ? active : undefined; - return active; -} - function recordAfterStart( current: RecordState, response: DaemonResponse | undefined, @@ -188,42 +176,32 @@ function recordAfterStart( destination: string | undefined, order: number, ): RecordState { - const active = activeAfterStart(current, response, failure, generation, destination, order); - return { - ...(active ? { active } : {}), - pending: current.pending.filter((candidate) => candidate.generation !== generation), - certainty: certaintyAfterStart(current, response, failure, generation, order), - nextOrder: current.nextOrder, - }; -} - -function certaintyAfterStart( - current: RecordState, - response: DaemonResponse | undefined, - failure: unknown, - generation: string, - order: number, -): CaptureCertainty { - if (order < (current.active?.order ?? 0)) return current.certainty; - if (response?.ok === true && response.data?.clientCaptureId === generation) return 'settled'; + const pending = current.pending.filter((candidate) => candidate.generation !== generation); + const next = { ...current, pending }; + if (order < (current.active?.order ?? 0)) return next; + const uncertain = current.certainty === 'foreign' ? 'foreign' : 'unknown'; + if (response?.ok === true) { + const active = confirmedStartCapture(response, generation, destination, order); + return { ...next, active, certainty: active ? 'settled' : uncertain }; + } const details = refusalDetails(response, failure); - if (details?.reason === CAPTURE_IDENTITY_REASONS.alreadyActive.reason) - return certaintyAfterAlreadyActive(current, details.clientCaptureId); - return current.certainty === 'foreign' ? 'foreign' : 'unknown'; + if (details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason) + return { ...next, certainty: uncertain }; + const clientCaptureId = details.clientCaptureId; + if (current.active && clientCaptureId === current.active.generation) return next; + const foreign = + current.certainty === 'settled' && + typeof clientCaptureId === 'string' && + !pending.some((candidate) => candidate.generation === clientCaptureId) && + clientCaptureId !== generation; + return { ...next, active: undefined, certainty: foreign ? 'foreign' : uncertain }; } -function certaintyAfterAlreadyActive( - current: RecordState, - clientCaptureId: unknown, -): CaptureCertainty { - if (current.active && clientCaptureId === current.active.generation) return current.certainty; - if (current.pending.some((pending) => pending.generation === clientCaptureId)) - return current.certainty === 'foreign' ? 'foreign' : 'unknown'; - if (current.certainty === 'settled' && typeof clientCaptureId === 'string') return 'foreign'; - return current.certainty === 'foreign' ? 'foreign' : 'unknown'; -} - -async function withRecordLock(file: string, task: () => Promise): Promise { +async function withRecordLock( + file: string, + task: () => Promise, + signal?: AbortSignal, +): Promise { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); const { pid, startTime } = readCurrentOwnerIdentity(); return await withProcessLock({ @@ -233,6 +211,7 @@ async function withRecordLock(file: string, task: () => Promise): Promise< owner: { pid, startTime, acquiredAtMs: Date.now() }, timeoutMs: 30_000, description: 'remote capture destination', + signal, }), task, }); @@ -244,13 +223,14 @@ export async function sendRemoteCapture( req: DaemonWireRequest, stateDir: string, send: Send, + signal?: AbortSignal, ): Promise { const capture = captureOf(req); - if (!capture) return await sendWithoutCapture(baseUrl, req, stateDir, send); + if (!capture) return await sendWithoutCapture(baseUrl, req, stateDir, send, signal); const file = recordFile(stateDir, baseUrl, req, capture.family); return capture.action === 'stop' - ? await sendCaptureStop(file, req, send) - : await sendCaptureStart(file, req, send); + ? await sendCaptureStop(file, req, send, signal) + : await sendCaptureStart(file, req, send, signal); } async function sendWithoutCapture( @@ -258,9 +238,12 @@ async function sendWithoutCapture( req: DaemonWireRequest, stateDir: string, send: Send, + signal?: AbortSignal, ): Promise { const closedRecords = - req.command === 'close' ? await snapshotSessionCaptures(baseUrl, req, stateDir) : undefined; + req.command === 'close' + ? await snapshotSessionCaptures(baseUrl, req, stateDir, signal) + : undefined; const response = await send(req); if (response.ok && closedRecords) await retireClosedSessionCaptures(closedRecords); return response; @@ -270,22 +253,27 @@ async function sendCaptureStop( file: string, req: DaemonWireRequest, send: Send, + signal?: AbortSignal, ): Promise { const hasExplicitPath = typeof req.meta?.clientArtifactPaths?.outPath === 'string'; - const { active, foreignBeforeStop } = await withRecordLock(file, async () => { - const current = readRecord(file); - if (current?.certainty === 'foreign' && !hasExplicitPath) - throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { - reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, - }); - return { - active: - current?.pending.length === 0 && current.certainty === 'settled' - ? current.active - : undefined, - foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, - }; - }); + const { active, foreignBeforeStop } = await withRecordLock( + file, + async () => { + const current = readRecord(file); + if (current?.certainty === 'foreign' && !hasExplicitPath) + throw new AppError('INVALID_ARGS', 'Remote capture identity changed', { + reason: CAPTURE_IDENTITY_REASONS.mismatch.reason, + }); + return { + active: + current?.pending.length === 0 && current.certainty === 'settled' + ? current.active + : undefined, + foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, + }; + }, + signal, + ); if (!active) { const response = await send(req); if (response.ok && foreignBeforeStop) await clearForeignAfterStop(file, foreignBeforeStop); @@ -300,11 +288,11 @@ async function sendCaptureStop( response = await send(sent); } catch (error) { if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) - await retireSuccessfulCaptureStop(sent); + await settleCaptureStop(sent); throw error; } if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) - await retireSuccessfulCaptureStop(sent); + await settleCaptureStop(sent); return response; } @@ -320,19 +308,24 @@ async function sendCaptureStart( file: string, req: DaemonWireRequest, send: Send, + signal?: AbortSignal, ): Promise { const generation = crypto.randomUUID(); - const order = await withRecordLock(file, async () => { - const current = readRecord(file); - const nextOrder = (current?.nextOrder ?? 0) + 1; - writeRecord(file, { - ...(current?.active ? { active: current.active } : {}), - pending: [...(current?.pending ?? []), { generation, order: nextOrder }], - certainty: current?.certainty ?? 'settled', - nextOrder, - }); - return nextOrder; - }); + const order = await withRecordLock( + file, + async () => { + const current = readRecord(file); + const nextOrder = (current?.nextOrder ?? 0) + 1; + writeRecord(file, { + ...(current?.active ? { active: current.active } : {}), + pending: [...(current?.pending ?? []), { generation, order: nextOrder }], + certainty: current?.certainty ?? 'settled', + nextOrder, + }); + return nextOrder; + }, + signal, + ); let response: DaemonResponse | undefined; let failure: unknown; let threw = false; @@ -343,7 +336,7 @@ async function sendCaptureStart( failure = error; } const destination = req.meta?.clientArtifactPaths?.outPath; - await withRecordLock(file, async () => { + const settle = withRecordLock(file, async () => { const current = readRecord(file); if (!current?.pending.some((pending) => pending.generation === generation)) return; settleRecord( @@ -351,49 +344,42 @@ async function sendCaptureStart( recordAfterStart(current, response, failure, generation, destination, order), ); }); + if (isRequestCanceledDetails(refusalDetails(undefined, failure))) { + // The pending generation already prevents reuse while canceled work settles. + void settle.catch(() => undefined); + throw failure; + } + await settle; if (threw) throw failure; if (!response) throw new TypeError('Capture start settled without a response'); return response; } -/** A successful daemon stop retires its generation before artifact download can fail. */ -export async function retireSuccessfulCaptureStop(req: DaemonWireRequest): Promise { - const owned = stopGenerations.get(req); - if (!owned) return; - stopGenerations.delete(req); - await withRecordLock(owned.file, async () => { - const current = readRecord(owned.file); - if (current?.active?.generation === owned.generation) - settleRecord(owned.file, { - pending: current.pending, - certainty: current.certainty, - nextOrder: current.nextOrder, - }); - }); -} - -/** A response can use a saved path only when it confirms this client's live capture identity. */ -export async function confirmedCaptureStopRequest( +/** Retire the stopped capture and recover its destination only from the same confirmed record. */ +export async function settleCaptureStop( req: DaemonWireRequest, - response: Extract, + response?: Extract, ): Promise { const owned = stopGenerations.get(req); - if (!owned || response.data?.clientCaptureId !== owned.generation) return req; - const active = await withRecordLock(owned.file, async () => { + if (!owned) return req; + stopGenerations.delete(req); + const destination = await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); - return current?.pending.length === 0 && + if (current?.active?.generation !== owned.generation) return undefined; + settleRecord(owned.file, { ...current, active: undefined }); + return response?.data?.clientCaptureId === owned.generation && + current.pending.length === 0 && current.certainty === 'settled' && - current.active?.generation === owned.generation - ? current.active + typeof req.meta?.clientArtifactPaths?.outPath !== 'string' + ? current.active.destination : undefined; }); - if (!active?.destination || typeof req.meta?.clientArtifactPaths?.outPath === 'string') - return req; + if (!destination) return req; return { ...req, meta: { ...req.meta, - clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: active.destination }, + clientArtifactPaths: { ...req.meta?.clientArtifactPaths, outPath: destination }, }, }; } @@ -402,6 +388,7 @@ async function snapshotSessionCaptures( baseUrl: string, req: DaemonWireRequest, stateDir: string, + signal?: AbortSignal, ): Promise> { const dir = sessionRecordDir(stateDir, baseUrl, req); let entries: string[]; @@ -414,10 +401,14 @@ async function snapshotSessionCaptures( const records = new Map(); for (const entry of entries) { const file = path.join(dir, entry); - await withRecordLock(file, async () => { - const current = readRecord(file); - if (current) records.set(file, JSON.stringify(current)); - }); + await withRecordLock( + file, + async () => { + const current = readRecord(file); + if (current) records.set(file, JSON.stringify(current)); + }, + signal, + ); } return records; } diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index cd632c59fd7..e2f2187594b 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -535,8 +535,7 @@ export async function materializeRemoteArtifacts( ): Promise { if (!info.baseUrl) return response; const captures = await import('./capture-destination-record.ts'); - const downloadRequest = await captures.confirmedCaptureStopRequest(req, response); - await captures.retireSuccessfulCaptureStop(req); + const downloadRequest = await captures.settleCaptureStop(req, response); const endpoint = { baseUrl: info.baseUrl, token: info.token }; const artifacts = Array.isArray(response.data?.artifacts) ? response.data.artifacts : []; const download = (scripts?: SessionScriptDelivery) => @@ -740,8 +739,7 @@ function isRecordStop(req: DaemonWireRequest): boolean { } /** - * A path from this request wins. Every unnamed artifact gets a unique client file in cwd. - * A NUL in a response file name cannot provide a fallback destination. + * A path from this request wins. Accepted fallback names get a unique client file in cwd. */ function resolveMaterializedArtifactPath( artifact: DaemonArtifact, diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 3ea25836e1c..fb2c820705c 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -149,7 +149,7 @@ Diagnostics and traces: agent-device press 'id="load-diagnostics"' agent-device trace stop ./traces/diagnostics.trace The trace path is positional. Do not use --path for trace start or trace stop. - For a remote capture, a stop without a path reuses the start destination saved in this client's state directory when the endpoint, session, lease, and capture kind match. + A remote trace or native perf stop without a path reuses the saved start destination only when the daemon confirms the same client capture ID. Use perf xctrace only for Apple native CPU/profile or Animation Hitches artifacts: agent-device perf cpu profile start --kind xctrace --template "Time Profiler" --out ./artifacts/app.trace agent-device perf cpu profile stop --kind xctrace --out ./artifacts/app.trace diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index a4bf9e1b122..db738ff5c01 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -99,10 +99,11 @@ request. Without one, it downloads to a unique file in the working directory wit The directory of a `record start` path does not carry over. Direct RPC callers receive artifact IDs and download each result with `GET /artifacts/` using the same authentication. -For an artifact without a destination on the current request, the client uses a recorded start path -for a trace or performance stop when one exists. Otherwise, it appends a unique suffix to the -artifact file name in its working directory. A daemon-provided name or path cannot select an -existing client file. +For a trace or native performance stop without a destination, the client reuses a saved start path +only when the daemon confirms the same client capture ID. The saved path is scoped to the endpoint, +credential, lease, session, and capture kind. If the credential changes, pass the desired destination +to the stop request. Other downloads without a caller destination use unique filenames in the working +directory. A malformed daemon name can cause the artifact to be skipped. 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 From e71768deac6014835fad8dd3038a5ae0a4e9717f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:53:46 +0100 Subject: [PATCH 08/13] chore(gates): record capture settlement 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 97f806b803d..4f28aa450bd 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -159,7 +159,7 @@ "packages/remote/src/daemon-artifacts.ts#buildDaemonArtifactUrl": "sha256:06dcde057809b507f70f7bb5cdef9bde6515be84b67e45865cf19e70b8636208", "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", - "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", + "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:3e41c8810156b6af71f0443e749d751b53cc0bb58b1a7c2adbd20d7ad0b9a38d", "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:0495174ab15a8c5a7c159eb957d3fc463a856b151c47a77cf0d567eb9843ee21", "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:c0fdd490bb6e596adbbc2b9db35230eac5373c313fc5a230ac09ec70320694bb", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", @@ -678,8 +678,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts", - "digest": "sha256:b7b4edcccfee11633ebcc96d302f389f644cf39ecea0e471ef31fc1082db5615", - "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner instead of the file download, and retires a client-local capture destination before downloading a successful stop's artifacts. A pathless stop can carry the existing optional meta.clientArtifactPaths.outPath from client state; an older daemon can ignore that hint or use it as before. An older client receives the same response and retains its fallback. A new client uses the destination recorded with the confirmed live capture ID for a pathless stop; an unconfirmed response gets a fresh client cwd name. A released daemon ignores optional captureId metadata, so this client-only destination choice does not change peer parsing. The GET /artifacts/:id request, headers, artifact fields, and response framing are unchanged." + "digest": "sha256:3e41c8810156b6af71f0443e749d751b53cc0bb58b1a7c2adbd20d7ad0b9a38d", + "rationale": "Passes the in-memory fetchRemoteArtifact to the session-script owner. A successful capture stop retires its client-side record and selects a saved path under one lock before download. Older daemons ignore optional captureId metadata and the client chooses a fresh filename when confirmation is absent. Older clients can still download when the daemon omits an optional localPath. The GET /artifacts/:id request, headers, and response framing are unchanged." }, { "declaration": "packages/remote/src/script-version-publisher.ts#publishScriptVersion", From 9f92303aa6ceb977cce91638eacadd94cb93921e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 16:23:56 +0100 Subject: [PATCH 09/13] fix(remote): recover capture destinations across starts and tenant aliases --- packages/contracts/src/daemon-http.ts | 6 ++ .../support/human-control-router-fixture.ts | 2 +- .../daemon/src/core/session-tenant-scope.ts | 4 - .../http/http-server-capture-tenant.test.ts | 2 +- .../daemon/src/sessions/request-admission.ts | 16 +--- .../session-inventory-scoped-paths.test.ts | 2 +- .../capture-destination-record.test.ts | 89 +++++++++++++++---- .../remote/src/capture-destination-record.ts | 15 +++- 8 files changed, 95 insertions(+), 41 deletions(-) diff --git a/packages/contracts/src/daemon-http.ts b/packages/contracts/src/daemon-http.ts index 9c849d8ccfd..50de76f8057 100644 --- a/packages/contracts/src/daemon-http.ts +++ b/packages/contracts/src/daemon-http.ts @@ -108,6 +108,12 @@ export function isTenantOwnedSessionName(tenant: string, sessionName: string): b return sessionName.startsWith(`${tenant}:`); } +/** The canonical address of a session under tenant isolation. */ +export function tenantScopedSessionName(tenant: string, sessionName: string | undefined): string { + const requested = sessionName || 'default'; + return isTenantOwnedSessionName(tenant, requested) ? requested : `${tenant}:${requested}`; +} + export function buildDaemonHttpTenantHeaders(tenantId: string | undefined): Record { const normalizedTenantId = tenantId?.trim(); if (!normalizedTenantId) return {}; diff --git a/packages/daemon/src/__tests__/support/human-control-router-fixture.ts b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts index c4c9eaa65ad..a63dac653c7 100644 --- a/packages/daemon/src/__tests__/support/human-control-router-fixture.ts +++ b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts @@ -10,7 +10,7 @@ import { buildSessionLeaseFromRequest } from '../../core/lease-context.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { createRequestHandler } from '../../server/request-router.ts'; import { providerCredentialsFixture } from './provider-credentials-fixture.ts'; -import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; +import { tenantScopedSessionName } from '@agent-device/contracts/daemon-http'; import { lifecycleDeviceRuntimeGateway } from './test-device-runtime-gateway.ts'; import { HUMAN_CONTROL_LEASE_REQUEST, humanControlRequest } from './human-control-fixtures.ts'; import { fakeCreateCommandSurface } from './command-surface-fake.ts'; diff --git a/packages/daemon/src/core/session-tenant-scope.ts b/packages/daemon/src/core/session-tenant-scope.ts index 4c0f52ec6db..4bb7cfbf703 100644 --- a/packages/daemon/src/core/session-tenant-scope.ts +++ b/packages/daemon/src/core/session-tenant-scope.ts @@ -47,10 +47,6 @@ export type TenantSessionNamespace = { partitioned: boolean; }; -export function tenantScopedSessionName(tenant: string, session: string): string { - return isTenantOwnedSessionName(tenant, session) ? session : `${tenant}:${session}`; -} - /** The tenant-relative name that addresses this session under tenant scoping. */ export function tenantPublicSessionName(tenant: string, session: string): string { return isTenantOwnedSessionName(tenant, session) ? session.slice(tenant.length + 1) : session; diff --git a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index 36e05c5c7c7..9debd14d792 100644 --- a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts @@ -15,7 +15,7 @@ import { createDaemonHttpServer } from './http-server.ts'; import { createRequestHandler } from '../../__tests__/support/test-device-runtime-gateway.ts'; import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; -import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; +import { tenantScopedSessionName } from '@agent-device/contracts/daemon-http'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { listDownloadableArtifacts, diff --git a/packages/daemon/src/sessions/request-admission.ts b/packages/daemon/src/sessions/request-admission.ts index f9dcbe623e5..39d765a3c78 100644 --- a/packages/daemon/src/sessions/request-admission.ts +++ b/packages/daemon/src/sessions/request-admission.ts @@ -1,8 +1,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; -import { isTenantOwnedSessionName, normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { normalizeTenantId, tenantScopedSessionName } from '@agent-device/contracts/daemon-http'; import { resolveSessionIsolationMode } from '../core/config.ts'; -import { tenantScopedSessionName } from '../core/session-tenant-scope.ts'; import { isAppLeaseAllowed, isLeaseAdmissionExempt, @@ -52,20 +51,9 @@ export function scopeRequestSession(req: DaemonRequest): DaemonRequest { 'session isolation mode tenant requires --tenant (or meta.tenantId).', ); } - const requestedSession = req.session || 'default'; - if (isTenantOwnedSessionName(tenant, requestedSession)) { - return { - ...req, - meta: { - ...req.meta, - tenantId: tenant, - sessionIsolation: isolation, - }, - }; - } return { ...req, - session: tenantScopedSessionName(tenant, requestedSession), + session: tenantScopedSessionName(tenant, req.session), meta: { ...req.meta, tenantId: tenant, diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-inventory-scoped-paths.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-inventory-scoped-paths.test.ts index e22472b2a54..f26f137a4e5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-inventory-scoped-paths.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-inventory-scoped-paths.test.ts @@ -8,7 +8,7 @@ import type { DaemonRequest } from '../../../../core/daemon-request.ts'; import type { SessionState } from '../../../../core/session-state.ts'; import { IOS_SIMULATOR, createTestHostEnvironment } from '@agent-device/test-kit'; import { resolveImplicitSessionScope } from '../../../session-routing.ts'; -import { tenantScopedSessionName } from '../../../../core/session-tenant-scope.ts'; +import { tenantScopedSessionName } from '@agent-device/contracts/daemon-http'; // A session opened without an explicit --session is NAMED `default` and STORED under // `cwd::default`. `session list` resolved its paths from the name, so it answered with diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 518e3e2b96a..8402700b09b 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -37,6 +37,7 @@ function request( runId?: string; leaseId?: string; session?: string; + sessionIsolation?: 'tenant' | 'none'; token?: string; } = {}, ): DaemonWireRequest { @@ -50,6 +51,7 @@ function request( tenantId: options.tenantId ?? 'tenant-a', runId: options.runId ?? 'run-a', leaseId: options.leaseId ?? 'lease-a', + sessionIsolation: options.sessionIsolation, ...(outPath ? { clientArtifactPaths: { outPath } } : {}), }, }; @@ -625,24 +627,68 @@ test('a concurrent rejected start does not discard a newly confirmed start', asy }); }); -test('successful close retires destinations before the same session address is reused', async () => { +test('successful close through a tenant session alias retires its capture destination', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => - confirmed(req), + const sessionScope = { session: 'device-a', sessionIsolation: 'tenant' } as const; + await sendRemoteCapture( + endpoint, + request('start', '/client/old.trace', sessionScope), + stateDir, + async (req) => confirmed(req), ); await sendRemoteCapture( endpoint, - { ...request('stop'), command: 'close', positionals: [] }, + { + ...request('stop', undefined, { ...sessionScope, session: 'tenant-a:device-a' }), + command: 'close', + positionals: [], + }, stateDir, async (req) => confirmed(req), ); - await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect(req.meta?.captureId).toBeUndefined(); - expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); - return success; - }); + await sendRemoteCapture( + endpoint, + request('stop', undefined, sessionScope), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBeUndefined(); + expect(req.meta?.clientArtifactPaths?.outPath).toBeUndefined(); + return success; + }, + ); }); +test.each(['tenant', 'none'] as const)( + 'capture stops share tenant session aliases only under tenant isolation (%s)', + async (sessionIsolation) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const destination = path.join(stateDir, 'owned.trace'); + let captureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', destination, { sessionIsolation }), + stateDir, + async (req) => { + captureId = req.meta?.captureId; + return confirmed(req); + }, + ); + await sendRemoteCapture( + endpoint, + request('stop', undefined, { sessionIsolation, session: 'tenant-a:device-a' }), + stateDir, + async (req) => { + expect(req.meta?.captureId).toBe(sessionIsolation === 'tenant' ? captureId : undefined); + const answer = { ok: true as const, data: { clientCaptureId: captureId } }; + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + sessionIsolation === 'tenant' ? destination : undefined, + ); + return answer; + }, + ); + }, +); + test('failed close leaves the confirmed destination for a retry', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); await sendRemoteCapture(endpoint, request('start', '/client/old.trace'), stateDir, async (req) => @@ -881,7 +927,7 @@ test.each(['returned', 'thrown'] as const)( }, ); -test('a late successful start cannot replace a newer confirmed destination', async () => { +test('a later capture can stop while an older start is still unsettled', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; const firstStarted = new Promise((resolve) => (releaseFirst = resolve)); @@ -908,15 +954,22 @@ test('a late successful start cannot replace a newer confirmed destination', asy return confirmed(req); }, ); - finishFirst(); - await first; + try { + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerCaptureId); + const answer = confirmed(req); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); + return answer; + }); + } finally { + finishFirst(); + await first; + } await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect(req.meta?.captureId).toBe(newerCaptureId); - const answer = confirmed(req); - expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( - '/client/new.trace', - ); - return answer; + expect(req.meta?.captureId).toBeUndefined(); + return success; }); }); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index db8ef389391..70503305d9a 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; +import { normalizeTenantId, tenantScopedSessionName } from '@agent-device/contracts/daemon-http'; import { leaseScopeFromRequest } from '@agent-device/contracts/lease-scope'; import { parsePerfRuntimeRequest } from '@agent-device/capture-kit/perf-runtime-plan'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; @@ -48,6 +49,10 @@ function captureOf(req: DaemonWireRequest): Capture | undefined { function sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequest): string { const scope = leaseScopeFromRequest(req); + const isolation = req.meta?.sessionIsolation ?? req.flags?.sessionIsolation; + // A tenant label alone does not establish that the daemon scopes session names. + const tenant = isolation === 'tenant' ? normalizeTenantId(scope.tenantId) : undefined; + const session = tenant ? tenantScopedSessionName(tenant, req.session) : req.session; const key = crypto .createHash('sha256') .update( @@ -56,7 +61,7 @@ function sessionRecordDir(stateDir: string, baseUrl: string, req: DaemonWireRequ scope.tenantId ?? null, scope.runId ?? null, scope.leaseId ?? null, - req.session ?? null, + session ?? null, req.token, ]), ) @@ -182,7 +187,13 @@ function recordAfterStart( const uncertain = current.certainty === 'foreign' ? 'foreign' : 'unknown'; if (response?.ok === true) { const active = confirmedStartCapture(response, generation, destination, order); - return { ...next, active, certainty: active ? 'settled' : uncertain }; + if (!active) return { ...next, active: undefined, certainty: uncertain }; + return { + ...next, + active, + pending: pending.filter((candidate) => candidate.order > order), + certainty: 'settled', + }; } const details = refusalDetails(response, failure); if (details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason) From 360a058558a6dcf1fcb474b4bb533d83a3e71351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 16:51:03 +0100 Subject: [PATCH 10/13] test(remote): split capture destination storage cases --- .../__tests__/capture-destination-fixture.ts | 51 ++++++ ...capture-destination-record-storage.test.ts | 118 ++++++++++++ .../capture-destination-record.test.ts | 170 +----------------- 3 files changed, 178 insertions(+), 161 deletions(-) create mode 100644 packages/remote/src/__tests__/capture-destination-fixture.ts create mode 100644 packages/remote/src/__tests__/capture-destination-record-storage.test.ts diff --git a/packages/remote/src/__tests__/capture-destination-fixture.ts b/packages/remote/src/__tests__/capture-destination-fixture.ts new file mode 100644 index 00000000000..d3b0fc22a04 --- /dev/null +++ b/packages/remote/src/__tests__/capture-destination-fixture.ts @@ -0,0 +1,51 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import type { DaemonWireRequest } from '@agent-device/contracts/command'; + +export const endpoint = 'https://capture.example.test/api'; +export const success = { ok: true as const, data: {} }; +export const confirmed = (req: DaemonWireRequest) => ({ + ok: true as const, + data: { clientCaptureId: req.meta?.captureId }, +}); + +export function request( + action: 'start' | 'stop', + outPath?: string, + options: { + family?: 'trace' | 'perf'; + perfKind?: 'perfetto' | 'xctrace'; + tenantId?: string; + runId?: string; + leaseId?: string; + session?: string; + sessionIsolation?: 'tenant' | 'none'; + token?: string; + } = {}, +): DaemonWireRequest { + return { + token: options.token ?? 'test', + command: options.family ?? 'trace', + session: options.session ?? 'device-a', + positionals: + options.family === 'perf' ? ['trace', action, options.perfKind ?? 'perfetto'] : [action], + meta: { + tenantId: options.tenantId ?? 'tenant-a', + runId: options.runId ?? 'run-a', + leaseId: options.leaseId ?? 'lease-a', + sessionIsolation: options.sessionIsolation, + ...(outPath ? { clientArtifactPaths: { outPath } } : {}), + }, + }; +} + +export function captureRecordPath(stateDir: string): string { + const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); + const [scope] = fs.readdirSync(root); + if (!scope) throw new Error('Missing capture session record directory'); + const recordName = fs + .readdirSync(path.join(root, scope)) + .find((entry) => entry.endsWith('.json')); + if (!recordName) throw new Error('Missing capture record'); + return path.join(root, scope, recordName); +} diff --git a/packages/remote/src/__tests__/capture-destination-record-storage.test.ts b/packages/remote/src/__tests__/capture-destination-record-storage.test.ts new file mode 100644 index 00000000000..a7b50d7bb22 --- /dev/null +++ b/packages/remote/src/__tests__/capture-destination-record-storage.test.ts @@ -0,0 +1,118 @@ +import fs from 'node:fs'; +import { test, expect, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { acquireProcessLock } from '@agent-device/host-kit/file'; +import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { createRequestCanceledError, REQUEST_CANCELED_REASONS } from '@agent-device/kernel/errors'; +import { sendRemoteCapture } from '../capture-destination-record.ts'; +import { + captureRecordPath, + confirmed, + endpoint, + request, + success, +} from './capture-destination-fixture.ts'; + +test('cancels a stop while another request owns the capture record lock', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture(endpoint, request('start'), stateDir, async (req) => confirmed(req)); + const release = await acquireProcessLock({ + lockDirPath: captureRecordPath(stateDir) + '.lock', + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + }); + const controller = new AbortController(); + try { + const stop = sendRemoteCapture( + endpoint, + request('stop'), + stateDir, + async () => { + throw new Error('stop should not be sent'); + }, + controller.signal, + ); + controller.abort(); + await expect(stop).rejects.toMatchObject({ + details: { reason: REQUEST_CANCELED_REASONS.canceled.reason }, + }); + } finally { + await release(); + } +}); + +test('a canceled start reports cancellation while the record cleanup is contended', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + const canceled = createRequestCanceledError(); + let release: (() => Promise) | undefined; + const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { + release = await acquireProcessLock({ + lockDirPath: captureRecordPath(stateDir) + '.lock', + owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, + }); + throw canceled; + }); + try { + await expect(start).rejects.toBe(canceled); + } finally { + await release?.(); + } + const record = captureRecordPath(stateDir); + await vi.waitFor(() => { + expect(JSON.parse(fs.readFileSync(record, 'utf8'))).toMatchObject({ + pending: [], + certainty: 'unknown', + }); + }); +}); + +test('a malformed capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.writeFileSync(file, '{invalid'); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { + details: { reason: 'capture-record-invalid' }, + }, + ); + expect(dispatched).toBe(false); + expect(fs.readFileSync(file, 'utf8')).toBe('{invalid'); +}); + +test('an unreadable capture record refuses start and stop before dispatch', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/owned.trace'), + stateDir, + async (req) => confirmed(req), + ); + const file = captureRecordPath(stateDir); + fs.rmSync(file); + fs.mkdirSync(file); + let dispatched = false; + const send = async () => { + dispatched = true; + return success; + }; + await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ + details: { reason: 'capture-record-invalid' }, + }); + await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( + { details: { reason: 'capture-record-invalid' } }, + ); + expect(dispatched).toBe(false); +}); diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 8402700b09b..22376992839 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; -import { test, expect, vi } from 'vitest'; +import { test, expect } from 'vitest'; import { closeLoopbackServer, createTestHostEnvironment, @@ -9,116 +9,16 @@ import { mkdtempForTestSync, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; -import { acquireProcessLock } from '@agent-device/host-kit/file'; -import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; -import type { DaemonWireRequest } from '@agent-device/contracts/command'; -import { - AppError, - createRequestCanceledError, - REQUEST_CANCELED_REASONS, -} from '@agent-device/kernel/errors'; +import { AppError } from '@agent-device/kernel/errors'; import { sendRemoteCapture, settleCaptureStop } from '../capture-destination-record.ts'; import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; - -const endpoint = 'https://capture.example.test/api'; -const success = { ok: true as const, data: {} }; -const confirmed = (req: DaemonWireRequest) => ({ - ok: true as const, - data: { clientCaptureId: req.meta?.captureId }, -}); - -function request( - action: 'start' | 'stop', - outPath?: string, - options: { - family?: 'trace' | 'perf'; - perfKind?: 'perfetto' | 'xctrace'; - tenantId?: string; - runId?: string; - leaseId?: string; - session?: string; - sessionIsolation?: 'tenant' | 'none'; - token?: string; - } = {}, -): DaemonWireRequest { - return { - token: options.token ?? 'test', - command: options.family ?? 'trace', - session: options.session ?? 'device-a', - positionals: - options.family === 'perf' ? ['trace', action, options.perfKind ?? 'perfetto'] : [action], - meta: { - tenantId: options.tenantId ?? 'tenant-a', - runId: options.runId ?? 'run-a', - leaseId: options.leaseId ?? 'lease-a', - sessionIsolation: options.sessionIsolation, - ...(outPath ? { clientArtifactPaths: { outPath } } : {}), - }, - }; -} - -function captureRecordPath(stateDir: string): string { - const root = path.join(stateDir, 'remote-connections', 'capture-destinations'); - const [scope] = fs.readdirSync(root); - if (!scope) throw new Error('Missing capture session record directory'); - const recordName = fs - .readdirSync(path.join(root, scope)) - .find((entry) => entry.endsWith('.json')); - if (!recordName) throw new Error('Missing capture record'); - return path.join(root, scope, recordName); -} - -test('cancels a stop while another request owns the capture record lock', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture(endpoint, request('start'), stateDir, async (req) => confirmed(req)); - const release = await acquireProcessLock({ - lockDirPath: captureRecordPath(stateDir) + '.lock', - owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, - }); - const controller = new AbortController(); - try { - const stop = sendRemoteCapture( - endpoint, - request('stop'), - stateDir, - async () => { - throw new Error('stop should not be sent'); - }, - controller.signal, - ); - controller.abort(); - await expect(stop).rejects.toMatchObject({ - details: { reason: REQUEST_CANCELED_REASONS.canceled.reason }, - }); - } finally { - await release(); - } -}); - -test('a canceled start reports cancellation while the record cleanup is contended', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - const canceled = createRequestCanceledError(); - let release: (() => Promise) | undefined; - const start = sendRemoteCapture(endpoint, request('start'), stateDir, async () => { - release = await acquireProcessLock({ - lockDirPath: captureRecordPath(stateDir) + '.lock', - owner: { ...readCurrentOwnerIdentity(), acquiredAtMs: Date.now() }, - }); - throw canceled; - }); - try { - await expect(start).rejects.toBe(canceled); - } finally { - await release?.(); - } - const record = captureRecordPath(stateDir); - await vi.waitFor(() => { - expect(JSON.parse(fs.readFileSync(record, 'utf8'))).toMatchObject({ - pending: [], - certainty: 'unknown', - }); - }); -}); +import { + captureRecordPath, + confirmed, + endpoint, + request, + success, +} from './capture-destination-fixture.ts'; test.for(['trace', 'perf'] as const)( '%s stop downloads to its own start path and retires it', @@ -526,58 +426,6 @@ test.each(['trace', 'perf'] as const)( }, ); -test('a malformed capture record refuses start and stop before dispatch', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture( - endpoint, - request('start', '/client/owned.trace'), - stateDir, - async (req) => confirmed(req), - ); - const file = captureRecordPath(stateDir); - fs.writeFileSync(file, '{invalid'); - let dispatched = false; - const send = async () => { - dispatched = true; - return success; - }; - await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ - details: { reason: 'capture-record-invalid' }, - }); - await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( - { - details: { reason: 'capture-record-invalid' }, - }, - ); - expect(dispatched).toBe(false); - expect(fs.readFileSync(file, 'utf8')).toBe('{invalid'); -}); - -test('an unreadable capture record refuses start and stop before dispatch', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - await sendRemoteCapture( - endpoint, - request('start', '/client/owned.trace'), - stateDir, - async (req) => confirmed(req), - ); - const file = captureRecordPath(stateDir); - fs.rmSync(file); - fs.mkdirSync(file); - let dispatched = false; - const send = async () => { - dispatched = true; - return success; - }; - await expect(sendRemoteCapture(endpoint, request('stop'), stateDir, send)).rejects.toMatchObject({ - details: { reason: 'capture-record-invalid' }, - }); - await expect(sendRemoteCapture(endpoint, request('start'), stateDir, send)).rejects.toMatchObject( - { details: { reason: 'capture-record-invalid' } }, - ); - expect(dispatched).toBe(false); -}); - test('a concurrent rejected start does not discard a newly confirmed start', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; From 23411a2872c4aec89b6d3d7a6b73e2f86ff7fd21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 17:42:24 +0100 Subject: [PATCH 11/13] fix(remote): retire captures stopped before start settles --- .../capture-destination-record.test.ts | 31 +++++++++ .../remote/src/capture-destination-record.ts | 69 ++++++++++++------- 2 files changed, 74 insertions(+), 26 deletions(-) diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index 22376992839..ab6f43567ab 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -775,6 +775,37 @@ test.each(['returned', 'thrown'] as const)( }, ); +test('a confirmed stop retires a capture before its start reply arrives', async () => { + const stateDir = mkdtempForTestSync('capture-destination-'); + await sendRemoteCapture( + endpoint, + request('start', '/client/capture.trace'), + stateDir, + async (start) => { + const reply = confirmed(start); + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (stop) => { + expect(stop.meta?.captureId).toBeUndefined(); + const record = captureRecordPath(stateDir); + const response = await materializeRemoteArtifacts( + { baseUrl: endpoint, token: 'test' }, + stop, + { ok: true, data: { trace: 'stopped', clientCaptureId: reply.data.clientCaptureId } }, + createTestHostEnvironment({ cwd: stateDir }), + stateDir, + ); + expect(fs.existsSync(record)).toBe(false); + return response; + }); + return reply; + }, + ); + + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (stop) => { + expect(stop.meta?.captureId).toBeUndefined(); + return success; + }); +}); + test('a later capture can stop while an older start is still unsettled', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); let releaseFirst!: () => void; diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 70503305d9a..fd6c696fa0f 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -25,7 +25,10 @@ type RecordState = { certainty: CaptureCertainty; nextOrder: number; }; -const stopGenerations = new WeakMap(); +const stopRecords = new WeakMap< + DaemonWireRequest, + { file: string; generation?: string; foreignBeforeStop?: string } +>(); function captureOf(req: DaemonWireRequest): Capture | undefined { if (req.command === 'trace') { @@ -285,36 +288,31 @@ async function sendCaptureStop( }, signal, ); - if (!active) { - const response = await send(req); - if (response.ok && foreignBeforeStop) await clearForeignAfterStop(file, foreignBeforeStop); - return response; - } - const sent = hasExplicitPath - ? req - : { ...req, meta: { ...req.meta, captureId: active.generation } }; - stopGenerations.set(sent, { file, generation: active.generation }); + const sent = + hasExplicitPath || !active + ? { ...req } + : { ...req, meta: { ...req.meta, captureId: active.generation } }; + stopRecords.set(sent, { file, generation: active?.generation, foreignBeforeStop }); let response: DaemonResponse; try { response = await send(sent); } catch (error) { - if (refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + if ( + active && + refusalDetails(undefined, error)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason + ) await settleCaptureStop(sent); throw error; } - if (refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason) + if (!active && response.ok) await settleCaptureStop(sent, response); + if ( + active && + refusalDetails(response, undefined)?.reason === CAPTURE_IDENTITY_REASONS.mismatch.reason + ) await settleCaptureStop(sent); return response; } -async function clearForeignAfterStop(file: string, beforeStop: string): Promise { - await withRecordLock(file, async () => { - const current = readRecord(file); - if (current?.certainty === 'foreign' && JSON.stringify(current) === beforeStop) - settleRecord(file, { ...current, certainty: 'settled' }); - }); -} - async function sendCaptureStart( file: string, req: DaemonWireRequest, @@ -371,18 +369,37 @@ export async function settleCaptureStop( req: DaemonWireRequest, response?: Extract, ): Promise { - const owned = stopGenerations.get(req); + const owned = stopRecords.get(req); if (!owned) return req; - stopGenerations.delete(req); + stopRecords.delete(req); + const confirmedId = response?.data?.clientCaptureId; + if (!owned.generation && typeof confirmedId !== 'string' && !owned.foreignBeforeStop) return req; const destination = await withRecordLock(owned.file, async () => { const current = readRecord(owned.file); - if (current?.active?.generation !== owned.generation) return undefined; - settleRecord(owned.file, { ...current, active: undefined }); - return response?.data?.clientCaptureId === owned.generation && + if (!current) return undefined; + const active = current.active; + const retireActive = + active && (active.generation === owned.generation || active.generation === confirmedId); + const pending = current.pending.filter((candidate) => candidate.generation !== confirmedId); + const clearForeign = + response && + current.certainty === 'foreign' && + owned.foreignBeforeStop === JSON.stringify(current); + if (retireActive || pending.length !== current.pending.length || clearForeign) { + settleRecord(owned.file, { + ...current, + active: retireActive ? undefined : active, + pending, + certainty: clearForeign ? 'settled' : current.certainty, + }); + } + return active && + active.generation === owned.generation && + confirmedId === owned.generation && current.pending.length === 0 && current.certainty === 'settled' && typeof req.meta?.clientArtifactPaths?.outPath !== 'string' - ? current.active.destination + ? active.destination : undefined; }); if (!destination) return req; From d7278df3696a3c00cee9722c6c535ea1c7d13ab6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:41:05 +0100 Subject: [PATCH 12/13] fix(remote): settle capture starts in daemon order --- packages/contracts/src/recording.ts | 1 + .../src/core/capture-identity-refusal.ts | 10 +++ .../handlers/__tests__/trace-runtime.test.ts | 5 +- .../src/sessions/handlers/trace-runtime.ts | 7 +- .../__tests__/session-perf-runtime.test.ts | 1 + .../internal/session-perf-runtime.ts | 7 +- .../__tests__/capture-destination-fixture.ts | 7 +- .../capture-destination-record.test.ts | 88 ++++++++++--------- .../remote/src/capture-destination-record.ts | 53 +++++++++-- 9 files changed, 125 insertions(+), 54 deletions(-) diff --git a/packages/contracts/src/recording.ts b/packages/contracts/src/recording.ts index 9002dc82f0a..fe0b11dd470 100644 --- a/packages/contracts/src/recording.ts +++ b/packages/contracts/src/recording.ts @@ -70,6 +70,7 @@ export type TraceCommandResult = trace: 'started'; outPath: string; clientCaptureId?: string; + captureStartOrder?: number; } | { trace: 'stopped'; diff --git a/packages/daemon/src/core/capture-identity-refusal.ts b/packages/daemon/src/core/capture-identity-refusal.ts index f21621efe46..4f1e617362a 100644 --- a/packages/daemon/src/core/capture-identity-refusal.ts +++ b/packages/daemon/src/core/capture-identity-refusal.ts @@ -28,3 +28,13 @@ export function captureIdentityRefusal( ...(refusal === 'already-active' ? { clientCaptureId } : {}), }); } + +let lastCaptureStartOrder = 0; + +/** Orders successful capture starts even when their HTTP replies arrive out of order. */ +export function captureStartReceipt(clientCaptureId: string | undefined) { + if (!clientCaptureId) return {}; + const now = Math.floor((performance.timeOrigin + performance.now()) * 1_000); + lastCaptureStartOrder = Math.max(lastCaptureStartOrder + 1, now); + return { clientCaptureId, captureStartOrder: lastCaptureStartOrder }; +} diff --git a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts index d0eaf357168..c5070411d59 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/trace-runtime.test.ts @@ -95,7 +95,10 @@ test('a stale client capture identity cannot stop a reopened trace', () => { sessionName: session.name, sessionStore, }); - expect(started).toMatchObject({ ok: true, data: { clientCaptureId: 'capture-b' } }); + expect(started).toMatchObject({ + ok: true, + data: { clientCaptureId: 'capture-b', captureStartOrder: expect.any(Number) }, + }); const stale = handleTraceCommand({ host, req: request(['stop'], undefined, 'capture-a'), diff --git a/packages/daemon/src/sessions/handlers/trace-runtime.ts b/packages/daemon/src/sessions/handlers/trace-runtime.ts index fe475ea04f2..107741da7d0 100644 --- a/packages/daemon/src/sessions/handlers/trace-runtime.ts +++ b/packages/daemon/src/sessions/handlers/trace-runtime.ts @@ -15,7 +15,10 @@ import type { SessionRef } from '../../core/session-state.ts'; import { recordSessionAction } from '../../core/session-action-recorder.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; -import { captureIdentityRefusal } from '../../core/capture-identity-refusal.ts'; +import { + captureIdentityRefusal, + captureStartReceipt, +} from '../../core/capture-identity-refusal.ts'; export function handleTraceCommand(params: { host: HostEnvironment; @@ -61,7 +64,7 @@ function startTrace( data: { trace: 'started', outPath, - ...(req.meta?.captureId ? { clientCaptureId: req.meta.captureId } : {}), + ...captureStartReceipt(req.meta?.captureId), } satisfies TraceCommandResult, }; } diff --git a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts index d7a9de1f6ef..67f927f9c09 100644 --- a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts +++ b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts @@ -223,6 +223,7 @@ test.each([ }); assert.equal(startResponse?.ok, true, JSON.stringify(startResponse)); assert.equal(startResponse?.data?.clientCaptureId, 'capture-b'); + assert.ok(Number.isSafeInteger(startResponse?.data?.captureStartOrder)); assert.ok(sessionStore.get('android')?.perfCapture); assert.deepEqual( sessionStore.get('android')?.actions.map(({ command }) => command), diff --git a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts index 2798a587434..8b4425e815a 100644 --- a/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts +++ b/packages/daemon/src/sessions/session-observability/internal/session-perf-runtime.ts @@ -39,7 +39,10 @@ import { requestCwd } from '../../../core/context.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import { bindSessionPerfCapture } from '../../../core/session-capture-binding.ts'; import { withCaptureOutputOwnership } from '../../../core/capture-output-ownership.ts'; -import { captureIdentityRefusal } from '../../../core/capture-identity-refusal.ts'; +import { + captureIdentityRefusal, + captureStartReceipt, +} from '../../../core/capture-identity-refusal.ts'; import { recordSessionAction } from '../../../core/session-action-recorder.ts'; import { admitRuntimePlan, @@ -304,7 +307,7 @@ async function startPerfCapture( ok: true, data: { ...started.response, - ...(clientCaptureId ? { clientCaptureId } : {}), + ...captureStartReceipt(clientCaptureId), }, }; } diff --git a/packages/remote/src/__tests__/capture-destination-fixture.ts b/packages/remote/src/__tests__/capture-destination-fixture.ts index d3b0fc22a04..d171c96e581 100644 --- a/packages/remote/src/__tests__/capture-destination-fixture.ts +++ b/packages/remote/src/__tests__/capture-destination-fixture.ts @@ -4,9 +4,14 @@ import type { DaemonWireRequest } from '@agent-device/contracts/command'; export const endpoint = 'https://capture.example.test/api'; export const success = { ok: true as const, data: {} }; +let daemonStartOrder = 0; + export const confirmed = (req: DaemonWireRequest) => ({ ok: true as const, - data: { clientCaptureId: req.meta?.captureId }, + data: { + clientCaptureId: req.meta?.captureId, + ...(req.positionals?.includes('start') ? { captureStartOrder: ++daemonStartOrder } : {}), + }, }); export function request( diff --git a/packages/remote/src/__tests__/capture-destination-record.test.ts b/packages/remote/src/__tests__/capture-destination-record.test.ts index ab6f43567ab..5420ac30fc8 100644 --- a/packages/remote/src/__tests__/capture-destination-record.test.ts +++ b/packages/remote/src/__tests__/capture-destination-record.test.ts @@ -806,51 +806,59 @@ test('a confirmed stop retires a capture before its start reply arrives', async }); }); -test('a later capture can stop while an older start is still unsettled', async () => { - const stateDir = mkdtempForTestSync('capture-destination-'); - let releaseFirst!: () => void; - const firstStarted = new Promise((resolve) => (releaseFirst = resolve)); - let finishFirst!: () => void; - const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); - const first = sendRemoteCapture( - endpoint, - request('start', '/client/old.trace'), - stateDir, - async (req) => { - releaseFirst(); - await firstCanFinish; - return confirmed(req); - }, - ); - await firstStarted; - let newerCaptureId: string | undefined; - await sendRemoteCapture( - endpoint, - request('start', '/client/new.trace'), - stateDir, - async (req) => { - newerCaptureId = req.meta?.captureId; - return confirmed(req); - }, - ); - try { +test.each(['before', 'after'] as const)( + 'a start reserved first and admitted %s a later reservation settles in daemon order', + async (admission) => { + const stateDir = mkdtempForTestSync('capture-destination-'); + let releaseFirst!: () => void; + const firstStarted = new Promise((resolve) => (releaseFirst = resolve)); + let finishFirst!: () => void; + const firstCanFinish = new Promise((resolve) => (finishFirst = resolve)); + const first = sendRemoteCapture( + endpoint, + request('start', '/client/old.trace'), + stateDir, + async (req) => { + const earlyReply = admission === 'before' ? confirmed(req) : undefined; + releaseFirst(); + await firstCanFinish; + return earlyReply ?? confirmed(req); + }, + ); + await firstStarted; + let newerCaptureId: string | undefined; + await sendRemoteCapture( + endpoint, + request('start', '/client/new.trace'), + stateDir, + async (req) => { + newerCaptureId = req.meta?.captureId; + return confirmed(req); + }, + ); + try { + await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { + expect(req.meta?.captureId).toBe(newerCaptureId); + const answer = confirmed(req); + expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( + '/client/new.trace', + ); + return answer; + }); + } finally { + finishFirst(); + await first; + } await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect(req.meta?.captureId).toBe(newerCaptureId); const answer = confirmed(req); - expect((await settleCaptureStop(req, answer)).meta?.clientArtifactPaths?.outPath).toBe( - '/client/new.trace', + const stop = await settleCaptureStop(req, answer); + expect(stop.meta?.clientArtifactPaths?.outPath).toBe( + admission === 'before' ? undefined : '/client/old.trace', ); return answer; }); - } finally { - finishFirst(); - await first; - } - await sendRemoteCapture(endpoint, request('stop'), stateDir, async (req) => { - expect(req.meta?.captureId).toBeUndefined(); - return success; - }); -}); + }, +); test('scope and explicit stop path cannot borrow or override another capture destination', async () => { const stateDir = mkdtempForTestSync('capture-destination-'); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index fd6c696fa0f..142d66cf874 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -12,18 +12,24 @@ import { isRequestCanceledDetails, } from '@agent-device/kernel/errors'; import { acquireProcessLock, publishFileSync, withProcessLock } from '@agent-device/host-kit/file'; -import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process'; +import { + isProcessAlive, + isProcessPid, + readCurrentOwnerIdentity, +} from '@agent-device/host-kit/process'; type Capture = { action: 'start' | 'stop'; family: string }; type Send = (req: DaemonWireRequest) => Promise; type Active = { generation: string; destination?: string; order: number }; -type Pending = { generation: string; order: number }; +type Pending = { generation: string; order: number; pid?: number }; type CaptureCertainty = 'settled' | 'unknown' | 'foreign'; type RecordState = { active?: Active; pending: Pending[]; certainty: CaptureCertainty; nextOrder: number; + confirmedOrder?: number; + daemonStartOrder?: number; }; const stopRecords = new WeakMap< DaemonWireRequest, @@ -105,6 +111,7 @@ function isPending(value: unknown): value is Pending { const pending = value as Partial; return ( typeof pending.generation === 'string' && + (pending.pid === undefined || isProcessPid(pending.pid)) && Number.isSafeInteger(pending.order) && (pending.order ?? 0) > 0 ); @@ -133,6 +140,8 @@ function isRecordState(value: unknown): value is RecordState { record.certainty === 'foreign') && Number.isSafeInteger(record.nextOrder) && (record.nextOrder ?? -1) >= 0 && + (record.confirmedOrder === undefined || Number.isSafeInteger(record.confirmedOrder)) && + (record.daemonStartOrder === undefined || Number.isSafeInteger(record.daemonStartOrder)) && (record.active === undefined || isActive(record.active)) ); } @@ -157,6 +166,11 @@ function settleRecord(file: string, record: RecordState): void { else writeRecord(file, record); } +function hasUnconfirmedStart(record: RecordState): boolean { + const confirmedOrder = record.confirmedOrder ?? record.active?.order ?? 0; + return record.pending.some((pending) => pending.order > confirmedOrder); +} + function refusalDetails(response: DaemonResponse | undefined, failure: unknown) { if (response?.ok === false) return response.error.details; return failure instanceof AppError ? failure.details : undefined; @@ -186,18 +200,39 @@ function recordAfterStart( ): RecordState { const pending = current.pending.filter((candidate) => candidate.generation !== generation); const next = { ...current, pending }; - if (order < (current.active?.order ?? 0)) return next; + const confirmedOrder = current.confirmedOrder ?? current.active?.order ?? 0; const uncertain = current.certainty === 'foreign' ? 'foreign' : 'unknown'; if (response?.ok === true) { const active = confirmedStartCapture(response, generation, destination, order); - if (!active) return { ...next, active: undefined, certainty: uncertain }; + if (!active) + return order < confirmedOrder ? next : { ...next, active: undefined, certainty: uncertain }; + const reportedOrder = response.data?.captureStartOrder; + const daemonStartOrder = + typeof reportedOrder === 'number' && Number.isSafeInteger(reportedOrder) + ? reportedOrder + : undefined; + if ( + daemonStartOrder !== undefined && current.daemonStartOrder !== undefined + ? daemonStartOrder <= current.daemonStartOrder + : order < confirmedOrder + ) + return next; + const latestConfirmedOrder = Math.max(confirmedOrder, order); return { ...next, active, - pending: pending.filter((candidate) => candidate.order > order), + // Older live reservations can arrive at the daemon after this start has stopped. + pending: pending.filter( + (candidate) => + candidate.order > latestConfirmedOrder || + (candidate.pid !== undefined && isProcessAlive(candidate.pid)), + ), certainty: 'settled', + confirmedOrder: latestConfirmedOrder, + daemonStartOrder, }; } + if (order < confirmedOrder) return next; const details = refusalDetails(response, failure); if (details?.reason !== CAPTURE_IDENTITY_REASONS.alreadyActive.reason) return { ...next, certainty: uncertain }; @@ -280,7 +315,7 @@ async function sendCaptureStop( }); return { active: - current?.pending.length === 0 && current.certainty === 'settled' + current?.certainty === 'settled' && !hasUnconfirmedStart(current) ? current.active : undefined, foreignBeforeStop: current?.certainty === 'foreign' ? JSON.stringify(current) : undefined, @@ -327,7 +362,9 @@ async function sendCaptureStart( const nextOrder = (current?.nextOrder ?? 0) + 1; writeRecord(file, { ...(current?.active ? { active: current.active } : {}), - pending: [...(current?.pending ?? []), { generation, order: nextOrder }], + confirmedOrder: current?.confirmedOrder, + daemonStartOrder: current?.daemonStartOrder, + pending: [...(current?.pending ?? []), { generation, order: nextOrder, pid: process.pid }], certainty: current?.certainty ?? 'settled', nextOrder, }); @@ -396,7 +433,7 @@ export async function settleCaptureStop( return active && active.generation === owned.generation && confirmedId === owned.generation && - current.pending.length === 0 && + !hasUnconfirmedStart(current) && current.certainty === 'settled' && typeof req.meta?.clientArtifactPaths?.outPath !== 'string' ? active.destination From f3f55752009ad161e0939a986694067700ede2be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:50:15 +0100 Subject: [PATCH 13/13] refactor(remote): isolate confirmed capture start settlement --- .../__tests__/session-perf-runtime.test.ts | 23 ++++---- .../remote/src/capture-destination-record.ts | 58 +++++++++++-------- 2 files changed, 43 insertions(+), 38 deletions(-) diff --git a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts index 67f927f9c09..8fdf6f9f8dd 100644 --- a/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts +++ b/packages/daemon/src/sessions/session-observability/internal/__tests__/session-perf-runtime.test.ts @@ -241,13 +241,11 @@ test.each([ positionals: ['cpu', 'profile', 'stop', 'xctrace'], }, }); - assert.equal(wrongModeResponse?.ok, false); - if (wrongModeResponse && !wrongModeResponse.ok) { - assert.equal( - wrongModeResponse.error.message, - 'No xctrace cpu-profile is active for this session.', - ); - } + assert.ok(wrongModeResponse?.ok === false, JSON.stringify(wrongModeResponse)); + assert.equal( + wrongModeResponse.error.message, + 'No xctrace cpu-profile is active for this session.', + ); assert.equal(finish.mock.calls.length, 0); assert.ok(sessionStore.get('android')?.perfCapture); assert.equal(sessionStore.get('android')?.actions.length, 1); @@ -264,9 +262,8 @@ test.each([ meta: { captureId: 'capture-a' }, }, }); - assert.equal(staleStop?.ok, false); - if (staleStop && !staleStop.ok) - assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); + assert.ok(staleStop?.ok === false, JSON.stringify(staleStop)); + assert.equal(staleStop.error.details?.reason, 'capture-identity-mismatch'); assert.equal(finish.mock.calls.length, 0); const stopResponse = await handleSessionObservabilityCommands({ @@ -281,9 +278,9 @@ test.each([ meta: { captureId }, }, }); - assert.equal(stopResponse?.ok, true, JSON.stringify(stopResponse)); - if (stopResponse?.ok) assert.equal(stopResponse.data?.clientOutPath, expectedClientOutPath); - if (stopResponse?.ok) assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); + assert.ok(stopResponse?.ok === true, JSON.stringify(stopResponse)); + assert.equal(stopResponse.data?.clientOutPath, expectedClientOutPath); + assert.equal(stopResponse.data?.clientCaptureId, 'capture-b'); assert.equal(finish.mock.calls.length, 1); assert.deepEqual(runtime.uses, [['perfNativeCaptureStart']]); assert.equal(sessionStore.get('android')?.perfCapture, undefined); diff --git a/packages/remote/src/capture-destination-record.ts b/packages/remote/src/capture-destination-record.ts index 142d66cf874..16312b63156 100644 --- a/packages/remote/src/capture-destination-record.ts +++ b/packages/remote/src/capture-destination-record.ts @@ -190,6 +190,38 @@ function confirmedStartCapture( }; } +function recordConfirmedStart( + record: RecordState, + active: Active, + confirmedOrder: number, + reportedOrder: unknown, +): RecordState { + const daemonStartOrder = + typeof reportedOrder === 'number' && Number.isSafeInteger(reportedOrder) + ? reportedOrder + : undefined; + if ( + daemonStartOrder !== undefined && record.daemonStartOrder !== undefined + ? daemonStartOrder <= record.daemonStartOrder + : active.order < confirmedOrder + ) + return record; + const latestConfirmedOrder = Math.max(confirmedOrder, active.order); + return { + ...record, + active, + // Older live reservations can arrive at the daemon after this start has stopped. + pending: record.pending.filter( + (candidate) => + candidate.order > latestConfirmedOrder || + (candidate.pid !== undefined && isProcessAlive(candidate.pid)), + ), + certainty: 'settled', + confirmedOrder: latestConfirmedOrder, + daemonStartOrder, + }; +} + function recordAfterStart( current: RecordState, response: DaemonResponse | undefined, @@ -206,31 +238,7 @@ function recordAfterStart( const active = confirmedStartCapture(response, generation, destination, order); if (!active) return order < confirmedOrder ? next : { ...next, active: undefined, certainty: uncertain }; - const reportedOrder = response.data?.captureStartOrder; - const daemonStartOrder = - typeof reportedOrder === 'number' && Number.isSafeInteger(reportedOrder) - ? reportedOrder - : undefined; - if ( - daemonStartOrder !== undefined && current.daemonStartOrder !== undefined - ? daemonStartOrder <= current.daemonStartOrder - : order < confirmedOrder - ) - return next; - const latestConfirmedOrder = Math.max(confirmedOrder, order); - return { - ...next, - active, - // Older live reservations can arrive at the daemon after this start has stopped. - pending: pending.filter( - (candidate) => - candidate.order > latestConfirmedOrder || - (candidate.pid !== undefined && isProcessAlive(candidate.pid)), - ), - certainty: 'settled', - confirmedOrder: latestConfirmedOrder, - daemonStartOrder, - }; + return recordConfirmedStart(next, active, confirmedOrder, response.data?.captureStartOrder); } if (order < confirmedOrder) return next; const details = refusalDetails(response, failure);