diff --git a/src/daemon.ts b/src/daemon.ts index 4e015bd425..9e29982a89 100644 --- a/src/daemon.ts +++ b/src/daemon.ts @@ -1,53 +1,30 @@ -import net from 'node:net'; -import type { Server as HttpServer } from 'node:http'; -import fs from 'node:fs'; -import path from 'node:path'; import crypto from 'node:crypto'; -import { dispatchCommand, type CommandFlags } from './core/dispatch.ts'; -import { isCommandSupportedOnDevice } from './core/capabilities.ts'; -import { asAppError, AppError, normalizeError } from './utils/errors.ts'; -import { findProjectRoot, readVersion } from './utils/version.ts'; -import { abortAllIosRunnerSessions, stopAllIosRunnerSessions } from './platforms/ios/runner-client.ts'; -import type { DaemonArtifact, DaemonRequest, DaemonResponse, DaemonResponseData } from './daemon/types.ts'; +import { asAppError, AppError } from './utils/errors.ts'; +import { stopAllIosRunnerSessions } from './platforms/ios/runner-client.ts'; import { SessionStore } from './daemon/session-store.ts'; -import { contextFromFlags as contextFromFlagsWithLog, type DaemonCommandContext } from './daemon/context.ts'; -import { handleSessionCommands } from './daemon/handlers/session.ts'; -import { handleSnapshotCommands } from './daemon/handlers/snapshot.ts'; -import { handleFindCommands } from './daemon/handlers/find.ts'; -import { handleRecordTraceCommands } from './daemon/handlers/record-trace.ts'; -import { handleInteractionCommands } from './daemon/handlers/interaction.ts'; -import { handleLeaseCommands } from './daemon/handlers/lease.ts'; import { cleanupStaleAppLogProcesses } from './daemon/app-log.ts'; -import { assertSessionSelectorMatches } from './daemon/session-selector.ts'; -import { resolveEffectiveSessionName } from './daemon/session-routing.ts'; -import { - clearRequestCanceled, - createRequestCanceledError, - isRequestCanceled, - markRequestCanceled, - registerRequestAbort, - resolveRequestTrackingId, -} from './daemon/request-cancel.ts'; -import { - isAgentDeviceDaemonProcess, - readProcessStartTime, -} from './utils/process-identity.ts'; -import { emitDiagnostic, flushDiagnosticsToSessionFile, getDiagnosticsMeta, withDiagnosticsScope } from './utils/diagnostics.ts'; -import { - normalizeTenantId, - resolveDaemonPaths, - resolveDaemonServerMode, - resolveSessionIsolationMode, -} from './daemon/config.ts'; +import { resolveDaemonPaths, resolveDaemonServerMode } from './daemon/config.ts'; import { createDaemonHttpServer } from './daemon/http-server.ts'; import { trackDownloadableArtifact } from './daemon/artifact-registry.ts'; import { LeaseRegistry } from './daemon/lease-registry.ts'; -import { resolveLeaseScope } from './daemon/lease-context.ts'; +import { createRequestHandler } from './daemon/request-router.ts'; +import { + acquireDaemonLock, + parseIntegerEnv, + readProcessStartTime, + readVersion, + releaseDaemonLock, + removeInfo, + resolveDaemonCodeSignature, + writeInfo, +} from './daemon/server-lifecycle.ts'; +import { createSocketServer, listenHttpServer, listenNetServer } from './daemon/transport.ts'; const daemonPaths = resolveDaemonPaths(process.env.AGENT_DEVICE_STATE_DIR); const { baseDir, infoPath, lockPath, logPath, sessionsDir } = daemonPaths; const daemonServerMode = resolveDaemonServerMode(process.env.AGENT_DEVICE_DAEMON_SERVER_MODE); cleanupStaleAppLogProcesses(sessionsDir); + const sessionStore = new SessionStore(sessionsDir); const leaseRegistry = new LeaseRegistry({ maxActiveSimulatorLeases: parseIntegerEnv(process.env.AGENT_DEVICE_MAX_SIMULATOR_LEASES), @@ -57,510 +34,19 @@ const leaseRegistry = new LeaseRegistry({ }); const version = readVersion(); const token = crypto.randomBytes(24).toString('hex'); -const selectorValidationExemptCommands = new Set(['session_list', 'devices', 'ensure-simulator']); -const leaseAdmissionExemptCommands = new Set([ - 'session_list', - 'devices', - 'ensure-simulator', - 'lease_allocate', - 'lease_heartbeat', - 'lease_release', -]); -const disconnectAbortPollIntervalMs = 200; -const disconnectAbortMaxWindowMs = 15_000; - -type DaemonLockInfo = { - pid: number; - version: string; - startedAt: number; - processStartTime?: string; -}; - const daemonProcessStartTime = readProcessStartTime(process.pid) ?? undefined; const daemonCodeSignature = resolveDaemonCodeSignature(); -function contextFromFlags( - flags: CommandFlags | undefined, - appBundleId?: string, - traceLogPath?: string, -): DaemonCommandContext { - const requestId = getDiagnosticsMeta().requestId; - return { - ...contextFromFlagsWithLog(logPath, flags, appBundleId, traceLogPath, requestId), - requestId, - }; -} - -function scopeRequestSession(req: DaemonRequest): DaemonRequest { - const isolation = resolveSessionIsolationMode(req.meta?.sessionIsolation ?? req.flags?.sessionIsolation); - const rawTenant = req.meta?.tenantId ?? req.flags?.tenant; - const tenant = normalizeTenantId(rawTenant); - - if (rawTenant && !tenant) { - throw new AppError('INVALID_ARGS', 'Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.'); - } - if (isolation !== 'tenant') { - return req; - } - if (!tenant) { - throw new AppError('INVALID_ARGS', 'session isolation mode tenant requires --tenant (or meta.tenantId).'); - } - return { - ...req, - session: `${tenant}:${req.session || 'default'}`, - meta: { - ...req.meta, - tenantId: tenant, - sessionIsolation: isolation, - }, - }; -} - -async function handleRequest(req: DaemonRequest): Promise { - const normalizedReq = normalizeAliasedCommands(req); - const debug = Boolean(normalizedReq.meta?.debug || normalizedReq.flags?.verbose); - return await withDiagnosticsScope( - { - session: normalizedReq.session, - requestId: normalizedReq.meta?.requestId, - command: normalizedReq.command, - debug, - logPath, - }, - async () => { - if (normalizedReq.token !== token) { - const unauthorizedError = normalizeError(new AppError('UNAUTHORIZED', 'Invalid token')); - return { ok: false, error: unauthorizedError }; - } - - try { - const scopedReq = scopeRequestSession(normalizedReq); - emitDiagnostic({ - level: 'info', - phase: 'request_start', - data: { - session: scopedReq.session, - command: scopedReq.command, - tenant: scopedReq.meta?.tenantId, - isolation: scopedReq.meta?.sessionIsolation, - }, - }); - - const command = scopedReq.command; - const finalize = (response: DaemonResponse): DaemonResponse => finalizeDaemonResponse(scopedReq, response); - const leaseScope = resolveLeaseScope(scopedReq); - if (!leaseAdmissionExemptCommands.has(command) && scopedReq.meta?.sessionIsolation === 'tenant') { - leaseRegistry.assertLeaseAdmission({ - tenantId: leaseScope.tenantId, - runId: leaseScope.runId, - leaseId: leaseScope.leaseId, - backend: leaseScope.leaseBackend, - }); - } - const sessionName = resolveEffectiveSessionName(scopedReq, sessionStore); - const existingSession = sessionStore.get(sessionName); - if (existingSession && !selectorValidationExemptCommands.has(command)) { - assertSessionSelectorMatches(existingSession, scopedReq.flags); - } - - const leaseResponse = await handleLeaseCommands({ - req: scopedReq, - leaseRegistry, - }); - if (leaseResponse) return finalize(leaseResponse); - - const sessionResponse = await handleSessionCommands({ - req: scopedReq, - sessionName, - logPath, - sessionStore, - invoke: handleRequest, - }); - if (sessionResponse) return finalize(sessionResponse); - - const snapshotResponse = await handleSnapshotCommands({ - req: scopedReq, - sessionName, - logPath, - sessionStore, - }); - if (snapshotResponse) return finalize(snapshotResponse); - - const recordTraceResponse = await handleRecordTraceCommands({ - req: scopedReq, - sessionName, - sessionStore, - logPath, - }); - if (recordTraceResponse) return finalize(recordTraceResponse); - - const findResponse = await handleFindCommands({ - req: scopedReq, - sessionName, - logPath, - sessionStore, - invoke: handleRequest, - }); - if (findResponse) return finalize(findResponse); - - const interactionResponse = await handleInteractionCommands({ - req: scopedReq, - sessionName, - sessionStore, - contextFromFlags, - }); - if (interactionResponse) return finalize(interactionResponse); - - const session = sessionStore.get(sessionName); - if (!session) { - return finalize({ - ok: false, - error: { code: 'SESSION_NOT_FOUND', message: 'No active session. Run open first.' }, - }); - } - - if (!isCommandSupportedOnDevice(command, session.device)) { - return finalize({ - ok: false, - error: { code: 'UNSUPPORTED_OPERATION', message: `${command} is not supported on this device` }, - }); - } - - const data = await dispatchCommand(session.device, command, scopedReq.positionals ?? [], scopedReq.flags?.out, { - ...contextFromFlags(scopedReq.flags, session.appBundleId, session.trace?.outPath), - }); - sessionStore.recordAction(session, { - command, - positionals: scopedReq.positionals ?? [], - flags: scopedReq.flags ?? {}, - result: data ?? {}, - }); - return finalize({ ok: true, data: data ?? {} }); - } catch (error) { - emitDiagnostic({ - level: 'error', - phase: 'request_failed', - data: { - error: error instanceof Error ? error.message : String(error), - }, - }); - const details = getDiagnosticsMeta(); - const logPathOnFailure = flushDiagnosticsToSessionFile({ force: true }) ?? undefined; - const normalizedError = normalizeError(error, { - diagnosticId: details.diagnosticId, - logPath: logPathOnFailure, - }); - return { ok: false, error: normalizedError }; - } - }, - ); -} - -function finalizeDaemonResponse(req: DaemonRequest, response: DaemonResponse): DaemonResponse { - const details = getDiagnosticsMeta(); - if (!response.ok) { - emitDiagnostic({ - level: 'error', - phase: 'request_failed', - data: { - code: response.error.code, - message: response.error.message, - }, - }); - const logPathOnFailure = flushDiagnosticsToSessionFile({ force: true }) ?? undefined; - const normalizedError = normalizeError( - new AppError(response.error.code as any, response.error.message, { - ...(response.error.details ?? {}), - hint: response.error.hint, - diagnosticId: response.error.diagnosticId, - logPath: response.error.logPath, - }), - { - diagnosticId: details.diagnosticId, - logPath: logPathOnFailure, - }, - ); - return { ok: false, error: normalizedError }; - } - emitDiagnostic({ level: 'info', phase: 'request_success' }); - flushDiagnosticsToSessionFile(); - return { - ok: true, - data: registerDownloadableArtifacts(req, response.data), - }; -} - -function registerDownloadableArtifacts( - req: DaemonRequest, - data: DaemonResponseData | undefined, -): DaemonResponseData | undefined { - if (!data) return data; - const pendingArtifacts = collectPendingArtifacts(req, data); - if (pendingArtifacts.length === 0) return data; - return { - ...data, - artifacts: pendingArtifacts.map((artifact) => { - const artifactPath = artifact.path as string; - return { - field: artifact.field, - artifactId: trackDownloadableArtifact({ - artifactPath, - tenantId: req.meta?.tenantId, - fileName: artifact.fileName, - }), - fileName: artifact.fileName, - localPath: artifact.localPath, - }; - }), - }; -} - -function collectPendingArtifacts(req: DaemonRequest, data: DaemonResponseData): DaemonArtifact[] { - const artifacts = Array.isArray(data.artifacts) ? [...data.artifacts] : []; - const hasField = (field: string): boolean => artifacts.some((artifact) => artifact?.field === field); - if ( - req.command === 'screenshot' - && !hasField('path') - && typeof data.path === 'string' - ) { - artifacts.push({ - field: 'path', - path: data.path, - localPath: req.meta?.clientArtifactPaths?.path, - fileName: path.basename(req.meta?.clientArtifactPaths?.path ?? data.path), - }); - } - return artifacts.filter((artifact): artifact is DaemonArtifact => - Boolean( - artifact - && typeof artifact.field === 'string' - && typeof artifact.path === 'string' - && typeof artifact.localPath === 'string' - && artifact.localPath.length > 0, - ), - ); -} - -function normalizeAliasedCommands(req: DaemonRequest): DaemonRequest { - if (req.command === 'click') { - return { ...req, command: 'press' }; - } - return req; -} - -function writeInfo(ports: { socketPort?: number; httpPort?: number }): void { - if (!fs.existsSync(baseDir)) fs.mkdirSync(baseDir, { recursive: true }); - fs.writeFileSync(logPath, ''); - const transport = ports.httpPort && ports.socketPort - ? 'dual' - : ports.httpPort - ? 'http' - : 'socket'; - fs.writeFileSync( - infoPath, - JSON.stringify( - { - port: ports.socketPort, - httpPort: ports.httpPort, - transport, - token, - pid: process.pid, - version, - codeSignature: daemonCodeSignature, - processStartTime: daemonProcessStartTime, - stateDir: baseDir, - }, - null, - 2, - ), - { - mode: 0o600, - }, - ); -} - -function resolveDaemonCodeSignature(): string { - const entryPath = process.argv[1]; - if (!entryPath) return 'unknown'; - try { - const stat = fs.statSync(entryPath); - const root = findProjectRoot(); - const relativePath = path.relative(root, entryPath) || entryPath; - return `${relativePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`; - } catch { - return 'unknown'; - } -} - -function removeInfo(): void { - if (fs.existsSync(infoPath)) fs.unlinkSync(infoPath); -} +const handleRequest = createRequestHandler({ logPath, token, sessionStore, leaseRegistry, trackDownloadableArtifact }); -function readLockInfo(): DaemonLockInfo | null { - if (!fs.existsSync(lockPath)) return null; - try { - const parsed = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as DaemonLockInfo; - if (!Number.isInteger(parsed.pid) || parsed.pid <= 0) return null; - return parsed; - } catch { - return null; - } -} - -function acquireDaemonLock(): boolean { - if (!fs.existsSync(baseDir)) fs.mkdirSync(baseDir, { recursive: true }); - const lockData: DaemonLockInfo = { +async function start(): Promise { + const lockData = { pid: process.pid, version, startedAt: Date.now(), processStartTime: daemonProcessStartTime, }; - const payload = JSON.stringify(lockData, null, 2); - - const tryWriteLock = (): boolean => { - try { - fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); - return true; - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; - throw err; - } - }; - - if (tryWriteLock()) return true; - const existing = readLockInfo(); - if ( - existing?.pid - && existing.pid !== process.pid - && isAgentDeviceDaemonProcess(existing.pid, existing.processStartTime) - ) { - return false; - } - try { - fs.unlinkSync(lockPath); - } catch { - // ignore - } - return tryWriteLock(); -} - -function releaseDaemonLock(): void { - const existing = readLockInfo(); - if (existing && existing.pid !== process.pid) return; - try { - if (fs.existsSync(lockPath)) fs.unlinkSync(lockPath); - } catch { - // ignore - } -} - -function createSocketServer(): net.Server { - return net.createServer((socket) => { - let buffer = ''; - let inFlightRequests = 0; - const activeRequestIds = new Set(); - let canceledInFlight = false; - const cancelInFlightRunnerSessions = () => { - if (canceledInFlight || inFlightRequests === 0) return; - canceledInFlight = true; - for (const requestId of activeRequestIds) { - markRequestCanceled(requestId); - } - emitDiagnostic({ - level: 'warn', - phase: 'request_client_disconnected', - data: { - inFlightRequests, - }, - }); - void (async () => { - const deadline = Date.now() + disconnectAbortMaxWindowMs; - while (inFlightRequests > 0 && Date.now() < deadline) { - await abortAllIosRunnerSessions(); - if (inFlightRequests <= 0) break; - await sleep(disconnectAbortPollIntervalMs); - } - })(); - }; - socket.setEncoding('utf8'); - socket.on('close', cancelInFlightRunnerSessions); - socket.on('error', cancelInFlightRunnerSessions); - socket.on('data', async (chunk) => { - buffer += chunk; - let idx = buffer.indexOf('\n'); - while (idx !== -1) { - const line = buffer.slice(0, idx).trim(); - buffer = buffer.slice(idx + 1); - if (line.length === 0) { - idx = buffer.indexOf('\n'); - continue; - } - let response: DaemonResponse; - inFlightRequests += 1; - let requestIdForCleanup: string | undefined; - try { - const req = JSON.parse(line) as DaemonRequest; - requestIdForCleanup = resolveRequestTrackingId(req.meta?.requestId, 'socket'); - req.meta = { - ...req.meta, - requestId: requestIdForCleanup, - }; - activeRequestIds.add(requestIdForCleanup); - registerRequestAbort(requestIdForCleanup); - if (isRequestCanceled(requestIdForCleanup)) { - throw createRequestCanceledError(); - } - response = await handleRequest(req); - } catch (err) { - response = { ok: false, error: normalizeError(err) }; - } finally { - inFlightRequests -= 1; - if (requestIdForCleanup) { - activeRequestIds.delete(requestIdForCleanup); - clearRequestCanceled(requestIdForCleanup); - } - } - if (!socket.destroyed) { - socket.write(`${JSON.stringify(response)}\n`); - } - idx = buffer.indexOf('\n'); - } - }); - }); -} - -function listenNetServer(server: net.Server): Promise { - return new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(0, '127.0.0.1', () => { - server.off('error', reject); - const address = server.address(); - if (typeof address === 'object' && address?.port) { - resolve(address.port); - return; - } - reject(new AppError('COMMAND_FAILED', 'Failed to bind socket server')); - }); - }); -} - -function listenHttpServer(server: HttpServer): Promise { - return new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(0, '127.0.0.1', () => { - server.off('error', reject); - const address = server.address(); - if (typeof address === 'object' && address?.port) { - resolve(address.port); - return; - } - reject(new AppError('COMMAND_FAILED', 'Failed to bind HTTP server')); - }); - }); -} - -async function start(): Promise { - if (!acquireDaemonLock()) { + if (!acquireDaemonLock(baseDir, lockPath, lockData)) { process.stderr.write('Daemon lock is held by another process; exiting.\n'); process.exit(0); return; @@ -572,7 +58,7 @@ async function start(): Promise { try { if (daemonServerMode === 'socket' || daemonServerMode === 'dual') { - const socketServer = createSocketServer(); + const socketServer = createSocketServer(handleRequest); servers.push(socketServer); socketPort = await listenNetServer(socketServer); } @@ -583,7 +69,14 @@ async function start(): Promise { httpPort = await listenHttpServer(httpServer); } - writeInfo({ socketPort, httpPort }); + writeInfo(baseDir, infoPath, logPath, { + socketPort, + httpPort, + token, + version, + codeSignature: daemonCodeSignature, + processStartTime: daemonProcessStartTime, + }); if (socketPort) process.stdout.write(`AGENT_DEVICE_DAEMON_PORT=${socketPort}\n`); if (httpPort) process.stdout.write(`AGENT_DEVICE_DAEMON_HTTP_PORT=${httpPort}\n`); } catch (error) { @@ -596,8 +89,8 @@ async function start(): Promise { // ignore } } - removeInfo(); - releaseDaemonLock(); + removeInfo(infoPath); + releaseDaemonLock(lockPath); process.exit(1); return; } @@ -625,8 +118,8 @@ async function start(): Promise { sessionStore.writeSessionLog(session); } await stopAllIosRunnerSessions(); - removeInfo(); - releaseDaemonLock(); + removeInfo(infoPath); + releaseDaemonLock(lockPath); process.exit(0); }; @@ -646,15 +139,4 @@ async function start(): Promise { }); } -function sleep(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - void start(); - -function parseIntegerEnv(raw: string | undefined): number | undefined { - if (raw === undefined) return undefined; - const value = Number(raw); - if (!Number.isInteger(value)) return undefined; - return value; -} diff --git a/src/daemon/request-router.ts b/src/daemon/request-router.ts new file mode 100644 index 0000000000..2addbb2892 --- /dev/null +++ b/src/daemon/request-router.ts @@ -0,0 +1,324 @@ +import path from 'node:path'; +import type { CommandFlags } from '../core/dispatch.ts'; +import { dispatchCommand } from '../core/dispatch.ts'; +import { isCommandSupportedOnDevice } from '../core/capabilities.ts'; +import { AppError, normalizeError } from '../utils/errors.ts'; +import type { DaemonArtifact, DaemonRequest, DaemonResponse, DaemonResponseData } from './types.ts'; +import { SessionStore } from './session-store.ts'; +import { contextFromFlags as contextFromFlagsWithLog, type DaemonCommandContext } from './context.ts'; +import { handleSessionCommands } from './handlers/session.ts'; +import { handleSnapshotCommands } from './handlers/snapshot.ts'; +import { handleFindCommands } from './handlers/find.ts'; +import { handleRecordTraceCommands } from './handlers/record-trace.ts'; +import { handleInteractionCommands } from './handlers/interaction.ts'; +import { handleLeaseCommands } from './handlers/lease.ts'; +import { assertSessionSelectorMatches } from './session-selector.ts'; +import { resolveEffectiveSessionName } from './session-routing.ts'; +import { + normalizeTenantId, + resolveSessionIsolationMode, +} from './config.ts'; +import { emitDiagnostic, flushDiagnosticsToSessionFile, getDiagnosticsMeta, withDiagnosticsScope } from '../utils/diagnostics.ts'; +import { resolveLeaseScope } from './lease-context.ts'; +import type { LeaseRegistry } from './lease-registry.ts'; + +const selectorValidationExemptCommands = new Set(['session_list', 'devices', 'ensure-simulator']); +const leaseAdmissionExemptCommands = new Set([ + 'session_list', + 'devices', + 'ensure-simulator', + 'lease_allocate', + 'lease_heartbeat', + 'lease_release', +]); + +function contextFromFlags( + logPath: string, + flags: CommandFlags | undefined, + appBundleId?: string, + traceLogPath?: string, +): DaemonCommandContext { + const requestId = getDiagnosticsMeta().requestId; + return { + ...contextFromFlagsWithLog(logPath, flags, appBundleId, traceLogPath, requestId), + requestId, + }; +} + +function normalizeAliasedCommands(req: DaemonRequest): DaemonRequest { + if (req.command === 'click') { + return { ...req, command: 'press' }; + } + return req; +} + +function scopeRequestSession(req: DaemonRequest): DaemonRequest { + const isolation = resolveSessionIsolationMode(req.meta?.sessionIsolation ?? req.flags?.sessionIsolation); + const rawTenant = req.meta?.tenantId ?? req.flags?.tenant; + const tenant = normalizeTenantId(rawTenant); + + if (rawTenant && !tenant) { + throw new AppError('INVALID_ARGS', 'Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.'); + } + if (isolation !== 'tenant') { + return req; + } + if (!tenant) { + throw new AppError('INVALID_ARGS', 'session isolation mode tenant requires --tenant (or meta.tenantId).'); + } + return { + ...req, + session: `${tenant}:${req.session || 'default'}`, + meta: { + ...req.meta, + tenantId: tenant, + sessionIsolation: isolation, + }, + }; +} + +function finalizeDaemonResponse( + req: DaemonRequest, + response: DaemonResponse, + trackArtifact: (opts: { artifactPath: string; tenantId?: string; fileName?: string }) => string, +): DaemonResponse { + const details = getDiagnosticsMeta(); + if (!response.ok) { + emitDiagnostic({ + level: 'error', + phase: 'request_failed', + data: { + code: response.error.code, + message: response.error.message, + }, + }); + const logPathOnFailure = flushDiagnosticsToSessionFile({ force: true }) ?? undefined; + const normalizedError = normalizeError( + new AppError(response.error.code as any, response.error.message, { + ...(response.error.details ?? {}), + hint: response.error.hint, + diagnosticId: response.error.diagnosticId, + logPath: response.error.logPath, + }), + { + diagnosticId: details.diagnosticId, + logPath: logPathOnFailure, + }, + ); + return { ok: false, error: normalizedError }; + } + emitDiagnostic({ level: 'info', phase: 'request_success' }); + flushDiagnosticsToSessionFile(); + return { + ok: true, + data: registerDownloadableArtifacts(req, response.data, trackArtifact), + }; +} + +function registerDownloadableArtifacts( + req: DaemonRequest, + data: DaemonResponseData | undefined, + trackArtifact: (opts: { artifactPath: string; tenantId?: string; fileName?: string }) => string, +): DaemonResponseData | undefined { + if (!data) return data; + const pendingArtifacts = collectPendingArtifacts(req, data); + if (pendingArtifacts.length === 0) return data; + return { + ...data, + artifacts: pendingArtifacts.map((artifact) => { + const artifactPath = artifact.path as string; + return { + field: artifact.field, + artifactId: trackArtifact({ + artifactPath, + tenantId: req.meta?.tenantId, + fileName: artifact.fileName, + }), + fileName: artifact.fileName, + localPath: artifact.localPath, + }; + }), + }; +} + +function collectPendingArtifacts(req: DaemonRequest, data: DaemonResponseData): DaemonArtifact[] { + const artifacts = Array.isArray(data.artifacts) ? [...data.artifacts] : []; + const hasField = (field: string): boolean => artifacts.some((artifact) => artifact?.field === field); + if ( + req.command === 'screenshot' + && !hasField('path') + && typeof data.path === 'string' + ) { + artifacts.push({ + field: 'path', + path: data.path, + localPath: req.meta?.clientArtifactPaths?.path, + fileName: path.basename(req.meta?.clientArtifactPaths?.path ?? data.path), + }); + } + return artifacts.filter((artifact): artifact is DaemonArtifact => + Boolean( + artifact + && typeof artifact.field === 'string' + && typeof artifact.path === 'string' + && typeof artifact.localPath === 'string' + && artifact.localPath.length > 0, + ), + ); +} + +export type RequestRouterDeps = { + logPath: string; + token: string; + sessionStore: SessionStore; + leaseRegistry: LeaseRegistry; + trackDownloadableArtifact: (opts: { artifactPath: string; tenantId?: string; fileName?: string }) => string; +}; + +export function createRequestHandler(deps: RequestRouterDeps): (req: DaemonRequest) => Promise { + const { logPath, token, sessionStore, leaseRegistry, trackDownloadableArtifact } = deps; + + async function handleRequest(req: DaemonRequest): Promise { + const normalizedReq = normalizeAliasedCommands(req); + const debug = Boolean(normalizedReq.meta?.debug || normalizedReq.flags?.verbose); + return await withDiagnosticsScope( + { + session: normalizedReq.session, + requestId: normalizedReq.meta?.requestId, + command: normalizedReq.command, + debug, + logPath, + }, + async () => { + if (normalizedReq.token !== token) { + const unauthorizedError = normalizeError(new AppError('UNAUTHORIZED', 'Invalid token')); + return { ok: false, error: unauthorizedError }; + } + + try { + const scopedReq = scopeRequestSession(normalizedReq); + emitDiagnostic({ + level: 'info', + phase: 'request_start', + data: { + session: scopedReq.session, + command: scopedReq.command, + tenant: scopedReq.meta?.tenantId, + isolation: scopedReq.meta?.sessionIsolation, + }, + }); + + const command = scopedReq.command; + const finalize = (response: DaemonResponse): DaemonResponse => + finalizeDaemonResponse(scopedReq, response, trackDownloadableArtifact); + const leaseScope = resolveLeaseScope(scopedReq); + if (!leaseAdmissionExemptCommands.has(command) && scopedReq.meta?.sessionIsolation === 'tenant') { + leaseRegistry.assertLeaseAdmission({ + tenantId: leaseScope.tenantId, + runId: leaseScope.runId, + leaseId: leaseScope.leaseId, + backend: leaseScope.leaseBackend, + }); + } + const sessionName = resolveEffectiveSessionName(scopedReq, sessionStore); + const existingSession = sessionStore.get(sessionName); + if (existingSession && !selectorValidationExemptCommands.has(command)) { + assertSessionSelectorMatches(existingSession, scopedReq.flags); + } + + const leaseResponse = await handleLeaseCommands({ + req: scopedReq, + leaseRegistry, + }); + if (leaseResponse) return finalize(leaseResponse); + + const sessionResponse = await handleSessionCommands({ + req: scopedReq, + sessionName, + logPath, + sessionStore, + invoke: handleRequest, + }); + if (sessionResponse) return finalize(sessionResponse); + + const snapshotResponse = await handleSnapshotCommands({ + req: scopedReq, + sessionName, + logPath, + sessionStore, + }); + if (snapshotResponse) return finalize(snapshotResponse); + + const recordTraceResponse = await handleRecordTraceCommands({ + req: scopedReq, + sessionName, + sessionStore, + logPath, + }); + if (recordTraceResponse) return finalize(recordTraceResponse); + + const findResponse = await handleFindCommands({ + req: scopedReq, + sessionName, + logPath, + sessionStore, + invoke: handleRequest, + }); + if (findResponse) return finalize(findResponse); + + const interactionResponse = await handleInteractionCommands({ + req: scopedReq, + sessionName, + sessionStore, + contextFromFlags: (flags, appBundleId, traceLogPath) => + contextFromFlags(logPath, flags, appBundleId, traceLogPath), + }); + if (interactionResponse) return finalize(interactionResponse); + + const session = sessionStore.get(sessionName); + if (!session) { + return finalize({ + ok: false, + error: { code: 'SESSION_NOT_FOUND', message: 'No active session. Run open first.' }, + }); + } + + if (!isCommandSupportedOnDevice(command, session.device)) { + return finalize({ + ok: false, + error: { code: 'UNSUPPORTED_OPERATION', message: `${command} is not supported on this device` }, + }); + } + + const data = await dispatchCommand(session.device, command, scopedReq.positionals ?? [], scopedReq.flags?.out, { + ...contextFromFlags(logPath, scopedReq.flags, session.appBundleId, session.trace?.outPath), + }); + sessionStore.recordAction(session, { + command, + positionals: scopedReq.positionals ?? [], + flags: scopedReq.flags ?? {}, + result: data ?? {}, + }); + return finalize({ ok: true, data: data ?? {} }); + } catch (error) { + emitDiagnostic({ + level: 'error', + phase: 'request_failed', + data: { + error: error instanceof Error ? error.message : String(error), + }, + }); + const details = getDiagnosticsMeta(); + const logPathOnFailure = flushDiagnosticsToSessionFile({ force: true }) ?? undefined; + const normalizedError = normalizeError(error, { + diagnosticId: details.diagnosticId, + logPath: logPathOnFailure, + }); + return { ok: false, error: normalizedError }; + } + }, + ); + } + + return handleRequest; +} diff --git a/src/daemon/server-lifecycle.ts b/src/daemon/server-lifecycle.ts new file mode 100644 index 0000000000..0912dbb775 --- /dev/null +++ b/src/daemon/server-lifecycle.ts @@ -0,0 +1,139 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { findProjectRoot, readVersion } from '../utils/version.ts'; +import { + isAgentDeviceDaemonProcess, + readProcessStartTime, +} from '../utils/process-identity.ts'; + +export type DaemonLockInfo = { + pid: number; + version: string; + startedAt: number; + processStartTime?: string; +}; + +export function resolveDaemonCodeSignature(): string { + const entryPath = process.argv[1]; + if (!entryPath) return 'unknown'; + try { + const stat = fs.statSync(entryPath); + const root = findProjectRoot(); + const relativePath = path.relative(root, entryPath) || entryPath; + return `${relativePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`; + } catch { + return 'unknown'; + } +} + +export function writeInfo( + baseDir: string, + infoPath: string, + logPath: string, + opts: { + socketPort?: number; + httpPort?: number; + token: string; + version: string; + codeSignature: string; + processStartTime: string | undefined; + }, +): void { + if (!fs.existsSync(baseDir)) fs.mkdirSync(baseDir, { recursive: true }); + fs.writeFileSync(logPath, ''); + const transport = opts.socketPort && opts.httpPort + ? 'dual' + : opts.httpPort + ? 'http' + : 'socket'; + fs.writeFileSync( + infoPath, + JSON.stringify( + { + port: opts.socketPort, + httpPort: opts.httpPort, + transport, + token: opts.token, + pid: process.pid, + version: opts.version, + codeSignature: opts.codeSignature, + processStartTime: opts.processStartTime, + stateDir: baseDir, + }, + null, + 2, + ), + { + mode: 0o600, + }, + ); +} + +export function removeInfo(infoPath: string): void { + if (fs.existsSync(infoPath)) fs.unlinkSync(infoPath); +} + +export function readLockInfo(lockPath: string): DaemonLockInfo | null { + if (!fs.existsSync(lockPath)) return null; + try { + const parsed = JSON.parse(fs.readFileSync(lockPath, 'utf8')) as DaemonLockInfo; + if (!Number.isInteger(parsed.pid) || parsed.pid <= 0) return null; + return parsed; + } catch { + return null; + } +} + +export function acquireDaemonLock( + baseDir: string, + lockPath: string, + lockData: DaemonLockInfo, +): boolean { + if (!fs.existsSync(baseDir)) fs.mkdirSync(baseDir, { recursive: true }); + const payload = JSON.stringify(lockData, null, 2); + + const tryWriteLock = (): boolean => { + try { + fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); + return true; + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; + throw err; + } + }; + + if (tryWriteLock()) return true; + const existing = readLockInfo(lockPath); + if ( + existing?.pid + && existing.pid !== process.pid + && isAgentDeviceDaemonProcess(existing.pid, existing.processStartTime) + ) { + return false; + } + try { + fs.unlinkSync(lockPath); + } catch { + // ignore + } + return tryWriteLock(); +} + +export function releaseDaemonLock(lockPath: string): void { + const existing = readLockInfo(lockPath); + if (existing && existing.pid !== process.pid) return; + try { + if (fs.existsSync(lockPath)) fs.unlinkSync(lockPath); + } catch { + // ignore + } +} + +export function parseIntegerEnv(raw: string | undefined): number | undefined { + if (raw === undefined) return undefined; + const value = Number(raw); + if (!Number.isInteger(value)) return undefined; + return value; +} + +export { readVersion, readProcessStartTime }; diff --git a/src/daemon/transport.ts b/src/daemon/transport.ts new file mode 100644 index 0000000000..6579ac110b --- /dev/null +++ b/src/daemon/transport.ts @@ -0,0 +1,129 @@ +import net from 'node:net'; +import type { Server as HttpServer } from 'node:http'; +import { normalizeError } from '../utils/errors.ts'; +import { AppError } from '../utils/errors.ts'; +import type { DaemonRequest, DaemonResponse } from './types.ts'; +import { abortAllIosRunnerSessions } from '../platforms/ios/runner-client.ts'; +import { + clearRequestCanceled, + createRequestCanceledError, + isRequestCanceled, + markRequestCanceled, + registerRequestAbort, + resolveRequestTrackingId, +} from './request-cancel.ts'; +import { emitDiagnostic } from '../utils/diagnostics.ts'; + +const disconnectAbortPollIntervalMs = 200; +const disconnectAbortMaxWindowMs = 15_000; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export function createSocketServer( + handleRequest: (req: DaemonRequest) => Promise, +): net.Server { + return net.createServer((socket) => { + let buffer = ''; + let inFlightRequests = 0; + const activeRequestIds = new Set(); + let canceledInFlight = false; + const cancelInFlightRunnerSessions = () => { + if (canceledInFlight || inFlightRequests === 0) return; + canceledInFlight = true; + for (const requestId of activeRequestIds) { + markRequestCanceled(requestId); + } + emitDiagnostic({ + level: 'warn', + phase: 'request_client_disconnected', + data: { + inFlightRequests, + }, + }); + void (async () => { + const deadline = Date.now() + disconnectAbortMaxWindowMs; + while (inFlightRequests > 0 && Date.now() < deadline) { + await abortAllIosRunnerSessions(); + if (inFlightRequests <= 0) break; + await sleep(disconnectAbortPollIntervalMs); + } + })(); + }; + socket.setEncoding('utf8'); + socket.on('close', cancelInFlightRunnerSessions); + socket.on('error', cancelInFlightRunnerSessions); + socket.on('data', async (chunk) => { + buffer += chunk; + let idx = buffer.indexOf('\n'); + while (idx !== -1) { + const line = buffer.slice(0, idx).trim(); + buffer = buffer.slice(idx + 1); + if (line.length === 0) { + idx = buffer.indexOf('\n'); + continue; + } + let response: DaemonResponse; + inFlightRequests += 1; + let requestIdForCleanup: string | undefined; + try { + const req = JSON.parse(line) as DaemonRequest; + requestIdForCleanup = resolveRequestTrackingId(req.meta?.requestId, 'socket'); + req.meta = { + ...req.meta, + requestId: requestIdForCleanup, + }; + activeRequestIds.add(requestIdForCleanup); + registerRequestAbort(requestIdForCleanup); + if (isRequestCanceled(requestIdForCleanup)) { + throw createRequestCanceledError(); + } + response = await handleRequest(req); + } catch (err) { + response = { ok: false, error: normalizeError(err) }; + } finally { + inFlightRequests -= 1; + if (requestIdForCleanup) { + activeRequestIds.delete(requestIdForCleanup); + clearRequestCanceled(requestIdForCleanup); + } + } + if (!socket.destroyed) { + socket.write(`${JSON.stringify(response)}\n`); + } + idx = buffer.indexOf('\n'); + } + }); + }); +} + +export function listenNetServer(server: net.Server): Promise { + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + server.off('error', reject); + const address = server.address(); + if (typeof address === 'object' && address?.port) { + resolve(address.port); + return; + } + reject(new AppError('COMMAND_FAILED', 'Failed to bind socket server')); + }); + }); +} + +export function listenHttpServer(server: HttpServer): Promise { + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + server.off('error', reject); + const address = server.address(); + if (typeof address === 'object' && address?.port) { + resolve(address.port); + return; + } + reject(new AppError('COMMAND_FAILED', 'Failed to bind HTTP server')); + }); + }); +}