/** * Environment-scoped RPC over the worker's existing long-poll channel. * * The new-session dialog needs to browse directories on a daemon machine * before any session exists, so there is no session control channel to use. * The daemon already long-polls /v1/environments/:id/work; we enqueue a * non-session work item, the worker answers over HTTP with the requestId, * and this module resolves the waiting Web request. * * Only workers that advertise `capabilities.fs_browse` are eligible — * otherwise the request would sit until timeout on an older daemon. */ import { randomUUID } from 'node:crypto' import { storeGetEnvironment, storeUpdateWorkItem } from '../store' import { createRpcWorkItem } from './work-dispatch' /** Default time budget for a round trip. The poll channel is already in * flight most of the time (the server long-polls), but a worker sleeping * between polls can add its interval. */ export const ENVIRONMENT_RPC_TIMEOUT_MS = 15_000 export type EnvironmentRpcErrorCode = | 'unsupported' | 'offline' | 'timeout' | 'failed' export class EnvironmentRpcError extends Error { readonly code: EnvironmentRpcErrorCode constructor(message: string, code: EnvironmentRpcErrorCode = 'failed') { super(message) this.name = 'EnvironmentRpcError' this.code = code } } export interface DirectoryEntry { name: string path: string } export interface DirectoryListing { path: string parent: string | null entries: DirectoryEntry[] truncated: boolean } type PendingRpc = { environmentId: string workId: string resolve: (value: DirectoryListing) => void reject: (error: Error) => void timer: ReturnType } const pendingRpcs = new Map() /** True when the machine's worker can serve directory listings. */ export function supportsDirectoryBrowse( capabilities: Record | null | undefined, ): boolean { return capabilities?.fs_browse === true } function normalizeListing(payload: unknown): DirectoryListing { if (!payload || typeof payload !== 'object') { throw new EnvironmentRpcError('Invalid directory listing response') } const record = payload as Record if (typeof record.path !== 'string' || !Array.isArray(record.entries)) { throw new EnvironmentRpcError('Invalid directory listing response') } const entries: DirectoryEntry[] = [] for (const raw of record.entries) { if (!raw || typeof raw !== 'object') continue const entry = raw as Record if (typeof entry.name !== 'string' || typeof entry.path !== 'string') { continue } entries.push({ name: entry.name, path: entry.path }) } return { path: record.path, parent: typeof record.parent === 'string' ? record.parent : null, entries, truncated: record.truncated === true, } } /** * Ask the worker to list `path`. An empty path means "the worker's home * directory"; the worker is the authority on the filesystem. */ export async function requestDirectoryListing( environmentId: string, path: string, timeoutMs: number = ENVIRONMENT_RPC_TIMEOUT_MS, ): Promise { const env = storeGetEnvironment(environmentId) if (!env) { throw new EnvironmentRpcError('Environment not found', 'offline') } if (env.status !== 'active') { throw new EnvironmentRpcError('Machine is offline', 'offline') } if (!supportsDirectoryBrowse(env.capabilities)) { throw new EnvironmentRpcError( 'This machine does not support directory browsing', 'unsupported', ) } const requestId = `rpc_${randomUUID().replace(/-/g, '')}` let workId: string try { workId = await createRpcWorkItem(environmentId, requestId, 'list_dir', { path, }) } catch (err) { throw new EnvironmentRpcError( err instanceof Error ? err.message : 'Failed to queue directory request', ) } return await new Promise((resolve, reject) => { const timer = setTimeout(() => { pendingRpcs.delete(requestId) // Drop the undispatched work item so a later reconnection does not // replay a request whose Web caller already gave up. storeUpdateWorkItem(workId, { state: 'completed' }) reject( new EnvironmentRpcError( 'The machine did not respond in time', 'timeout', ), ) }, timeoutMs) // Don't keep the process alive solely for an RPC timeout. timer.unref?.() pendingRpcs.set(requestId, { environmentId, workId, resolve, reject, timer, }) }) } /** * Worker→server receipt. Returns false when the request is unknown, * already settled, or belongs to another environment (late responses * after a timeout are dropped silently). */ export function settleEnvironmentRpc( environmentId: string, requestId: string, payload: unknown, ): boolean { const pending = pendingRpcs.get(requestId) if (!pending || pending.environmentId !== environmentId) return false pendingRpcs.delete(requestId) clearTimeout(pending.timer) // Release the work item even if the worker's stopWork request is lost. storeUpdateWorkItem(pending.workId, { state: 'completed' }) try { const response = payload as Record if (typeof response?.error === 'string' && response.error.length > 0) { pending.reject(new EnvironmentRpcError(response.error)) } else { pending.resolve(normalizeListing(payload)) } } catch (err) { pending.reject( err instanceof Error ? err : new EnvironmentRpcError('RPC failed'), ) } return true } /** Test hook — drop all waiters without resolving. */ export function resetEnvironmentRpcsForTests(): void { for (const pending of pendingRpcs.values()) clearTimeout(pending.timer) pendingRpcs.clear() }