@workerdeck/react 0.7.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/transcript.ts","../src/use-session.ts","../src/tool-host.ts","../src/use-tool-host.ts"],"sourcesContent":["import type {\n ContentBlock,\n ContextUsage,\n ModelOption,\n PermissionMode,\n PermissionRequest,\n ProfileEngine,\n RateLimitInfo,\n SessionEvent,\n SessionInfo,\n SessionStatus,\n SlashCommandInfo,\n ToolExecutionBackend,\n ToolExecutionOutput,\n ToolResultBlock,\n} from '@workerdeck/protocol'\n\n/**\n * Pure transcript state machine over the wire-protocol event stream. Framework-free\n * so it can be unit-tested and reused outside React.\n */\n\nexport type TranscriptItem =\n | { kind: 'user'; id: string; text: string }\n | {\n kind: 'assistant_text'\n id: string\n text: string\n streaming: boolean\n parentToolUseId: string | null\n }\n | { kind: 'thinking'; id: string; text: string; parentToolUseId: string | null }\n | {\n kind: 'tool_call'\n id: string\n name: string\n input: unknown\n parentToolUseId: string | null\n /**\n * - `running` — the model called it; execution has not been reported\n * - `pending` — dispatched to an executor (bridged to this client, queued)\n * - `deferred` — parked beyond this turn; may outlive the session's liveness\n * - `settled` / `failed` — terminal\n *\n * Derive UI from this, not from `result` being present: a pending or\n * deferred call has no result yet and is not the same as a running one.\n */\n status: 'running' | 'pending' | 'deferred' | 'settled' | 'failed'\n result?: { text: string; isError: boolean }\n /** Correlation id when this call is executed outside the model loop. */\n executionId?: string\n /** Which backend is executing it, when known. */\n backend?: ToolExecutionBackend\n /** Logs captured by the executor (guest console output). */\n logs?: string[]\n }\n | {\n kind: 'turn_result'\n id: string\n subtype: string\n isError: boolean\n durationMs: number\n totalCostUsd: number\n errors?: string[]\n }\n | { kind: 'notice'; id: string; level: 'info' | 'error'; text: string }\n /** The agent handed over a session file (`file_delivered`). Render a download\n * card; the file is served by GET /sessions/:id/files/<path> while the\n * session lives. */\n | { kind: 'file_delivered'; id: string; path: string; bytes: number; description?: string }\n\nexport type TranscriptState = {\n status: SessionStatus\n statusDetail?: string\n model?: string\n cwd?: string\n sdkSessionId?: string\n /** Engine running the session, from the attach snapshot. Gates CLI-only\n * affordances; absent (an older server) reads as 'claude'. */\n engine?: ProfileEngine\n /** Models the session can switch to (from the `capabilities` event). */\n models?: ModelOption[]\n /** Slash commands the CLI accepts (from the `capabilities` event). */\n commands?: SlashCommandInfo[]\n /** Seeded from `system_init`, updated on `permission_mode_changed`. */\n permissionMode?: PermissionMode\n /** Latest context-window snapshot; absent until the first turn completes. */\n contextUsage?: ContextUsage\n /** Latest rate-limit snapshot per window ('five_hour', 'seven_day', ...).\n * Absent for API-key sessions — render nothing, not 0%. */\n rateLimits?: Record<string, RateLimitInfo>\n items: TranscriptItem[]\n pendingApprovals: PermissionRequest[]\n totalCostUsd: number\n lastSeq: number\n}\n\nexport const initialTranscriptState: TranscriptState = {\n status: 'starting',\n items: [],\n pendingApprovals: [],\n totalCostUsd: 0,\n lastSeq: 0,\n}\n\nconst STREAMING_ID = 'streaming'\nconst STREAMING_THINKING_ID = 'streaming-thinking'\n\nfunction blockText(content: ToolResultBlock['content']): string {\n if (content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction contentToBlocks(content: string | ContentBlock[]): ContentBlock[] {\n return typeof content === 'string' ? [{ type: 'text', text: content }] : content\n}\n\n/** Render an execution's by-value output for the transcript. */\nfunction outputText(output: ToolExecutionOutput): string {\n if (output.type === 'text') return output.value\n try {\n return JSON.stringify(output.value)\n } catch {\n return String(output.value)\n }\n}\n\n/** CLI-side command output arrives as user text wrapped in local-command tags. */\nconst LOCAL_COMMAND_OUTPUT = /^<local-command-(stdout|stderr)>([\\s\\S]*?)<\\/local-command-\\1>$/\n\nfunction upsert(items: TranscriptItem[], item: TranscriptItem): TranscriptItem[] {\n const index = items.findIndex((existing) => existing.id === item.id && existing.kind === item.kind)\n if (index === -1) return [...items, item]\n const next = [...items]\n next[index] = item\n return next\n}\n\n/**\n * Seed transcript state from the attach snapshot (the `attached` frame's SessionInfo).\n * A promptless session emits no `system_init` until its first message, so fields like\n * `permissionMode` and `model` would otherwise stay empty — fill only what events\n * haven't set yet; the event stream stays authoritative.\n */\nexport function seedFromSessionInfo(state: TranscriptState, info: SessionInfo): TranscriptState {\n return {\n ...state,\n // Before any event has arrived, the snapshot status is fresher than 'starting'.\n status: state.lastSeq === 0 ? info.status : state.status,\n model: state.model ?? info.model,\n permissionMode: state.permissionMode ?? info.permissionMode,\n cwd: state.cwd ?? info.cwd,\n sdkSessionId: state.sdkSessionId ?? info.sdkSessionId,\n // Never changes for a live session, and no event carries it — the snapshot is\n // the only source, so take it whenever it is present.\n engine: info.engine ?? state.engine,\n }\n}\n\nexport function applyEvent(state: TranscriptState, event: SessionEvent): TranscriptState {\n if (event.seq <= state.lastSeq) return state\n const base: TranscriptState = { ...state, lastSeq: event.seq }\n\n switch (event.type) {\n case 'system_init':\n return {\n ...base,\n model: event.model,\n cwd: event.cwd,\n sdkSessionId: event.sdkSessionId,\n permissionMode: event.permissionMode,\n }\n\n case 'status_changed':\n return { ...base, status: event.status, statusDetail: event.detail }\n\n case 'capabilities':\n return { ...base, models: event.models, commands: event.commands }\n\n case 'model_changed':\n // undefined = reset to the server default; keep showing the last known model.\n return event.model === undefined ? base : { ...base, model: event.model }\n\n case 'permission_mode_changed':\n return { ...base, permissionMode: event.mode }\n\n case 'context_usage':\n return { ...base, contextUsage: event.usage }\n\n case 'rate_limit': {\n // Keyed by window so five_hour and seven_day updates don't clobber each other.\n const key = event.info.rateLimitType\n if (!key) return base\n return { ...base, rateLimits: { ...base.rateLimits, [key]: event.info } }\n }\n\n case 'user_message': {\n let items = base.items\n for (const block of contentToBlocks(event.message.content)) {\n if (block.type === 'tool_result') {\n const toolResult = block as ToolResultBlock\n const isError = toolResult.is_error === true\n items = items.map((item) =>\n item.kind === 'tool_call' && item.id === toolResult.tool_use_id\n ? {\n ...item,\n status: isError ? 'failed' : 'settled',\n result: { text: blockText(toolResult.content), isError },\n }\n : item,\n )\n } else if (block.type === 'text' && !event.synthetic) {\n const text = (block as { text: string }).text\n const localOutput = LOCAL_COMMAND_OUTPUT.exec(text.trim())\n if (localOutput) {\n items = upsert(items, {\n kind: 'notice',\n id: event.uuid ?? `user-${event.seq}`,\n level: localOutput[1] === 'stderr' ? 'error' : 'info',\n text: localOutput[2].trim(),\n })\n } else {\n items = upsert(items, {\n kind: 'user',\n id: event.uuid ?? `user-${event.seq}`,\n text,\n })\n }\n }\n }\n return { ...base, items }\n }\n\n case 'assistant_message': {\n // Encrypted thinking arrives as a signature-only block on the final message: `thinking`\n // is '' and the human-readable summary, when the model surfaces one at all, exists only\n // in the thinking_delta stream. Carry the streamed text over rather than let the full\n // message overwrite it with nothing.\n let streamedThinking =\n base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'thinking' }> =>\n item.kind === 'thinking' && item.id === STREAMING_THINKING_ID,\n )?.text ?? ''\n // The full message supersedes any in-flight streamed text/thinking.\n let items = base.items.filter(\n (item) =>\n !(item.kind === 'assistant_text' && item.id === STREAMING_ID) &&\n !(item.kind === 'thinking' && item.id === STREAMING_THINKING_ID),\n )\n const blocks = contentToBlocks(event.message.content)\n blocks.forEach((block, index) => {\n const id = `${event.uuid}-${index}`\n if (block.type === 'text') {\n items = upsert(items, {\n kind: 'assistant_text',\n id,\n text: (block as { text: string }).text,\n streaming: false,\n parentToolUseId: event.parentToolUseId,\n })\n } else if (block.type === 'thinking') {\n const text = (block as { thinking: string }).thinking || streamedThinking\n // One streamed thought backfills at most one block, so a multi-block message\n // doesn't repeat it.\n streamedThinking = ''\n // No summary anywhere: drop the block instead of leaving a \"Thought process\" row\n // that expands to nothing (and, across consecutive messages, stacks up).\n if (text.trim() === '') return\n items = upsert(items, {\n kind: 'thinking',\n id,\n text,\n parentToolUseId: event.parentToolUseId,\n })\n } else if (block.type === 'tool_use') {\n const toolUse = block as { id: string; name: string; input: unknown }\n items = upsert(items, {\n kind: 'tool_call',\n id: toolUse.id,\n name: toolUse.name,\n input: toolUse.input,\n parentToolUseId: event.parentToolUseId,\n status: 'running',\n })\n }\n })\n return { ...base, items }\n }\n\n case 'stream_delta': {\n const delta = event.event as {\n type: string\n delta?: { type?: string; text?: string; thinking?: string }\n }\n if (delta.type !== 'content_block_delta') return base\n if (delta.delta?.type === 'text_delta') {\n const existing = base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'assistant_text' }> =>\n item.kind === 'assistant_text' && item.id === STREAMING_ID,\n )\n const item: TranscriptItem = {\n kind: 'assistant_text',\n id: STREAMING_ID,\n text: (existing?.text ?? '') + (delta.delta.text ?? ''),\n streaming: true,\n parentToolUseId: event.parentToolUseId,\n }\n return { ...base, items: upsert(base.items, item) }\n }\n if (delta.delta?.type === 'thinking_delta') {\n const existing = base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'thinking' }> =>\n item.kind === 'thinking' && item.id === STREAMING_THINKING_ID,\n )\n const item: TranscriptItem = {\n kind: 'thinking',\n id: STREAMING_THINKING_ID,\n text: (existing?.text ?? '') + (delta.delta.thinking ?? ''),\n parentToolUseId: event.parentToolUseId,\n }\n return { ...base, items: upsert(base.items, item) }\n }\n return base\n }\n\n case 'turn_result':\n return {\n ...base,\n // total_cost_usd is session-cumulative on each SDK result message.\n totalCostUsd: event.totalCostUsd,\n items: [\n ...base.items,\n {\n kind: 'turn_result',\n id: `turn-${event.seq}`,\n subtype: event.subtype,\n isError: event.isError,\n durationMs: event.durationMs,\n totalCostUsd: event.totalCostUsd,\n errors: event.errors,\n },\n ],\n }\n\n case 'permission_requested':\n return { ...base, pendingApprovals: [...base.pendingApprovals, event.request] }\n\n case 'permission_resolved':\n return {\n ...base,\n pendingApprovals: base.pendingApprovals.filter((r) => r.id !== event.requestId),\n }\n\n // Execution lifecycle for tool calls that run outside the model loop\n // (bridged to this client, queued, or deferred). Keyed by executionId, which\n // equals the tool_use id for calls the model made. Events for an unknown id\n // are ignored rather than fabricating an item: the tool_use that explains it\n // may simply not have arrived (or belongs to another session).\n case 'execution_dispatched':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: event.deferred ? 'deferred' : 'pending',\n executionId: event.executionId,\n backend: event.backend,\n }\n : item,\n ),\n }\n\n case 'execution_result':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: 'settled',\n executionId: event.executionId,\n result: { text: outputText(event.output), isError: false },\n logs: event.logs ?? item.logs,\n }\n : item,\n ),\n }\n\n case 'execution_failed':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: 'failed',\n executionId: event.executionId,\n result: { text: `${event.reason}: ${event.error}`, isError: true },\n logs: event.logs ?? item.logs,\n }\n : item,\n ),\n }\n\n case 'file_delivered':\n return {\n ...base,\n items: [\n ...base.items,\n {\n kind: 'file_delivered',\n id: `file-${event.seq}`,\n path: event.path,\n bytes: event.bytes,\n description: event.description,\n },\n ],\n }\n\n case 'session_error':\n return {\n ...base,\n items: [\n ...base.items,\n { kind: 'notice', id: `err-${event.seq}`, level: 'error', text: event.message },\n ],\n }\n\n case 'session_closed':\n return {\n ...base,\n items: [\n ...base.items,\n {\n kind: 'notice',\n id: `closed-${event.seq}`,\n level: 'info',\n text: `Session closed (${event.reason})`,\n },\n ],\n }\n\n case 'sdk_event':\n default:\n return base\n }\n}\n","import { useEffect, useMemo, useReducer, useRef, useState } from 'react'\nimport type { WorkerDeckClient, SessionHandle } from '@workerdeck/client'\nimport type { AttachedFrame, PermissionMode, SessionEvent } from '@workerdeck/protocol'\nimport {\n applyEvent,\n initialTranscriptState,\n seedFromSessionInfo,\n type TranscriptState,\n} from './transcript.ts'\n\n/** Session events drive the reducer; the attach snapshot seeds fields (permission\n * mode, model) that a promptless session's event stream doesn't carry yet. */\nfunction reduce(state: TranscriptState, action: SessionEvent | AttachedFrame): TranscriptState {\n return action.type === 'attached'\n ? seedFromSessionInfo(state, action.session)\n : applyEvent(state, action)\n}\n\nexport type UseClaudeSessionOptions = {\n /** Called when the server rejects a command with a protocol_error frame — e.g. a\n * permission-mode switch the CLI refuses. Without a handler these are dropped\n * silently and the UI looks like \"nothing happened\". */\n onProtocolError?: (message: string) => void\n}\n\nexport type UseClaudeSessionResult = {\n state: TranscriptState\n connected: boolean\n /** The live attach handle, for wiring companions that must ride the SAME\n * socket — e.g. useToolCallHost: the bridge asks the first attached client,\n * so a host on a second handle would never see the requests. Undefined until\n * attached and after unmount. */\n handle: SessionHandle | undefined\n send: (text: string) => void\n approve: (requestId: string, updatedInput?: Record<string, unknown>) => void\n deny: (requestId: string, message?: string) => void\n interrupt: () => void\n setPermissionMode: (mode: PermissionMode) => void\n setModel: (model?: string) => void\n closeSession: () => void\n}\n\n/** Attach to a session and maintain live transcript state. Detaches on unmount. */\nexport function useClaudeSession(\n client: WorkerDeckClient,\n sessionId: string | undefined,\n options?: UseClaudeSessionOptions,\n): UseClaudeSessionResult {\n const [state, dispatch] = useReducer(reduce, initialTranscriptState)\n const [connected, setConnected] = useState(false)\n // Ref for the stable callbacks below; state so consumers of `handle` re-render\n // when the socket opens or the session switches.\n const [handleState, setHandleState] = useState<SessionHandle | undefined>()\n const handleRef = useRef<SessionHandle | null>(null)\n // Ref'd so a new inline callback doesn't tear down and reopen the socket.\n const onProtocolErrorRef = useRef(options?.onProtocolError)\n onProtocolErrorRef.current = options?.onProtocolError\n\n useEffect(() => {\n if (!sessionId) return\n const handle = client.attach(sessionId)\n handleRef.current = handle\n setHandleState(handle)\n const offEvent = handle.on('event', (event: SessionEvent) => dispatch(event))\n const offAttached = handle.on('attached', (frame: AttachedFrame) => dispatch(frame))\n const offConn = handle.on('connectionChange', setConnected)\n const offProtocolError = handle.on('protocolError', (message: string) => {\n onProtocolErrorRef.current?.(message)\n })\n return () => {\n offEvent()\n offAttached()\n offConn()\n offProtocolError()\n handle.detach()\n handleRef.current = null\n setHandleState(undefined)\n }\n }, [client, sessionId])\n\n return useMemo(\n () => ({\n state,\n connected,\n handle: handleState,\n send: (text) => handleRef.current?.send(text),\n approve: (requestId, updatedInput) => handleRef.current?.approve(requestId, updatedInput),\n deny: (requestId, message) => handleRef.current?.deny(requestId, message),\n interrupt: () => handleRef.current?.interrupt(),\n setPermissionMode: (mode) => handleRef.current?.setPermissionMode(mode),\n setModel: (model) => handleRef.current?.setModel(model),\n closeSession: () => handleRef.current?.closeSession(),\n }),\n [state, connected, handleState],\n )\n}\n","import type { SessionHandle } from '@workerdeck/client'\nimport type { RunScriptResult, SandboxEngine, SandboxVfs } from '@workerdeck/sandbox'\nimport type { ToolCallRequestFrame } from '@workerdeck/protocol'\n\n/** What the host was asked to do and how it went (for UI/telemetry). */\nexport type ToolHostExecution = {\n executionId: string\n toolName: string\n status: 'running' | 'settled' | 'failed' | 'canceled'\n reason?: string\n startedAt: number\n endedAt?: number\n}\n\nexport type ToolHostRunner = (request: {\n script: string\n vfs: SandboxVfs\n timeoutMs: number\n memoryLimitBytes: number\n signal: AbortSignal\n}) => Promise<RunScriptResult>\n\nexport type ToolCallHostOptions = {\n /** Tools this client will execute. Anything else is refused, so a server can\n * never talk this tab into running something it didn't opt into.\n * Default: `['eval_script']`. */\n tools?: string[]\n /** Guest wall-clock limit, unless the request asks for less. Default 5000. */\n timeoutMs?: number\n /** Guest allocator cap, unless the request asks for less. Default 64 MiB. */\n memoryLimitBytes?: number\n /**\n * Load the WASM guest engine. Called at most once, on the first bridged call\n * — nothing is downloaded or parsed until a session actually bridges one.\n * Defaults to `@workerdeck/sandbox` with the single-file browser build.\n */\n loadEngine?: () => Promise<SandboxEngine>\n /**\n * Run the script. Defaults to executing on this thread, which is fine for the\n * short, time-boxed evaluations this is built for. Supply your own (a Web\n * Worker running the same engine) to keep long evaluations off the UI thread\n * — the guest deadline preempts the interpreter, but only between bytecode\n * ops on whichever thread it runs on.\n */\n execute?: ToolHostRunner\n /** Host-gated fetch for the guest. Omitted = the guest has no network at all. */\n fetchText?: (url: string) => Promise<string>\n /** Observe executions (rendering, logging). */\n onExecution?: (execution: ToolHostExecution) => void\n}\n\n/**\n * Answers server-bridged tool calls by executing them in this browser tab.\n * Framework-free — {@link useToolCallHost} is a thin React wrapper.\n *\n * The point is data locality: documents fetched or held client-side can be\n * evaluated here and never touch the server. The engine loads lazily, so a page\n * that never bridges a call never pays for the WASM guest.\n */\nexport function createToolCallHost(\n handle: SessionHandle,\n options: ToolCallHostOptions = {},\n): { dispose: () => void } {\n const inFlight = new Map<string, AbortController>()\n let enginePromise: Promise<SandboxEngine> | undefined\n let disposed = false\n\n const track = (execution: ToolHostExecution) => options.onExecution?.(execution)\n\n const refuse = (frame: ToolCallRequestFrame, reason: string, error: string, startedAt: number) => {\n handle.sendToolCallError(frame.executionId, reason, error)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'failed',\n reason,\n startedAt,\n endedAt: Date.now(),\n })\n }\n\n const run = async (frame: ToolCallRequestFrame): Promise<void> => {\n const startedAt = Date.now()\n const allowed = options.tools ?? ['eval_script']\n if (!allowed.includes(frame.toolName)) {\n refuse(frame, 'unsupported_tool', `this client does not execute '${frame.toolName}'`, startedAt)\n return\n }\n const script = (frame.input as { script?: unknown } | undefined)?.script\n if (typeof script !== 'string') {\n refuse(frame, 'invalid_input', 'expected a string `script` input', startedAt)\n return\n }\n\n const controller = new AbortController()\n inFlight.set(frame.executionId, controller)\n track({ executionId: frame.executionId, toolName: frame.toolName, status: 'running', startedAt })\n\n try {\n const sandbox = await import('@workerdeck/sandbox')\n const vfs = sandbox.createVfs(frame.vfsSeed)\n // Never exceed what the server asked for: it owns the deadline it will\n // give up at, and answering after that is wasted work.\n const timeoutMs = Math.min(\n frame.limits?.timeoutMs ?? Number.POSITIVE_INFINITY,\n options.timeoutMs ?? 5000,\n )\n const memoryLimitBytes = Math.min(\n frame.limits?.memoryLimitBytes ?? Number.POSITIVE_INFINITY,\n options.memoryLimitBytes ?? 64 * 1024 * 1024,\n )\n\n const result = options.execute\n ? await options.execute({ script, vfs, timeoutMs, memoryLimitBytes, signal: controller.signal })\n : await (async () => {\n enginePromise ??= (options.loadEngine ?? defaultLoadEngine)()\n return sandbox.runScript(await enginePromise, {\n script,\n vfs,\n timeoutMs,\n memoryLimitBytes,\n signal: controller.signal,\n fetchText: options.fetchText,\n })\n })()\n\n // Cancelled or torn down while we worked: the server is no longer waiting.\n if (disposed || !inFlight.has(frame.executionId)) return\n const logs = result.logs.map((l) => `[${l.level}] ${l.text}`)\n if (result.ok) {\n handle.sendToolCallResult(frame.executionId, { type: 'json', value: result.value }, logs)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'settled',\n startedAt,\n endedAt: Date.now(),\n })\n } else {\n handle.sendToolCallError(frame.executionId, result.reason, result.error, logs)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'failed',\n reason: result.reason,\n startedAt,\n endedAt: Date.now(),\n })\n }\n } catch (error) {\n if (disposed || !inFlight.has(frame.executionId)) return\n // Engine load failures land here — tell the server so the agent can adapt\n // instead of waiting out the deadline.\n refuse(frame, 'host_error', error instanceof Error ? error.message : String(error), startedAt)\n } finally {\n inFlight.delete(frame.executionId)\n }\n }\n\n const offRequest = handle.on('toolCallRequest', (frame) => void run(frame))\n const offCancel = handle.on('toolCallCanceled', ({ executionId, reason }) => {\n const controller = inFlight.get(executionId)\n if (!controller) return\n controller.abort()\n inFlight.delete(executionId)\n track({\n executionId,\n toolName: '',\n status: 'canceled',\n reason,\n startedAt: Date.now(),\n endedAt: Date.now(),\n })\n })\n\n return {\n dispose: () => {\n disposed = true\n offRequest()\n offCancel()\n for (const controller of inFlight.values()) controller.abort()\n inFlight.clear()\n },\n }\n}\n\n/** The single-file browser build keeps this to one lazy chunk — no separate\n * .wasm fetch, and nothing at all until the first bridged call. */\nasync function defaultLoadEngine(): Promise<SandboxEngine> {\n const [sandbox, variant] = await Promise.all([\n import('@workerdeck/sandbox'),\n import('@jitl/quickjs-singlefile-browser-release-asyncify'),\n ])\n return sandbox.loadEngine(variant as never)\n}\n","import { useEffect, useRef, useState } from 'react'\nimport type { SessionHandle } from '@workerdeck/client'\nimport {\n createToolCallHost,\n type ToolCallHostOptions,\n type ToolHostExecution,\n} from './tool-host.ts'\n\nexport type UseToolCallHostOptions = ToolCallHostOptions & {\n /** Turn the host off without unmounting. Default true. */\n enabled?: boolean\n /** How many recent executions to keep for rendering. Default 50. */\n historyLimit?: number\n}\n\n/**\n * React wrapper around {@link createToolCallHost}: subscribes while mounted and\n * exposes recent executions for rendering. All the logic lives in the\n * framework-free host — this only manages the subscription's lifetime.\n */\nexport function useToolCallHost(\n handle: SessionHandle | undefined,\n options: UseToolCallHostOptions = {},\n): { executions: ToolHostExecution[] } {\n const [executions, setExecutions] = useState<ToolHostExecution[]>([])\n // Read options at call time so re-renders never tear down the subscription.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n useEffect(() => {\n if (!handle || options.enabled === false) return\n const host = createToolCallHost(handle, {\n // Delegate every option through the ref, so a caller passing inline\n // objects/closures (the common case) doesn't resubscribe each render.\n get tools() {\n return optionsRef.current.tools\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs\n },\n get memoryLimitBytes() {\n return optionsRef.current.memoryLimitBytes\n },\n get loadEngine() {\n return optionsRef.current.loadEngine\n },\n get execute() {\n return optionsRef.current.execute\n },\n get fetchText() {\n return optionsRef.current.fetchText\n },\n onExecution: (execution) => {\n optionsRef.current.onExecution?.(execution)\n const limit = optionsRef.current.historyLimit ?? 50\n setExecutions((prev) => [\n ...prev.filter((e) => e.executionId !== execution.executionId),\n execution,\n ].slice(-limit))\n },\n })\n return () => host.dispose()\n }, [handle, options.enabled])\n\n return { executions }\n}\n"],"mappings":";;AAiGA,MAAa,yBAA0C;CACrD,QAAQ;CACR,OAAO,EAAE;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MAAM,CAAC,SAAS,WAAW,MAAM,QAAQ,IAAI,CAC3C,OAAO,wBACP,OAAO,qDACR,CAAC;AACF,QAAO,QAAQ,WAAW,QAAiB;;;;;;;;;AC7K7C,SAAgB,gBACd,QACA,UAAkC,EAAE,EACC;CACrC,MAAM,CAAC,YAAY,iBAAiB,SAA8B,EAAE,CAAC;CAErE,MAAM,aAAa,OAAO,QAAQ;AAClC,YAAW,UAAU;AAErB,iBAAgB;AACd,MAAI,CAAC,UAAU,QAAQ,YAAY,MAAO;EAC1C,MAAM,OAAO,mBAAmB,QAAQ;GAGtC,IAAI,QAAQ;AACV,WAAO,WAAW,QAAQ;;GAE5B,IAAI,YAAY;AACd,WAAO,WAAW,QAAQ;;GAE5B,IAAI,mBAAmB;AACrB,WAAO,WAAW,QAAQ;;GAE5B,IAAI,aAAa;AACf,WAAO,WAAW,QAAQ;;GAE5B,IAAI,UAAU;AACZ,WAAO,WAAW,QAAQ;;GAE5B,IAAI,YAAY;AACd,WAAO,WAAW,QAAQ;;GAE5B,cAAc,cAAc;AAC1B,eAAW,QAAQ,cAAc,UAAU;IAC3C,MAAM,QAAQ,WAAW,QAAQ,gBAAgB;AACjD,mBAAe,SAAS,CACtB,GAAG,KAAK,QAAQ,MAAM,EAAE,gBAAgB,UAAU,YAAY,EAC9D,UACD,CAAC,MAAM,CAAC,MAAM,CAAC;;GAEnB,CAAC;AACF,eAAa,KAAK,SAAS;IAC1B,CAAC,QAAQ,QAAQ,QAAQ,CAAC;AAE7B,QAAO,EAAE,YAAY"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/transcript.ts","../src/use-session.ts","../src/use-attachments.ts","../src/prompt-tokens.ts","../src/host-tree.ts","../src/use-host-files.ts","../src/use-session-info.ts","../src/open-files.ts","../src/use-open-files.ts","../src/tool-host.ts","../src/use-tool-host.ts","../src/recap.ts"],"sourcesContent":["import { ENGINE_CAPABILITIES } from '@workerdeck/protocol'\nimport type {\n ContentBlock,\n ContextUsage,\n EngineCapabilities,\n MessageAttachment,\n ModelOption,\n PermissionMode,\n PermissionRequest,\n ProfileEngine,\n RateLimitInfo,\n SessionEvent,\n SessionInfo,\n SessionStatus,\n SkillInfo,\n SlashCommandInfo,\n ToolExecutionBackend,\n ToolExecutionOutput,\n ToolResultBlock,\n} from '@workerdeck/protocol'\n\n/**\n * Pure transcript state machine over the wire-protocol event stream. Framework-free\n * so it can be unit-tested and reused outside React.\n */\n\nexport type TranscriptItem =\n | { kind: 'user'; id: string; text: string; attachments?: MessageAttachment[] }\n | {\n kind: 'assistant_text'\n id: string\n text: string\n streaming: boolean\n parentToolUseId: string | null\n }\n | { kind: 'thinking'; id: string; text: string; parentToolUseId: string | null }\n | {\n kind: 'tool_call'\n id: string\n name: string\n input: unknown\n parentToolUseId: string | null\n /**\n * - `running` — the model called it; execution has not been reported\n * - `pending` — dispatched to an executor (bridged to this client, queued)\n * - `deferred` — parked beyond this turn; may outlive the session's liveness\n * - `settled` / `failed` — terminal\n *\n * Derive UI from this, not from `result` being present: a pending or\n * deferred call has no result yet and is not the same as a running one.\n */\n status: 'running' | 'pending' | 'deferred' | 'settled' | 'failed'\n result?: { text: string; isError: boolean }\n /** Correlation id when this call is executed outside the model loop. */\n executionId?: string\n /** Which backend is executing it, when known. */\n backend?: ToolExecutionBackend\n /** Logs captured by the executor (guest console output). */\n logs?: string[]\n }\n | {\n kind: 'turn_result'\n id: string\n subtype: string\n isError: boolean\n durationMs: number\n totalCostUsd: number\n errors?: string[]\n }\n | { kind: 'notice'; id: string; level: 'info' | 'error'; text: string }\n /** The agent handed over a session file (`file_delivered`). Render a download\n * card; the file is served by GET /sessions/:id/files/<path> while the\n * session lives. */\n | { kind: 'file_delivered'; id: string; path: string; bytes: number; description?: string }\n\n/** A `file_produced` announcement, as the transcript keeps it. */\nexport type ProducedFileRef = {\n fileId: string\n mediaType?: string\n bytes?: number\n}\n\nexport type TranscriptState = {\n status: SessionStatus\n statusDetail?: string\n model?: string\n cwd?: string\n sdkSessionId?: string\n /** Engine running the session, from the attach snapshot. Gates CLI-only\n * affordances; absent (an older server) reads as 'claude'. */\n engine?: ProfileEngine\n /**\n * What this session's engine does and does not do: the runner-reported record\n * from the attach snapshot when present, else {@link ENGINE_CAPABILITIES} for\n * the engine. Always defined, so a surface can render every affordance from it\n * rather than switching on the engine name — an absent capability means the\n * affordance is *hidden*, never a control that silently does nothing.\n */\n capabilities: EngineCapabilities\n /**\n * The most recent attach snapshot, whole. The session-level facts no event\n * carries — profile, apiKeySource, canBypassPermissions, createdAt, numTurns —\n * live only here. Unlike the fields above it is replaced on every attach: it is\n * the server's answer, not something the event stream refines.\n */\n session?: SessionInfo\n /** Models the session can switch to (from the `capabilities` event). */\n models?: ModelOption[]\n /** Slash commands the CLI accepts (from the `capabilities` event). */\n commands?: SlashCommandInfo[]\n /**\n * Skills the engine can reach (from the `skills` event), replaced whole each\n * time. Absent until the engine has enumerated them — which for codex is on\n * its first turn, since listing needs a live child. So gate the affordance on\n * *this being defined*, not on `capabilities.skillsList` alone: the flag says\n * the engine can answer, this says it has.\n *\n * Not commands, and must not be offered as such — see the protocol's\n * `SkillInfo`.\n */\n skills?: SkillInfo[]\n /**\n * Files the engine wrote on the host, keyed by the absolute path it reported\n * (from `file_produced`). A tool card holding a `savedPath` looks itself up\n * here to turn that path into a fetchable id — `client.producedFileUrl` — so\n * the picture renders without the operator having declared a host-file root.\n */\n producedFiles?: Record<string, ProducedFileRef>\n\n /** What this session's default model resolves to (from `capabilities`). Known\n * before the first turn, which `model` is not — a promptless session has no\n * `system_init` until it is spoken to. */\n defaultModel?: string\n /** Seeded from `system_init`, updated on `permission_mode_changed`. */\n permissionMode?: PermissionMode\n /** Latest context-window snapshot; absent until the first turn completes. */\n contextUsage?: ContextUsage\n /** Latest rate-limit snapshot per window ('five_hour', 'seven_day', ...).\n * Absent for API-key sessions — render nothing, not 0%. */\n rateLimits?: Record<string, RateLimitInfo>\n /**\n * When the newest window reading was *taken* (the event's `ts`), not when this\n * client received it — so a reading replayed on attach is dated honestly\n * rather than as \"just now\". Updates come one per turn at best, which makes a\n * stale reading normal and worth saying out loud.\n */\n rateLimitsUpdatedAt?: number\n /** claude.ai plan the rate-limit windows belong to ('pro', 'max', ...), from\n * `plan_info`. Absent for API-key sessions, like the windows themselves. */\n subscriptionType?: string\n items: TranscriptItem[]\n pendingApprovals: PermissionRequest[]\n totalCostUsd: number\n lastSeq: number\n}\n\nexport const initialTranscriptState: TranscriptState = {\n status: 'starting',\n // The protocol's own default for an absent `engine`, so a surface has a record\n // to render from before the first attach frame lands.\n capabilities: ENGINE_CAPABILITIES.claude,\n items: [],\n pendingApprovals: [],\n totalCostUsd: 0,\n lastSeq: 0,\n}\n\nconst STREAMING_ID = 'streaming'\nconst STREAMING_THINKING_ID = 'streaming-thinking'\n\nfunction blockText(content: ToolResultBlock['content']): string {\n if (content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .filter(Boolean)\n .join('\\n')\n}\n\nfunction contentToBlocks(content: string | ContentBlock[]): ContentBlock[] {\n return typeof content === 'string' ? [{ type: 'text', text: content }] : content\n}\n\n/** Render an execution's by-value output for the transcript. */\nfunction outputText(output: ToolExecutionOutput): string {\n if (output.type === 'text') return output.value\n try {\n return JSON.stringify(output.value)\n } catch {\n return String(output.value)\n }\n}\n\n/** CLI-side command output arrives as user text wrapped in local-command tags. */\nconst LOCAL_COMMAND_OUTPUT = /^<local-command-(stdout|stderr)>([\\s\\S]*?)<\\/local-command-\\1>$/\n\nfunction upsert(items: TranscriptItem[], item: TranscriptItem): TranscriptItem[] {\n const index = items.findIndex((existing) => existing.id === item.id && existing.kind === item.kind)\n if (index === -1) return [...items, item]\n const next = [...items]\n next[index] = item\n return next\n}\n\n/**\n * Seed transcript state from the attach snapshot (the `attached` frame's SessionInfo).\n * A promptless session emits no `system_init` until its first message, so fields like\n * `permissionMode` and `model` would otherwise stay empty — fill only what events\n * haven't set yet; the event stream stays authoritative.\n */\nexport function seedFromSessionInfo(state: TranscriptState, info: SessionInfo): TranscriptState {\n // Never changes for a live session, and no event carries it — the snapshot is\n // the only source, so take it whenever it is present.\n const engine = info.engine ?? state.engine\n return {\n ...state,\n // Before any event has arrived, the snapshot status is fresher than 'starting'.\n status: state.lastSeq === 0 ? info.status : state.status,\n model: state.model ?? info.model,\n permissionMode: state.permissionMode ?? info.permissionMode,\n cwd: state.cwd ?? info.cwd,\n sdkSessionId: state.sdkSessionId ?? info.sdkSessionId,\n engine,\n // The wire copy wins over the static default when both exist, per the\n // protocol — the runner knows what it actually wired up.\n capabilities: info.capabilities ?? ENGINE_CAPABILITIES[engine ?? 'claude'],\n session: info,\n }\n}\n\n/**\n * The session's rate-limit windows in reading order: the session window, the\n * weekly window, then whichever per-model weekly windows it reports.\n *\n * Discovered rather than hardcoded — the SDK's set of windows is an open union\n * and has grown before — but ordered, so the first two always mean the same\n * thing. A window with no `utilization` is *unknown*, not zero, and is dropped\n * entirely rather than drawn as an empty bar that reads as \"plenty left\".\n */\nexport function rateLimitWindows(\n state: TranscriptState,\n): Array<{ key: string; info: RateLimitInfo }> {\n const all = Object.entries(state.rateLimits ?? {})\n .filter(([, info]) => info.utilization !== undefined)\n .map(([key, info]) => ({ key, info }))\n const named = ['five_hour', 'seven_day'].flatMap((key) => all.filter((w) => w.key === key))\n const perModel = all\n .filter((w) => w.key.startsWith('seven_day_'))\n .sort((a, b) => a.key.localeCompare(b.key))\n return [...named, ...perModel]\n}\n\nexport function applyEvent(state: TranscriptState, event: SessionEvent): TranscriptState {\n if (event.seq <= state.lastSeq) return state\n const base: TranscriptState = { ...state, lastSeq: event.seq }\n\n switch (event.type) {\n case 'system_init':\n return {\n ...base,\n model: event.model,\n cwd: event.cwd,\n sdkSessionId: event.sdkSessionId,\n permissionMode: event.permissionMode,\n }\n\n case 'status_changed':\n return { ...base, status: event.status, statusDetail: event.detail }\n\n case 'capabilities':\n return {\n ...base,\n models: event.models,\n commands: event.commands,\n defaultModel: event.defaultModel ?? base.defaultModel,\n }\n\n case 'skills':\n // Replaced whole, never merged: the event is the engine's current answer,\n // so a skill deleted on disk has to be able to disappear from the list.\n return { ...base, skills: event.skills }\n\n case 'file_produced':\n // Keyed by PATH, not by fileId, because the lookup a card does is\n // \"here is the savedPath in my tool input — is there anything to fetch?\".\n return {\n ...base,\n producedFiles: {\n ...base.producedFiles,\n [event.path]: {\n fileId: event.fileId,\n ...(event.mediaType ? { mediaType: event.mediaType } : {}),\n ...(event.bytes !== undefined ? { bytes: event.bytes } : {}),\n },\n },\n }\n\n case 'model_changed':\n // undefined = reset to the server default; keep showing the last known model.\n return event.model === undefined ? base : { ...base, model: event.model }\n\n case 'permission_mode_changed':\n return { ...base, permissionMode: event.mode }\n\n case 'context_usage':\n return { ...base, contextUsage: event.usage }\n\n case 'rate_limit': {\n // Keyed by window so five_hour and seven_day updates don't clobber each other.\n const key = event.info.rateLimitType\n if (!key) return base\n return {\n ...base,\n rateLimits: { ...base.rateLimits, [key]: event.info },\n rateLimitsUpdatedAt: event.ts,\n }\n }\n\n case 'plan_info':\n return { ...base, subscriptionType: event.subscriptionType }\n\n case 'user_message': {\n let items = base.items\n for (const block of contentToBlocks(event.message.content)) {\n if (block.type === 'tool_result') {\n const toolResult = block as ToolResultBlock\n const isError = toolResult.is_error === true\n items = items.map((item) =>\n item.kind === 'tool_call' && item.id === toolResult.tool_use_id\n ? {\n ...item,\n status: isError ? 'failed' : 'settled',\n result: { text: blockText(toolResult.content), isError },\n }\n : item,\n )\n } else if (block.type === 'text' && !event.synthetic) {\n const text = (block as { text: string }).text\n const localOutput = LOCAL_COMMAND_OUTPUT.exec(text.trim())\n if (localOutput) {\n items = upsert(items, {\n kind: 'notice',\n id: event.uuid ?? `user-${event.seq}`,\n level: localOutput[1] === 'stderr' ? 'error' : 'info',\n text: localOutput[2].trim(),\n })\n } else {\n items = upsert(items, {\n kind: 'user',\n id: event.uuid ?? `user-${event.seq}`,\n text,\n // References, not bytes — render them by fetching\n // `/sessions/:id/attachments/:attachmentId`.\n attachments: event.attachments,\n })\n }\n }\n }\n return { ...base, items }\n }\n\n case 'assistant_message': {\n // Encrypted thinking arrives as a signature-only block on the final message: `thinking`\n // is '' and the human-readable summary, when the model surfaces one at all, exists only\n // in the thinking_delta stream. Carry the streamed text over rather than let the full\n // message overwrite it with nothing.\n let streamedThinking =\n base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'thinking' }> =>\n item.kind === 'thinking' && item.id === STREAMING_THINKING_ID,\n )?.text ?? ''\n // The full message supersedes any in-flight streamed text/thinking.\n let items = base.items.filter(\n (item) =>\n !(item.kind === 'assistant_text' && item.id === STREAMING_ID) &&\n !(item.kind === 'thinking' && item.id === STREAMING_THINKING_ID),\n )\n const blocks = contentToBlocks(event.message.content)\n blocks.forEach((block, index) => {\n const id = `${event.uuid}-${index}`\n if (block.type === 'text') {\n items = upsert(items, {\n kind: 'assistant_text',\n id,\n text: (block as { text: string }).text,\n streaming: false,\n parentToolUseId: event.parentToolUseId,\n })\n } else if (block.type === 'thinking') {\n const text = (block as { thinking: string }).thinking || streamedThinking\n // One streamed thought backfills at most one block, so a multi-block message\n // doesn't repeat it.\n streamedThinking = ''\n // No summary anywhere: drop the block instead of leaving a \"Thought process\" row\n // that expands to nothing (and, across consecutive messages, stacks up).\n if (text.trim() === '') return\n items = upsert(items, {\n kind: 'thinking',\n id,\n text,\n parentToolUseId: event.parentToolUseId,\n })\n } else if (block.type === 'tool_use') {\n const toolUse = block as { id: string; name: string; input: unknown }\n items = upsert(items, {\n kind: 'tool_call',\n id: toolUse.id,\n name: toolUse.name,\n input: toolUse.input,\n parentToolUseId: event.parentToolUseId,\n status: 'running',\n })\n }\n })\n return { ...base, items }\n }\n\n case 'stream_delta': {\n const delta = event.event as {\n type: string\n delta?: { type?: string; text?: string; thinking?: string }\n }\n if (delta.type !== 'content_block_delta') return base\n if (delta.delta?.type === 'text_delta') {\n const existing = base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'assistant_text' }> =>\n item.kind === 'assistant_text' && item.id === STREAMING_ID,\n )\n const item: TranscriptItem = {\n kind: 'assistant_text',\n id: STREAMING_ID,\n text: (existing?.text ?? '') + (delta.delta.text ?? ''),\n streaming: true,\n parentToolUseId: event.parentToolUseId,\n }\n return { ...base, items: upsert(base.items, item) }\n }\n if (delta.delta?.type === 'thinking_delta') {\n const existing = base.items.find(\n (item): item is Extract<TranscriptItem, { kind: 'thinking' }> =>\n item.kind === 'thinking' && item.id === STREAMING_THINKING_ID,\n )\n const item: TranscriptItem = {\n kind: 'thinking',\n id: STREAMING_THINKING_ID,\n text: (existing?.text ?? '') + (delta.delta.thinking ?? ''),\n parentToolUseId: event.parentToolUseId,\n }\n return { ...base, items: upsert(base.items, item) }\n }\n return base\n }\n\n case 'turn_result':\n return {\n ...base,\n // total_cost_usd is session-cumulative on each SDK result message.\n totalCostUsd: event.totalCostUsd,\n items: [\n ...base.items,\n {\n kind: 'turn_result',\n id: `turn-${event.seq}`,\n subtype: event.subtype,\n isError: event.isError,\n durationMs: event.durationMs,\n totalCostUsd: event.totalCostUsd,\n errors: event.errors,\n },\n ],\n }\n\n case 'permission_requested':\n return { ...base, pendingApprovals: [...base.pendingApprovals, event.request] }\n\n case 'permission_resolved':\n return {\n ...base,\n pendingApprovals: base.pendingApprovals.filter((r) => r.id !== event.requestId),\n }\n\n // Execution lifecycle for tool calls that run outside the model loop\n // (bridged to this client, queued, or deferred). Keyed by executionId, which\n // equals the tool_use id for calls the model made. Events for an unknown id\n // are ignored rather than fabricating an item: the tool_use that explains it\n // may simply not have arrived (or belongs to another session).\n case 'execution_dispatched':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: event.deferred ? 'deferred' : 'pending',\n executionId: event.executionId,\n backend: event.backend,\n }\n : item,\n ),\n }\n\n case 'execution_result':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: 'settled',\n executionId: event.executionId,\n result: { text: outputText(event.output), isError: false },\n logs: event.logs ?? item.logs,\n }\n : item,\n ),\n }\n\n case 'execution_failed':\n return {\n ...base,\n items: base.items.map((item) =>\n item.kind === 'tool_call' && item.id === event.executionId\n ? {\n ...item,\n status: 'failed',\n executionId: event.executionId,\n result: { text: `${event.reason}: ${event.error}`, isError: true },\n logs: event.logs ?? item.logs,\n }\n : item,\n ),\n }\n\n case 'file_delivered':\n return {\n ...base,\n items: [\n ...base.items,\n {\n kind: 'file_delivered',\n id: `file-${event.seq}`,\n path: event.path,\n bytes: event.bytes,\n description: event.description,\n },\n ],\n }\n\n case 'session_error':\n return {\n ...base,\n items: [\n ...base.items,\n { kind: 'notice', id: `err-${event.seq}`, level: 'error', text: event.message },\n ],\n }\n\n case 'session_closed':\n return {\n ...base,\n items: [\n ...base.items,\n {\n kind: 'notice',\n id: `closed-${event.seq}`,\n level: 'info',\n text: `Session closed (${event.reason})`,\n },\n ],\n }\n\n case 'sdk_event':\n default:\n return base\n }\n}\n","import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react'\nimport type { WorkerDeckClient, SessionHandle } from '@workerdeck/client'\nimport { PROTOCOL_VERSION } from '@workerdeck/protocol'\nimport type {\n AttachedFrame,\n ModelOption,\n PermissionMode,\n SessionEvent,\n} from '@workerdeck/protocol'\nimport {\n applyEvent,\n initialTranscriptState,\n seedFromSessionInfo,\n type TranscriptState,\n} from './transcript.ts'\n\n/** Session events drive the reducer; the attach snapshot seeds fields (permission\n * mode, model) that a promptless session's event stream doesn't carry yet. */\nfunction reduce(state: TranscriptState, action: SessionEvent | AttachedFrame): TranscriptState {\n return action.type === 'attached'\n ? seedFromSessionInfo(state, action.session)\n : applyEvent(state, action)\n}\n\n/**\n * How the client is doing at reaching the gateway — deliberately not the session's\n * status. The two are orthogonal, and while the socket is down the status a client\n * holds is *stale*, so a surface that merges them must say so rather than keep\n * claiming \"idle\".\n *\n * The handle retries forever, so `offline` is a judgement about how long it has\n * been failing rather than a state the transport reports.\n */\nexport type ConnectionState = 'live' | 'reconnecting' | 'offline'\n\n/** Failed attempts in a row before \"reconnecting…\" stops being the honest word.\n * Three is ~3.5s of backoff — past a blip. Matches the iOS client. */\nconst OFFLINE_AFTER_ATTEMPTS = 3\n\nexport type UseClaudeSessionOptions = {\n /** Called when the server rejects a command with a protocol_error frame — e.g. a\n * permission-mode switch the CLI refuses. Without a handler these are dropped\n * silently and the UI looks like \"nothing happened\". */\n onProtocolError?: (message: string) => void\n}\n\nexport type UseClaudeSessionResult = {\n state: TranscriptState\n /** True while the socket is open. {@link UseClaudeSessionResult.connection}\n * carries the same fact with the \"has it been failing a while\" distinction. */\n connected: boolean\n connection: ConnectionState\n /** The server's `PROTOCOL_VERSION` when it disagrees with the one this build\n * mirrors — undefined when they match. Some events may not render. */\n protocolMismatch?: number\n /**\n * What a model picker should offer. Two sources, and which is authoritative\n * depends on the engine: the `capabilities` event is the CLI asked what it\n * supports, so for claude it wins; codex never sends one — its models are a\n * catalog shipped with the release and served on the profile — so without the\n * fallback its picker would be permanently empty and the session unswitchable.\n */\n models: ModelOption[]\n /** The model this session answers as: the one it reported, or, before it has\n * reported anything, the default it will use. */\n effectiveModel?: string\n /** The live attach handle, for wiring companions that must ride the SAME\n * socket — e.g. useToolCallHost: the bridge asks the first attached client,\n * so a host on a second handle would never see the requests. Undefined until\n * attached and after unmount. */\n handle: SessionHandle | undefined\n /** Attachment ids come from `client.uploadAttachment`, in send order. */\n send: (text: string, attachmentIds?: string[]) => void\n approve: (requestId: string, updatedInput?: Record<string, unknown>) => void\n /** `message` is fed back to the agent, which can then try something else;\n * `interrupt` also stops the turn (\"deny & stop\"). */\n deny: (requestId: string, message?: string, interrupt?: boolean) => void\n interrupt: () => void\n setPermissionMode: (mode: PermissionMode) => void\n setModel: (model?: string) => void\n closeSession: () => void\n /** Skip the reconnect backoff — what a tab returning to the foreground does. */\n reconnectNow: () => void\n}\n\n/** Attach to a session and maintain live transcript state. Detaches on unmount. */\nexport function useClaudeSession(\n client: WorkerDeckClient,\n sessionId: string | undefined,\n options?: UseClaudeSessionOptions,\n): UseClaudeSessionResult {\n const [state, dispatch] = useReducer(reduce, initialTranscriptState)\n const [connection, setConnection] = useState<ConnectionState>('reconnecting')\n const [protocolMismatch, setProtocolMismatch] = useState<number | undefined>()\n // Ref for the stable callbacks below; state so consumers of `handle` re-render\n // when the socket opens or the session switches.\n const [handleState, setHandleState] = useState<SessionHandle | undefined>()\n const handleRef = useRef<SessionHandle | null>(null)\n // Ref'd so a new inline callback doesn't tear down and reopen the socket.\n const onProtocolErrorRef = useRef(options?.onProtocolError)\n onProtocolErrorRef.current = options?.onProtocolError\n\n useEffect(() => {\n if (!sessionId) return\n const handle = client.attach(sessionId)\n handleRef.current = handle\n setHandleState(handle)\n const offEvent = handle.on('event', (event: SessionEvent) => dispatch(event))\n const offAttached = handle.on('attached', (frame: AttachedFrame) => {\n dispatch(frame)\n setProtocolMismatch(\n frame.protocolVersion === PROTOCOL_VERSION ? undefined : frame.protocolVersion,\n )\n })\n const offConn = handle.on('connectionChange', (open: boolean) =>\n setConnection(open ? 'live' : 'reconnecting'),\n )\n const offRetry = handle.on('reconnectAttempt', (attempts: number) =>\n setConnection(attempts >= OFFLINE_AFTER_ATTEMPTS ? 'offline' : 'reconnecting'),\n )\n const offProtocolError = handle.on('protocolError', (message: string) => {\n onProtocolErrorRef.current?.(message)\n })\n return () => {\n offEvent()\n offAttached()\n offConn()\n offRetry()\n offProtocolError()\n handle.detach()\n handleRef.current = null\n setHandleState(undefined)\n setConnection('reconnecting')\n setProtocolMismatch(undefined)\n }\n }, [client, sessionId])\n\n const models = useProfileModelFallback(client, sessionId, state)\n\n const connected = connection === 'live'\n const reconnectNow = useCallback(() => handleRef.current?.reconnectNow(), [])\n\n return useMemo(\n () => ({\n state,\n connected,\n connection,\n protocolMismatch,\n models,\n effectiveModel: state.model ?? state.defaultModel,\n handle: handleState,\n send: (text, attachmentIds) => handleRef.current?.send(text, attachmentIds),\n approve: (requestId, updatedInput) => handleRef.current?.approve(requestId, updatedInput),\n deny: (requestId, message, interrupt) =>\n handleRef.current?.deny(requestId, message, interrupt),\n interrupt: () => handleRef.current?.interrupt(),\n setPermissionMode: (mode) => handleRef.current?.setPermissionMode(mode),\n setModel: (model) => handleRef.current?.setModel(model),\n closeSession: () => handleRef.current?.closeSession(),\n reconnectNow,\n }),\n [state, connected, connection, protocolMismatch, models, handleState, reconnectNow],\n )\n}\n\n/**\n * The session's profile catalog, fetched once and only when it could matter —\n * i.e. when the engine has reported no models of its own.\n *\n * Fire-and-forget on purpose: an empty catalog is exactly the state a picker\n * already handles, so a failed or 404'd `/profiles` (a server predating them)\n * degrades to the old behaviour rather than raising an error about a list the\n * operator may never open.\n */\nfunction useProfileModelFallback(\n client: WorkerDeckClient,\n sessionId: string | undefined,\n state: TranscriptState,\n): ModelOption[] {\n const [catalog, setCatalog] = useState<ModelOption[]>([])\n const profile = state.session?.profile\n const reported = state.models\n const hasReported = !!reported?.length\n\n useEffect(() => setCatalog([]), [sessionId])\n\n useEffect(() => {\n if (!profile || hasReported) return\n let cancelled = false\n client\n .listProfiles()\n .then((response) => {\n if (!cancelled) {\n setCatalog(response.profiles.find((p) => p.name === profile)?.models ?? [])\n }\n })\n .catch(() => {\n // No catalog: the picker falls back to whatever the session reports.\n })\n return () => {\n cancelled = true\n }\n }, [client, profile, hasReported])\n\n return hasReported ? reported : catalog\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { WorkerDeckClient } from '@workerdeck/client'\nimport type { EngineCapabilities, ProfileEngine } from '@workerdeck/protocol'\n\n/**\n * Files staged for the next message.\n *\n * The upload happens as soon as something is picked, not at send time — the\n * message names attachment *ids*, so the bytes must already be the server's\n * before a turn can reference them, and the wait is spent while the user is\n * still typing rather than after they hit send. It also keeps base64 out of the\n * event log entirely, which is the protocol's rule.\n */\nexport type StagedAttachment = {\n /** Local identity, stable across a retry — the React key while uploading. */\n key: string\n name: string\n mediaType: string\n bytes: number\n /** Object URL for an image thumbnail, revoked when the item goes away. */\n previewUrl?: string\n status: 'uploading' | 'ready' | 'failed'\n /** The server's id once uploaded — what `send` names. */\n id?: string\n /** Why the upload failed, verbatim from the gateway (413, 415, …). */\n error?: string\n}\n\n/** The kind vocabulary of {@link EngineCapabilities.attachments}. */\nexport type AttachmentKind = 'image' | 'pdf' | 'text'\n\n/**\n * How a media type reaches a model, in the capability record's vocabulary.\n * `undefined` means this build can't classify it — the upload still goes,\n * because the gateway's vocabulary is the authoritative one.\n */\nexport function attachmentKind(mediaType: string): AttachmentKind | undefined {\n const type = mediaType.split(';')[0]!.trim().toLowerCase()\n if (type.startsWith('image/')) return 'image'\n if (type === 'application/pdf') return 'pdf'\n if (type.startsWith('text/')) return 'text'\n if (TEXTUAL_TYPES.has(type)) return 'text'\n return undefined\n}\n\n/** Textual types whose media type doesn't start with `text/` — mirrors core. */\nconst TEXTUAL_TYPES = new Set([\n 'application/json',\n 'application/xml',\n 'application/yaml',\n 'application/x-yaml',\n 'application/toml',\n 'application/javascript',\n 'application/typescript',\n 'application/x-sh',\n 'application/sql',\n])\n\n/** Longest edge an image is downscaled to before upload. Anthropic's own\n * recommendation, and the same number the iOS client uses — a phone photo is\n * several times this in each direction and costs tokens for nothing. */\nconst MAX_IMAGE_EDGE = 1568\n\nexport type UseAttachmentsOptions = {\n /** The session's capability record — its `attachments` list decides which\n * kinds are offered and which are refused locally. */\n capabilities: EngineCapabilities\n /** Named in a local refusal, so \"the codex engine does not take pdf\n * attachments\" says which engine meant it. */\n engine?: ProfileEngine\n}\n\nexport type UseAttachmentsResult = {\n items: StagedAttachment[]\n /** Uploaded ids in staging order — what {@link UseClaudeSessionResult.send} names. */\n readyIds: string[]\n /** An id that hasn't landed can't be named, so send waits. */\n uploading: boolean\n /** A refused file must be dealt with before the message goes. */\n hasFailure: boolean\n /** Accept attribute for a file input, narrowed to what the engine takes. */\n accept: string\n /** True when the engine takes no attachments at all — hide the affordance\n * entirely rather than offer one with no meaning. */\n disabled: boolean\n add: (files: Iterable<File>) => void\n retry: (key: string) => void\n remove: (key: string) => void\n clear: () => void\n /** A local refusal (wrong kind), surfaced once rather than silently dropped. */\n error?: string\n dismissError: () => void\n}\n\n/**\n * Stage, upload and track files for the next message of a session.\n *\n * Refusals happen as early as they can be known: a kind the capability record\n * forswears never reaches the network (the gateway would 415 it), and everything\n * else is the gateway's call — its vocabulary is authoritative, so an unknown\n * media type is uploaded rather than guessed at.\n */\nexport function useAttachments(\n client: WorkerDeckClient,\n sessionId: string | undefined,\n { capabilities, engine }: UseAttachmentsOptions,\n): UseAttachmentsResult {\n const [items, setItems] = useState<StagedAttachment[]>([])\n const [error, setError] = useState<string | undefined>()\n const counter = useRef(0)\n /** The originals, kept so a failed upload can be retried without re-picking. */\n const fileByKey = useRef(new Map<string, File>())\n /** Mirrors the live preview URLs so unmount can revoke them all — an unmount\n * with blobs outstanding is a leak the GC does not clean up. */\n const previewUrls = useRef<string[]>([])\n previewUrls.current = items.flatMap((item) => (item.previewUrl ? [item.previewUrl] : []))\n const accepts = capabilities.attachments\n\n useEffect(\n () => () => {\n for (const url of previewUrls.current) URL.revokeObjectURL(url)\n },\n [],\n )\n\n const patch = useCallback((key: string, next: Partial<StagedAttachment>) => {\n setItems((current) =>\n current.map((item) => (item.key === key ? { ...item, ...next } : item)),\n )\n }, [])\n\n const upload = useCallback(\n (key: string, file: File) => {\n if (!sessionId) return\n patch(key, { status: 'uploading', error: undefined })\n void (async () => {\n try {\n const data = await prepare(file)\n const uploaded = await client.uploadAttachment(sessionId, {\n name: file.name,\n mediaType: data.mediaType,\n data: data.body,\n })\n patch(key, { status: 'ready', id: uploaded.id, bytes: uploaded.bytes ?? file.size })\n } catch (e) {\n patch(key, { status: 'failed', error: e instanceof Error ? e.message : 'Upload failed' })\n }\n })()\n },\n [client, patch, sessionId],\n )\n\n const add = useCallback(\n (files: Iterable<File>) => {\n const staged: StagedAttachment[] = []\n const pending: Array<{ key: string; file: File }> = []\n for (const file of files) {\n const mediaType = file.type || 'application/octet-stream'\n const kind = attachmentKind(mediaType)\n // A kind this build can't classify still goes through: the gateway's\n // vocabulary is the authoritative one, and it answers with a real reason.\n if (kind && !accepts.includes(kind)) {\n setError(`The ${engine ?? 'claude'} engine does not take ${kind} attachments.`)\n continue\n }\n const key = `att-${++counter.current}`\n staged.push({\n key,\n name: file.name,\n mediaType,\n bytes: file.size,\n previewUrl: kind === 'image' ? URL.createObjectURL(file) : undefined,\n status: 'uploading',\n })\n pending.push({ key, file })\n }\n if (staged.length === 0) return\n setItems((current) => [...current, ...staged])\n fileByKey.current = new Map([\n ...fileByKey.current,\n ...pending.map(({ key, file }) => [key, file] as const),\n ])\n for (const { key, file } of pending) upload(key, file)\n },\n [accepts, engine, upload],\n )\n\n const forget = useCallback((keys: string[]) => {\n setItems((current) => {\n for (const item of current) {\n if (keys.includes(item.key) && item.previewUrl) URL.revokeObjectURL(item.previewUrl)\n }\n return current.filter((item) => !keys.includes(item.key))\n })\n for (const key of keys) fileByKey.current.delete(key)\n }, [])\n\n const remove = useCallback((key: string) => forget([key]), [forget])\n\n const clear = useCallback(() => {\n setItems((current) => {\n for (const item of current) if (item.previewUrl) URL.revokeObjectURL(item.previewUrl)\n return []\n })\n fileByKey.current.clear()\n }, [])\n\n const retry = useCallback(\n (key: string) => {\n const file = fileByKey.current.get(key)\n if (file) upload(key, file)\n },\n [upload],\n )\n\n return useMemo(\n () => ({\n items,\n readyIds: items.flatMap((item) => (item.id ? [item.id] : [])),\n uploading: items.some((item) => item.status === 'uploading'),\n hasFailure: items.some((item) => item.status === 'failed'),\n accept: acceptAttribute(accepts),\n disabled: accepts.length === 0 || !sessionId,\n add,\n retry,\n remove,\n clear,\n error,\n dismissError: () => setError(undefined),\n }),\n [items, accepts, sessionId, add, retry, remove, clear, error],\n )\n}\n\n/** What a file input should offer. The full set keeps the open door (anything —\n * the gateway refuses the rest with a clear message); a narrower record narrows\n * the browsing too, so most refusals never happen. */\nfunction acceptAttribute(kinds: readonly AttachmentKind[]): string {\n if (kinds.length === 0) return ''\n const parts: string[] = []\n if (kinds.includes('image')) parts.push('image/*')\n if (kinds.includes('pdf')) parts.push('application/pdf')\n if (kinds.includes('text')) parts.push('text/*', '.md', '.json', '.yaml', '.yml', '.toml')\n return kinds.length === 3 ? '' : parts.join(',')\n}\n\n/**\n * The two browser APIs the downscale needs, reached through `globalThis` and\n * typed structurally.\n *\n * This package compiles without the DOM lib — Node-only consumers (the smoke\n * tsconfig) pull its source in — so naming `document` or `createImageBitmap`\n * directly is a type error there. Feature-detecting them is what the code has to\n * do at runtime anyway: the downscale is an optimisation, and a host that can't\n * do it uploads the original.\n */\ntype ImageBitmapLike = { width: number; height: number; close(): void }\ntype CanvasLike = {\n width: number\n height: number\n getContext(contextId: '2d'): {\n drawImage(image: ImageBitmapLike, dx: number, dy: number, dw: number, dh: number): void\n } | null\n toBlob(callback: (blob: Blob | null) => void, type?: string, quality?: number): void\n}\nconst imaging = globalThis as unknown as {\n createImageBitmap?: (source: Blob) => Promise<ImageBitmapLike>\n document?: { createElement(tagName: 'canvas'): CanvasLike }\n}\n\n/**\n * The bytes to upload, and the type they are.\n *\n * Oversized images are redrawn to {@link MAX_IMAGE_EDGE} first: a modern phone\n * photo is 4000px on its long edge, which costs tokens for detail no model\n * reads, and often exceeds the gateway's per-file cap outright. Everything else\n * — and anything the browser can't decode — is uploaded as-is, so a failure here\n * is never worse than not trying.\n */\nasync function prepare(file: File): Promise<{ body: Blob; mediaType: string }> {\n const mediaType = file.type || 'application/octet-stream'\n const { createImageBitmap, document } = imaging\n // GIFs are excluded because a redraw would keep one frame of an animation.\n if (!createImageBitmap || !document || !mediaType.startsWith('image/')) {\n return { body: file, mediaType }\n }\n if (mediaType === 'image/gif') return { body: file, mediaType }\n try {\n const bitmap = await createImageBitmap(file)\n const longest = Math.max(bitmap.width, bitmap.height)\n if (longest <= MAX_IMAGE_EDGE) {\n bitmap.close()\n return { body: file, mediaType }\n }\n const scale = MAX_IMAGE_EDGE / longest\n const canvas = document.createElement('canvas')\n canvas.width = Math.round(bitmap.width * scale)\n canvas.height = Math.round(bitmap.height * scale)\n const context = canvas.getContext('2d')\n if (!context) {\n bitmap.close()\n return { body: file, mediaType }\n }\n context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n bitmap.close()\n const blob = await new Promise<Blob | null>((resolve) =>\n canvas.toBlob(resolve, 'image/jpeg', 0.85),\n )\n return blob ? { body: blob, mediaType: 'image/jpeg' } : { body: file, mediaType }\n } catch {\n // A format the browser can't decode (HEIC on most desktops) — let the\n // gateway answer with its own 415 rather than inventing one here.\n return { body: file, mediaType }\n }\n}\n","/**\n * The two prompt tokens the CLI understands — `@file` and `/command` — found in\n * text that has already been sent.\n *\n * The mirror of the iOS client's `PromptTokens.scan`, and deliberately the same\n * rules: a message should read the same after sending as it did in the composer,\n * on either client. It lives here, beside the transcript reducer, for the same\n * reason its Swift twin lives in the kit rather than the app — every interesting\n * case is an edge (an `@` mid-word, an email address, a slash that is really an\n * absolute path), so it is the part that gets unit-tested.\n *\n * Only the finished-text half is here; the composer's completion is the\n * prompt-area's own trigger machinery.\n */\nexport type PromptToken = {\n kind: 'file' | 'command'\n /** Offsets into the scanned string, prefix included. */\n start: number\n end: number\n text: string\n}\n\n/** Characters a command name may contain after the slash. Deliberately excludes\n * `/`, so an absolute path pasted into a message (`/Users/me/…`) is not mistaken\n * for a command; `:` is in because namespaced skills (`dev:wrapup`) are spelled\n * that way. */\nconst COMMAND_BODY = /^[A-Za-z0-9\\-_.:]+$/\n\n/** Trailing punctuation that belongs to the sentence, not the token — so\n * \"see @README.md.\" styles the path and leaves the period alone. */\nconst SENTENCE_TAIL = new Set(['.', ',', ';', ':', '!', '?', ')', ']', '}', '\"', \"'\"])\n\n/**\n * Every token in a sent message.\n *\n * Stricter than what a composer completes: a bare `@` is a token being typed, but\n * in a sent message it is just an at sign.\n */\nexport function scanPromptTokens(text: string): PromptToken[] {\n const tokens: PromptToken[] = []\n // Word starts: the beginning of the text, and every position after whitespace.\n const words = /\\S+/g\n let match: RegExpExecArray | null\n while ((match = words.exec(text)) !== null) {\n const word = match[0]\n const kind = word[0] === '@' ? 'file' : word[0] === '/' ? 'command' : undefined\n if (!kind) continue\n let end = match.index + word.length\n while (end > match.index && SENTENCE_TAIL.has(text[end - 1]!)) end--\n const body = text.slice(match.index + 1, end)\n if (!body) continue\n if (kind === 'command' && !COMMAND_BODY.test(body)) continue\n tokens.push({ kind, start: match.index, end, text: text.slice(match.index, end) })\n }\n return tokens\n}\n","import type { HostDirEntry } from '@workerdeck/protocol'\n\n/**\n * One directory as the tree knows it: what `/fs/list` answered, plus whether the\n * server held entries back.\n *\n * A directory that has never been asked for is simply absent from the map — which\n * is not the same as an empty directory, and the difference is what tells the\n * renderer to show a spinner rather than \"nothing here\".\n */\nexport type HostDirState = {\n entries: HostDirEntry[]\n /** The directory held more entries than the server will return. */\n truncated?: boolean\n}\n\n/** One rendered row of the tree — a flat list is what a scroll container wants,\n * and indentation is a number, not a nesting of DOM. */\nexport type HostTreeRow = {\n entry: HostDirEntry\n /** 0 for the root's own children. */\n depth: number\n /** Directories only: whether this row's children are showing. */\n expanded?: boolean\n /** Set on an expanded directory whose listing hasn't arrived yet. */\n loading?: boolean\n /** Set on an expanded directory the server truncated. */\n truncated?: boolean\n}\n\n/**\n * Flatten the loaded directories into the rows the tree shows.\n *\n * Pure, so the interesting part of a file tree — which nodes are visible at what\n * depth once a few directories are expanded and one of them is still loading —\n * is testable without a DOM or a gateway.\n *\n * Only *expanded* directories contribute children, and only if their listing has\n * arrived. An expanded-but-unlisted directory yields its own row with\n * `loading: true` and no children: expansion is a request the user already made,\n * so the row must say the answer is coming rather than look like an empty folder.\n */\nexport function flattenHostTree(\n root: string,\n dirs: ReadonlyMap<string, HostDirState>,\n expanded: ReadonlySet<string>,\n): HostTreeRow[] {\n const rows: HostTreeRow[] = []\n // Iterative rather than recursive: a deep tree is a user's checkout, not a\n // bounded structure, and blowing the stack on someone's monorepo would be a\n // silly way to fail.\n const walk = (dir: string, depth: number) => {\n const state = dirs.get(dir)\n if (!state) return\n for (const entry of state.entries) {\n if (entry.type !== 'dir') {\n rows.push({ entry, depth })\n continue\n }\n const isExpanded = expanded.has(entry.path)\n const childState = dirs.get(entry.path)\n rows.push({\n entry,\n depth,\n expanded: isExpanded,\n loading: isExpanded && !childState,\n truncated: isExpanded ? childState?.truncated : undefined,\n })\n if (isExpanded && childState) walk(entry.path, depth + 1)\n }\n }\n walk(root, 0)\n return rows\n}\n\n/**\n * Every ancestor of `path` below `root`, outermost first — the directories that\n * must be expanded for `path` to be on screen.\n *\n * Returns `[]` when `path` is not under `root` rather than guessing: revealing a\n * file the tree cannot contain is a no-op, not an error worth raising, and the\n * caller has no better answer either.\n *\n * The prefix test is on a **path boundary** (`root` + `/`), so `/src/app` is not\n * treated as living under `/src/a`.\n */\nexport function ancestorsWithin(root: string, path: string): string[] {\n const base = root.endsWith('/') ? root.slice(0, -1) : root\n if (path === base || !path.startsWith(`${base}/`)) return []\n const rest = path.slice(base.length + 1).split('/')\n // The last segment is the file itself, which is not a directory to expand.\n const out: string[] = []\n let current = base\n for (const segment of rest.slice(0, -1)) {\n current = `${current}/${segment}`\n out.push(current)\n }\n return out\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { WorkerDeckError, type WorkerDeckClient } from '@workerdeck/client'\nimport type { HostFileMatch } from '@workerdeck/protocol'\nimport { ancestorsWithin, flattenHostTree, type HostDirState, type HostTreeRow } from './host-tree.ts'\n\nexport type UseHostFileSearchResult = {\n /**\n * Whether `@file` completion is on offer at all: the session's cwd is known\n * and this gateway hasn't already 404'd the search. Read it before advertising\n * the affordance — a server without host files configured has none.\n */\n available: boolean\n /**\n * Run one search. Safe to call per keystroke — the route is built for it\n * (bounded walk, build directories skipped) — and it answers `[]` rather than\n * throwing, because a failed lookup is not worth an error banner over an\n * affordance the user can ignore.\n */\n search: (query: string, options?: { limit?: number; signal?: AbortSignal }) => Promise<HostFileMatch[]>\n}\n\n/**\n * Fuzzy file search rooted at a session's working directory — what an `@file`\n * picker needs.\n *\n * Deliberately session-scoped: the server's `hostFiles.roots` are the security\n * boundary, but what someone wants while talking to an agent is *this* project's\n * tree, so this never offers the roots list.\n *\n * A gateway that answers 404 once has answered for the session: host files are\n * either configured or they aren't, and the answer will not change while the cwd\n * holds. Asking again on every character would be a request per keystroke for a\n * feature that does not exist here.\n */\nexport function useHostFileSearch(\n client: WorkerDeckClient,\n cwd: string | undefined,\n): UseHostFileSearchResult {\n const [unsupported, setUnsupported] = useState(false)\n // A resume into a different directory invalidates the verdict as well as the\n // results — the new cwd may well be under a configured root.\n const lastCwd = useRef(cwd)\n useEffect(() => {\n if (lastCwd.current !== cwd) {\n lastCwd.current = cwd\n setUnsupported(false)\n }\n }, [cwd])\n\n const search = useCallback(\n async (query: string, options?: { limit?: number; signal?: AbortSignal }) => {\n if (!cwd || unsupported) return []\n try {\n const response = await client.findHostFiles(cwd, query, options?.limit ?? 8)\n return options?.signal?.aborted ? [] : response.matches\n } catch (e) {\n // No host files on this gateway (or the cwd isn't under a root).\n if (e instanceof WorkerDeckError && e.status === 404) setUnsupported(true)\n return []\n }\n },\n [client, cwd, unsupported],\n )\n\n return { available: !!cwd && !unsupported, search }\n}\n\nexport type UseHostFileRootsResult = {\n /** Whether this gateway serves host files at all. */\n available: boolean\n /**\n * Whether `PUT /fs/write` is enabled here.\n *\n * Read it before offering an editor. Writing is a **separate** server opt-in\n * from reading and defaults off, so a gateway that happily lists and reads a\n * tree may still refuse every save — and finding that out at save time, with\n * edits already made, is the worst moment for it.\n */\n canWrite: boolean\n}\n\n/**\n * Whether host files are served here, and whether they may be written.\n *\n * One request per client, cached for the life of the hook: the roots and the\n * write flag are gateway configuration, not session state, and they do not\n * change while the tab is open.\n */\nexport function useHostFileRoots(client: WorkerDeckClient): UseHostFileRootsResult {\n const [result, setResult] = useState<UseHostFileRootsResult>({\n available: false,\n canWrite: false,\n })\n useEffect(() => {\n let cancelled = false\n client\n .listHostRoots()\n .then((response) => {\n if (!cancelled) setResult({ available: true, canWrite: response.canWrite })\n })\n // A 404 means no host files here; anything else means we could not find\n // out. Both answer the same way, because the safe default for \"may I\n // write to the operator's disk?\" is no.\n .catch(() => {\n if (!cancelled) setResult({ available: false, canWrite: false })\n })\n return () => {\n cancelled = true\n }\n }, [client])\n return result\n}\n\nexport type UseHostFileTreeResult = {\n /**\n * Whether a tree can be shown at all: the cwd is known and this gateway serves\n * host files. Read it before rendering the rail — a gateway with no\n * `hostFiles` configured has no tree, and that is a layout decision, not an\n * error to display.\n */\n available: boolean\n /** The directory the tree is rooted at — the session's cwd. */\n root: string | undefined\n /** The visible tree, flattened. Empty until the root listing arrives. */\n rows: HostTreeRow[]\n /** True while the root listing is outstanding and there is nothing to show. */\n loading: boolean\n /** A listing that failed, verbatim from the gateway. */\n error: string | undefined\n /** Expand or collapse a directory. Expanding lists it once and remembers. */\n toggle: (path: string) => void\n /** Expand every directory between the root and this path, so it is on screen. */\n reveal: (path: string) => void\n /** Re-list one directory (default: the root), keeping what is expanded. */\n refresh: (path?: string) => void\n}\n\n/**\n * An expandable file tree rooted at a session's working directory.\n *\n * Rooted at the cwd rather than at `/fs/roots` for the same reason\n * {@link useHostFileSearch} is: the roots are the *security* boundary the server\n * enforces on every request, but what someone wants while watching an agent work\n * is this project's tree. The roots may well be broader; showing them would\n * offer navigation to directories the session has nothing to do with.\n *\n * Listings are cached per directory and kept across a collapse, so reopening a\n * folder is instant and does not re-ask. That staleness is deliberate and\n * bounded: `refresh` exists, and knowing when to call it is the *next* problem\n * (the agent is editing this same tree), not something a tree can guess.\n *\n * Like the search hook, a 404 is answered once for the session: host files are\n * either configured here or they are not.\n */\nexport function useHostFileTree(\n client: WorkerDeckClient,\n cwd: string | undefined,\n): UseHostFileTreeResult {\n const [dirs, setDirs] = useState<Map<string, HostDirState>>(() => new Map())\n const [expanded, setExpanded] = useState<Set<string>>(() => new Set())\n const [unsupported, setUnsupported] = useState(false)\n const [error, setError] = useState<string | undefined>()\n\n // A resume into a different project invalidates everything, including the\n // 404 verdict — the new cwd may well be under a configured root.\n const lastCwd = useRef(cwd)\n useEffect(() => {\n if (lastCwd.current === cwd) return\n lastCwd.current = cwd\n setDirs(new Map())\n setExpanded(new Set())\n setUnsupported(false)\n setError(undefined)\n }, [cwd])\n\n const alive = useRef(true)\n useEffect(() => {\n alive.current = true\n return () => {\n alive.current = false\n }\n }, [])\n\n // Directories whose listing has been asked for. A ref rather than state: it\n // must not re-render anything, and it is what keeps an expand-collapse-expand\n // from issuing three requests.\n const requested = useRef(new Set<string>())\n\n const list = useCallback(\n (target: string, { force = false } = {}) => {\n if (unsupported) return\n if (!force && requested.current.has(target)) return\n requested.current.add(target)\n client\n .listHostDir(target)\n .then((response) => {\n if (!alive.current) return\n setDirs((previous) => {\n const next = new Map(previous)\n // Keyed on the requested path, not the canonical one the server\n // answers with: the tree navigates by the paths `/fs/list` gave it,\n // and re-keying on a resolved path would orphan the node that asked.\n next.set(target, { entries: response.entries, truncated: response.truncated })\n return next\n })\n })\n .catch((e: unknown) => {\n if (!alive.current) return\n requested.current.delete(target)\n if (e instanceof WorkerDeckError && e.status === 404) {\n // No host files on this gateway, or the cwd is not under a root.\n // Not an error banner — the rail simply is not on offer.\n setUnsupported(true)\n return\n }\n setError(e instanceof Error ? e.message : 'Could not read that directory')\n })\n },\n [client, unsupported],\n )\n\n // The root lists itself; everything below is listed on expand.\n useEffect(() => {\n if (cwd) list(cwd)\n }, [cwd, list])\n\n const toggle = useCallback(\n (path: string) => {\n setExpanded((previous) => {\n const next = new Set(previous)\n if (next.has(path)) next.delete(path)\n else next.add(path)\n return next\n })\n // Outside the updater on purpose — React may run an updater twice, and a\n // request fired from inside one is a side effect in a place that promises\n // not to have any. Listing is idempotent (`requested` guards it) and the\n // first action on a directory is always an expand, so the call this makes\n // on a *collapse* has already been answered and does nothing.\n list(path)\n },\n [list],\n )\n\n const reveal = useCallback(\n (path: string) => {\n if (!cwd) return\n const ancestors = ancestorsWithin(cwd, path)\n if (ancestors.length === 0) return\n for (const dir of ancestors) list(dir)\n setExpanded((previous) => {\n const next = new Set(previous)\n for (const dir of ancestors) next.add(dir)\n return next\n })\n },\n [cwd, list],\n )\n\n const refresh = useCallback(\n (path?: string) => {\n const target = path ?? cwd\n if (!target) return\n setError(undefined)\n list(target, { force: true })\n },\n [cwd, list],\n )\n\n const rows = useMemo(\n () => (cwd ? flattenHostTree(cwd, dirs, expanded) : []),\n [cwd, dirs, expanded],\n )\n\n return {\n available: !!cwd && !unsupported,\n root: cwd,\n rows,\n loading: !!cwd && !unsupported && !dirs.has(cwd) && !error,\n error,\n toggle,\n reveal,\n refresh,\n }\n}\n","import { useEffect, useState } from 'react'\nimport type { WorkerDeckClient } from '@workerdeck/client'\nimport type { SessionInfo } from '@workerdeck/protocol'\n\nexport type UseSessionInfoResult = {\n info: SessionInfo | undefined\n /** True until the first answer — distinguishes \"still asking\" from \"no such session\". */\n loading: boolean\n /** Set when the gateway refused; `info` stays undefined. */\n error: string | undefined\n}\n\n/**\n * The registry's record of one session, over REST.\n *\n * Separate from {@link useClaudeSession} on purpose: that hook attaches a\n * WebSocket and streams a transcript, which is far more than a caller needs to\n * know a session's `cwd` or title — and a second attach would be a second\n * client on the bridge, which is the one thing the bridge's \"asks the first\n * attached client\" rule cannot tolerate.\n *\n * Fetched once per session id. The record is registry state, not a live feed;\n * anything that changes during a run arrives on the session's event stream.\n */\nexport function useSessionInfo(\n client: WorkerDeckClient,\n sessionId: string | undefined,\n): UseSessionInfoResult {\n const [info, setInfo] = useState<SessionInfo | undefined>()\n const [loading, setLoading] = useState(!!sessionId)\n const [error, setError] = useState<string | undefined>()\n\n useEffect(() => {\n if (!sessionId) {\n setInfo(undefined)\n setLoading(false)\n setError(undefined)\n return\n }\n let cancelled = false\n setLoading(true)\n setError(undefined)\n // The previous session's record must not linger under the new id — a stale\n // cwd would root a file tree in the wrong project.\n setInfo(undefined)\n client\n .getSession(sessionId)\n .then((next) => {\n if (cancelled) return\n setInfo(next)\n setLoading(false)\n })\n .catch((e: unknown) => {\n if (cancelled) return\n setError(e instanceof Error ? e.message : 'Session not found')\n setLoading(false)\n })\n return () => {\n cancelled = true\n }\n }, [client, sessionId])\n\n return { info, loading, error }\n}\n","/**\n * One open file, in whatever state its read got to.\n *\n * A tab exists from the moment it is opened, before any bytes arrive — the tab\n * strip is the record of what the user asked for, not of what the gateway has\n * answered, and a tab that only appeared once the read landed would make a slow\n * read look like a dead click.\n */\nexport type OpenFile = {\n /** Absolute host path — the tab's identity. Opening the same path twice\n * focuses the existing tab rather than making a second one. */\n path: string\n /** Last segment, for the tab label. */\n name: string\n status: 'loading' | 'ready' | 'binary' | 'error'\n /** The text **as last seen on disk** — never the user's edits. */\n content?: string\n /**\n * The user's unsaved text. Absent when nothing has been typed since the last\n * read or save.\n *\n * Kept separate from `content` rather than overwriting it, because a\n * conditional write needs to know both: what is being sent, and what the\n * `hash` describes. Collapsing them would make \"did this change?\" unanswerable\n * after the first keystroke.\n */\n draft?: string\n bytes?: number\n /**\n * sha256 of the bytes `content` was read from — the `expectedHash` for the\n * next write.\n *\n * This is the whole safety mechanism: `/fs/write` is conditional *always*, so\n * a tab that lost its hash could not save at all without re-reading, and\n * re-reading to save is precisely the race the conditional write exists to\n * prevent.\n */\n hash?: string\n modifiedAt?: number\n /** Why the read failed, verbatim from the gateway. */\n error?: string\n /** A write is in flight. */\n saving?: boolean\n /** Why the last write failed, verbatim from the gateway. */\n saveError?: string\n /**\n * The file changed on disk since this tab read it — the gateway answered 409.\n *\n * Held as a distinct flag rather than folded into `saveError` because it is\n * the one failure with a *choice* attached (reload, overwrite, keep editing)\n * rather than a message to read.\n */\n conflict?: boolean\n}\n\n/** Whether a tab has edits that are not on disk. Derived, so typing something\n * and undoing it back leaves the tab clean — which is what an editor should do\n * and what a boolean flag set on first keystroke would get wrong. */\nexport function isDirty(file: OpenFile): boolean {\n return file.draft !== undefined && file.draft !== file.content\n}\n\n/** What a tab would write: its edits if it has any, else what it read. */\nexport function currentText(file: OpenFile): string {\n return file.draft ?? file.content ?? ''\n}\n\nexport type OpenFilesState = {\n /** Tab order, left to right. */\n files: OpenFile[]\n /** Absolute path of the focused tab, or undefined when nothing is open. */\n activePath?: string\n}\n\nexport type OpenFilesAction =\n | { type: 'open'; path: string }\n | { type: 'close'; path: string }\n | { type: 'closeAll' }\n | { type: 'activate'; path: string }\n /** A read landed. Ignored if the tab was closed while it was in flight. */\n | {\n type: 'loaded'\n path: string\n content: string\n encoding: 'utf8' | 'base64'\n bytes: number\n hash: string\n modifiedAt: number\n }\n | { type: 'failed'; path: string; error: string }\n /** The user typed. */\n | { type: 'edit'; path: string; content: string }\n /** Throw away unsaved edits and go back to what was read. */\n | { type: 'revert'; path: string }\n | { type: 'saveStart'; path: string }\n /** A write succeeded. `content` is **what was written**, not what the tab\n * holds now — the user may have kept typing while it was in flight. */\n | { type: 'saved'; path: string; content: string; bytes: number; hash: string; modifiedAt: number }\n | { type: 'saveFailed'; path: string; error: string; conflict?: boolean }\n /** Dismiss the conflict banner and carry on editing. */\n | { type: 'dismissConflict'; path: string }\n\nexport const initialOpenFilesState: OpenFilesState = { files: [] }\n\n/**\n * The tab strip and the editor's whole behaviour, as a pure function.\n *\n * The rules worth stating, because they are the ones a naive implementation\n * gets wrong:\n *\n * - **Opening an open path never re-reads it.** It focuses the tab. Re-reading\n * would silently discard that tab's unsaved edits on a double click.\n * - **Closing the focused tab focuses its right-hand neighbour**, falling back\n * to the left when it was last. Focusing \"the first tab\" instead is what makes\n * closing several tabs in a row jump the user around.\n * - **A successful save is applied against the text that was sent**, not against\n * the tab's current text. Typing during a save is normal; treating the write's\n * completion as \"the tab is now clean\" would silently drop those keystrokes.\n * - **Nothing here discards edits implicitly.** `revert` and `loaded` are the\n * only two things that clear a draft, and both are the direct result of\n * someone asking for it. The conditional write exists so a browser edit cannot\n * clobber the agent mid-run; this holds the same line in the other direction.\n *\n * Late results are addressed by path and dropped if that tab is gone, so a slow\n * read of a closed file cannot resurrect it.\n */\nexport function openFilesReducer(\n state: OpenFilesState,\n action: OpenFilesAction,\n): OpenFilesState {\n switch (action.type) {\n case 'open': {\n if (state.files.some((f) => f.path === action.path)) {\n return state.activePath === action.path ? state : { ...state, activePath: action.path }\n }\n const file: OpenFile = { path: action.path, name: baseName(action.path), status: 'loading' }\n return { files: [...state.files, file], activePath: action.path }\n }\n\n case 'close': {\n const index = state.files.findIndex((f) => f.path === action.path)\n if (index === -1) return state\n const files = state.files.filter((f) => f.path !== action.path)\n if (state.activePath !== action.path) return { ...state, files }\n // The neighbour that was to the right has slid into this index; if the\n // closed tab was last, take the one now at the end.\n const next = files[index] ?? files[index - 1]\n return { files, activePath: next?.path }\n }\n\n case 'closeAll':\n return initialOpenFilesState\n\n case 'activate':\n if (!state.files.some((f) => f.path === action.path)) return state\n return state.activePath === action.path ? state : { ...state, activePath: action.path }\n\n case 'loaded':\n // Also the \"reload from disk\" path: the draft goes, deliberately, because\n // the only way here with a dirty tab is someone choosing to discard.\n return patch(state, action.path, () => ({\n path: action.path,\n name: baseName(action.path),\n // A base64 answer means the bytes are not text. The viewer says so\n // rather than rendering the base64, which is the one thing nobody wants\n // to look at — and an editor must never open it, because saving it back\n // as utf8 would corrupt the file.\n status: action.encoding === 'utf8' ? 'ready' : 'binary',\n content: action.encoding === 'utf8' ? action.content : undefined,\n bytes: action.bytes,\n hash: action.hash,\n modifiedAt: action.modifiedAt,\n }))\n\n case 'failed':\n return patch(state, action.path, (file) => ({ ...file, status: 'error', error: action.error }))\n\n case 'edit':\n // Only a readable text file can be edited; a binary or errored tab has no\n // content the editor could have been showing.\n return patch(state, action.path, (file) =>\n file.status === 'ready' ? { ...file, draft: action.content } : file,\n )\n\n case 'revert':\n return patch(state, action.path, (file) => ({\n ...file,\n draft: undefined,\n saveError: undefined,\n conflict: false,\n }))\n\n case 'saveStart':\n return patch(state, action.path, (file) => ({\n ...file,\n saving: true,\n saveError: undefined,\n conflict: false,\n }))\n\n case 'saved':\n return patch(state, action.path, (file) => ({\n ...file,\n saving: false,\n saveError: undefined,\n conflict: false,\n content: action.content,\n bytes: action.bytes,\n hash: action.hash,\n modifiedAt: action.modifiedAt,\n // Keystrokes that landed mid-flight survive; a draft equal to what was\n // written is simply no longer a draft.\n draft: file.draft === action.content ? undefined : file.draft,\n }))\n\n case 'saveFailed':\n return patch(state, action.path, (file) => ({\n ...file,\n saving: false,\n saveError: action.error,\n conflict: action.conflict ?? false,\n }))\n\n case 'dismissConflict':\n return patch(state, action.path, (file) => ({\n ...file,\n conflict: false,\n saveError: undefined,\n }))\n }\n}\n\n/** Replace one file in place, preserving tab order; a no-op if it was closed\n * while the request was in flight. */\nfunction patch(\n state: OpenFilesState,\n path: string,\n next: (file: OpenFile) => OpenFile,\n): OpenFilesState {\n const index = state.files.findIndex((f) => f.path === path)\n if (index === -1) return state\n const current = state.files[index]!\n const updated = next(current)\n if (updated === current) return state\n const files = state.files.slice()\n files[index] = updated\n return { ...state, files }\n}\n\n/** Last path segment. Trailing slashes are not expected here — these are file\n * paths from `/fs/list` and `/fs/find` — but a bare `/` should still show as\n * something rather than as an empty tab. */\nfunction baseName(path: string): string {\n const trimmed = path.endsWith('/') ? path.slice(0, -1) : path\n return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed || path\n}\n","import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'\nimport { WorkerDeckError, type WorkerDeckClient } from '@workerdeck/client'\nimport {\n currentText,\n initialOpenFilesState,\n isDirty,\n openFilesReducer,\n type OpenFile,\n type OpenFilesState,\n} from './open-files.ts'\n\nexport type UseOpenFilesResult = OpenFilesState & {\n /** The focused file, resolved — what the editor renders. */\n active: OpenFile | undefined\n /** Any tab with unsaved edits — what a close or unload guard asks. */\n hasUnsaved: boolean\n /** Open a path, or focus it if it is already open. */\n open: (path: string) => void\n close: (path: string) => void\n closeAll: () => void\n activate: (path: string) => void\n /** Record a keystroke. Pure state; nothing is written until `save`. */\n edit: (path: string, content: string) => void\n /** Write the tab's edits, conditional on the hash it read. No-op if clean. */\n save: (path: string) => Promise<void>\n /** Throw the tab's edits away and go back to what was read. */\n revert: (path: string) => void\n /** Re-read from disk. **Discards unsaved edits** — only call on an explicit\n * choice, never to \"refresh\". */\n reload: (path: string) => void\n /** Resolve a conflict by taking this tab's version: re-read for the current\n * hash, then write the draft against it. */\n overwrite: (path: string) => Promise<void>\n /** Dismiss the conflict banner without resolving it. */\n dismissConflict: (path: string) => void\n}\n\n/**\n * The open-file tabs of a workspace: which files are open, which one is focused,\n * the bytes behind each, and the edits on top of them.\n *\n * Reads are fired from an effect keyed on \"which tabs are still loading\" rather\n * than from `open` itself, so the reducer stays pure and a tab that was opened,\n * closed and reopened does not carry a stale in-flight request with it.\n *\n * Deliberately **not** given the session's cwd: a tab is an absolute host path,\n * and where it came from — the tree, a search hit, a path in the transcript — is\n * the caller's business. Containment is the server's job on every `/fs/read` and\n * `/fs/write`, not something re-derived here from a directory this hook would\n * have to trust.\n */\nexport function useOpenFiles(client: WorkerDeckClient): UseOpenFilesResult {\n const [state, dispatch] = useReducer(openFilesReducer, initialOpenFilesState)\n\n // Paths whose read has been started. Not derived from status, because a tab\n // stays 'loading' for the whole round trip and the effect re-runs on every\n // unrelated tab change in the meantime.\n const requested = useRef(new Set<string>())\n // Reads and writes outlive the component on a fast close-and-unmount; the flag\n // is what stops a resolved promise dispatching into a dead reducer.\n const alive = useRef(true)\n useEffect(() => {\n alive.current = true\n return () => {\n alive.current = false\n }\n }, [])\n\n // The latest state, for callbacks that must read a tab at call time rather\n // than close over the render they were created in — `save` is invoked from a\n // keybinding that outlives any single render.\n const latest = useRef(state)\n useEffect(() => {\n latest.current = state\n }, [state])\n\n const loading = state.files.filter((f) => f.status === 'loading')\n // Join the paths so the effect's identity tracks the *set* of pending reads,\n // not the array that the reducer rebuilds on every action.\n const pending = loading.map((f) => f.path).join('\\n')\n\n const read = useCallback(\n (path: string) =>\n client.readHostFile(path).then((response) => {\n if (!alive.current) return undefined\n dispatch({\n type: 'loaded',\n // The gateway answers with the canonical path; the tab is keyed on\n // what was asked for, so dispatch under that and let the response's\n // own path stay an implementation detail of the read.\n path,\n content: response.content,\n encoding: response.encoding,\n bytes: response.bytes,\n hash: response.hash,\n modifiedAt: response.modifiedAt,\n })\n return response\n }),\n [client],\n )\n\n useEffect(() => {\n for (const path of pending ? pending.split('\\n') : []) {\n if (requested.current.has(path)) continue\n requested.current.add(path)\n read(path).catch((e: unknown) => {\n if (!alive.current) return\n dispatch({\n type: 'failed',\n path,\n error: e instanceof Error ? e.message : 'Could not read that file',\n })\n })\n }\n }, [read, pending])\n\n const open = useCallback((path: string) => dispatch({ type: 'open', path }), [])\n const close = useCallback((path: string) => {\n // Forget the request too, so reopening the tab reads again rather than\n // sitting on 'loading' forever.\n requested.current.delete(path)\n dispatch({ type: 'close', path })\n }, [])\n const closeAll = useCallback(() => {\n requested.current.clear()\n dispatch({ type: 'closeAll' })\n }, [])\n const activate = useCallback((path: string) => dispatch({ type: 'activate', path }), [])\n const edit = useCallback(\n (path: string, content: string) => dispatch({ type: 'edit', path, content }),\n [],\n )\n const revert = useCallback((path: string) => dispatch({ type: 'revert', path }), [])\n const dismissConflict = useCallback(\n (path: string) => dispatch({ type: 'dismissConflict', path }),\n [],\n )\n\n const reload = useCallback(\n (path: string) => {\n requested.current.add(path)\n read(path).catch((e: unknown) => {\n if (!alive.current) return\n dispatch({\n type: 'failed',\n path,\n error: e instanceof Error ? e.message : 'Could not re-read that file',\n })\n })\n },\n [read],\n )\n\n /** One conditional write. Shared by `save` and `overwrite`, which differ only\n * in where the hash came from. */\n const write = useCallback(\n async (path: string, text: string, expectedHash: string | undefined) => {\n try {\n const response = await client.writeHostFile({ path, content: text, expectedHash })\n if (!alive.current) return\n dispatch({\n type: 'saved',\n path,\n content: text,\n bytes: response.bytes,\n hash: response.hash,\n modifiedAt: response.modifiedAt,\n })\n } catch (e) {\n if (!alive.current) return\n // 409 is the whole point of the conditional write: the file moved under\n // this tab. It is a choice to offer, not a message to print.\n const conflict = e instanceof WorkerDeckError && e.status === 409\n dispatch({\n type: 'saveFailed',\n path,\n conflict,\n error: conflict\n ? 'This file changed on disk since you opened it.'\n : e instanceof Error\n ? e.message\n : 'Could not save that file',\n })\n }\n },\n [client],\n )\n\n const save = useCallback(\n async (path: string) => {\n const file = latest.current.files.find((f) => f.path === path)\n if (!file || file.saving || !isDirty(file)) return\n dispatch({ type: 'saveStart', path })\n await write(path, currentText(file), file.hash)\n },\n [write],\n )\n\n const overwrite = useCallback(\n async (path: string) => {\n const file = latest.current.files.find((f) => f.path === path)\n if (!file || file.saving) return\n // The text to keep, captured before the re-read — `loaded` would clear the\n // draft, which is exactly what \"take mine\" must not do.\n const mine = currentText(file)\n dispatch({ type: 'saveStart', path })\n try {\n // There is no unconditional overwrite by design, so taking this tab's\n // version means learning the *current* hash and writing against it. The\n // window between this read and the write is small but real; a second 409\n // is the correct answer if the agent writes inside it.\n const fresh = await client.readHostFile(path)\n if (!alive.current) return\n await write(path, mine, fresh.hash)\n } catch (e) {\n if (!alive.current) return\n dispatch({\n type: 'saveFailed',\n path,\n error: e instanceof Error ? e.message : 'Could not save that file',\n })\n }\n },\n [client, write],\n )\n\n const active = useMemo(\n () => state.files.find((f) => f.path === state.activePath),\n [state.files, state.activePath],\n )\n const hasUnsaved = useMemo(() => state.files.some(isDirty), [state.files])\n\n return {\n ...state,\n active,\n hasUnsaved,\n open,\n close,\n closeAll,\n activate,\n edit,\n save,\n revert,\n reload,\n overwrite,\n dismissConflict,\n }\n}\n","import type { SessionHandle } from '@workerdeck/client'\nimport type { RunScriptResult, SandboxEngine, SandboxVfs } from '@workerdeck/sandbox'\nimport type { ToolCallRequestFrame } from '@workerdeck/protocol'\n\n/** What the host was asked to do and how it went (for UI/telemetry). */\nexport type ToolHostExecution = {\n executionId: string\n toolName: string\n status: 'running' | 'settled' | 'failed' | 'canceled'\n reason?: string\n startedAt: number\n endedAt?: number\n}\n\nexport type ToolHostRunner = (request: {\n script: string\n vfs: SandboxVfs\n timeoutMs: number\n memoryLimitBytes: number\n signal: AbortSignal\n}) => Promise<RunScriptResult>\n\nexport type ToolCallHostOptions = {\n /** Tools this client will execute. Anything else is refused, so a server can\n * never talk this tab into running something it didn't opt into.\n * Default: `['eval_script']`. */\n tools?: string[]\n /** Guest wall-clock limit, unless the request asks for less. Default 5000. */\n timeoutMs?: number\n /** Guest allocator cap, unless the request asks for less. Default 64 MiB. */\n memoryLimitBytes?: number\n /**\n * Load the WASM guest engine. Called at most once, on the first bridged call\n * — nothing is downloaded or parsed until a session actually bridges one.\n * Defaults to `@workerdeck/sandbox` with the single-file browser build.\n */\n loadEngine?: () => Promise<SandboxEngine>\n /**\n * Run the script. Defaults to executing on this thread, which is fine for the\n * short, time-boxed evaluations this is built for. Supply your own (a Web\n * Worker running the same engine) to keep long evaluations off the UI thread\n * — the guest deadline preempts the interpreter, but only between bytecode\n * ops on whichever thread it runs on.\n */\n execute?: ToolHostRunner\n /** Host-gated fetch for the guest. Omitted = the guest has no network at all. */\n fetchText?: (url: string) => Promise<string>\n /** Observe executions (rendering, logging). */\n onExecution?: (execution: ToolHostExecution) => void\n}\n\n/**\n * Answers server-bridged tool calls by executing them in this browser tab.\n * Framework-free — {@link useToolCallHost} is a thin React wrapper.\n *\n * The point is data locality: documents fetched or held client-side can be\n * evaluated here and never touch the server. The engine loads lazily, so a page\n * that never bridges a call never pays for the WASM guest.\n */\nexport function createToolCallHost(\n handle: SessionHandle,\n options: ToolCallHostOptions = {},\n): { dispose: () => void } {\n const inFlight = new Map<string, AbortController>()\n let enginePromise: Promise<SandboxEngine> | undefined\n let disposed = false\n\n const track = (execution: ToolHostExecution) => options.onExecution?.(execution)\n\n const refuse = (frame: ToolCallRequestFrame, reason: string, error: string, startedAt: number) => {\n handle.sendToolCallError(frame.executionId, reason, error)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'failed',\n reason,\n startedAt,\n endedAt: Date.now(),\n })\n }\n\n const run = async (frame: ToolCallRequestFrame): Promise<void> => {\n const startedAt = Date.now()\n const allowed = options.tools ?? ['eval_script']\n if (!allowed.includes(frame.toolName)) {\n refuse(frame, 'unsupported_tool', `this client does not execute '${frame.toolName}'`, startedAt)\n return\n }\n const script = (frame.input as { script?: unknown } | undefined)?.script\n if (typeof script !== 'string') {\n refuse(frame, 'invalid_input', 'expected a string `script` input', startedAt)\n return\n }\n\n const controller = new AbortController()\n inFlight.set(frame.executionId, controller)\n track({ executionId: frame.executionId, toolName: frame.toolName, status: 'running', startedAt })\n\n try {\n const sandbox = await import('@workerdeck/sandbox')\n const vfs = sandbox.createVfs(frame.vfsSeed)\n // Never exceed what the server asked for: it owns the deadline it will\n // give up at, and answering after that is wasted work.\n const timeoutMs = Math.min(\n frame.limits?.timeoutMs ?? Number.POSITIVE_INFINITY,\n options.timeoutMs ?? 5000,\n )\n const memoryLimitBytes = Math.min(\n frame.limits?.memoryLimitBytes ?? Number.POSITIVE_INFINITY,\n options.memoryLimitBytes ?? 64 * 1024 * 1024,\n )\n\n const result = options.execute\n ? await options.execute({ script, vfs, timeoutMs, memoryLimitBytes, signal: controller.signal })\n : await (async () => {\n enginePromise ??= (options.loadEngine ?? defaultLoadEngine)()\n return sandbox.runScript(await enginePromise, {\n script,\n vfs,\n timeoutMs,\n memoryLimitBytes,\n signal: controller.signal,\n fetchText: options.fetchText,\n })\n })()\n\n // Cancelled or torn down while we worked: the server is no longer waiting.\n if (disposed || !inFlight.has(frame.executionId)) return\n const logs = result.logs.map((l) => `[${l.level}] ${l.text}`)\n if (result.ok) {\n handle.sendToolCallResult(frame.executionId, { type: 'json', value: result.value }, logs)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'settled',\n startedAt,\n endedAt: Date.now(),\n })\n } else {\n handle.sendToolCallError(frame.executionId, result.reason, result.error, logs)\n track({\n executionId: frame.executionId,\n toolName: frame.toolName,\n status: 'failed',\n reason: result.reason,\n startedAt,\n endedAt: Date.now(),\n })\n }\n } catch (error) {\n if (disposed || !inFlight.has(frame.executionId)) return\n // Engine load failures land here — tell the server so the agent can adapt\n // instead of waiting out the deadline.\n refuse(frame, 'host_error', error instanceof Error ? error.message : String(error), startedAt)\n } finally {\n inFlight.delete(frame.executionId)\n }\n }\n\n const offRequest = handle.on('toolCallRequest', (frame) => void run(frame))\n const offCancel = handle.on('toolCallCanceled', ({ executionId, reason }) => {\n const controller = inFlight.get(executionId)\n if (!controller) return\n controller.abort()\n inFlight.delete(executionId)\n track({\n executionId,\n toolName: '',\n status: 'canceled',\n reason,\n startedAt: Date.now(),\n endedAt: Date.now(),\n })\n })\n\n return {\n dispose: () => {\n disposed = true\n offRequest()\n offCancel()\n for (const controller of inFlight.values()) controller.abort()\n inFlight.clear()\n },\n }\n}\n\n/** The single-file browser build keeps this to one lazy chunk — no separate\n * .wasm fetch, and nothing at all until the first bridged call. */\nasync function defaultLoadEngine(): Promise<SandboxEngine> {\n const [sandbox, variant] = await Promise.all([\n import('@workerdeck/sandbox'),\n import('@jitl/quickjs-singlefile-browser-release-asyncify'),\n ])\n return sandbox.loadEngine(variant as never)\n}\n","import { useEffect, useRef, useState } from 'react'\nimport type { SessionHandle } from '@workerdeck/client'\nimport {\n createToolCallHost,\n type ToolCallHostOptions,\n type ToolHostExecution,\n} from './tool-host.ts'\n\nexport type UseToolCallHostOptions = ToolCallHostOptions & {\n /** Turn the host off without unmounting. Default true. */\n enabled?: boolean\n /** How many recent executions to keep for rendering. Default 50. */\n historyLimit?: number\n}\n\n/**\n * React wrapper around {@link createToolCallHost}: subscribes while mounted and\n * exposes recent executions for rendering. All the logic lives in the\n * framework-free host — this only manages the subscription's lifetime.\n */\nexport function useToolCallHost(\n handle: SessionHandle | undefined,\n options: UseToolCallHostOptions = {},\n): { executions: ToolHostExecution[] } {\n const [executions, setExecutions] = useState<ToolHostExecution[]>([])\n // Read options at call time so re-renders never tear down the subscription.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n useEffect(() => {\n if (!handle || options.enabled === false) return\n const host = createToolCallHost(handle, {\n // Delegate every option through the ref, so a caller passing inline\n // objects/closures (the common case) doesn't resubscribe each render.\n get tools() {\n return optionsRef.current.tools\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs\n },\n get memoryLimitBytes() {\n return optionsRef.current.memoryLimitBytes\n },\n get loadEngine() {\n return optionsRef.current.loadEngine\n },\n get execute() {\n return optionsRef.current.execute\n },\n get fetchText() {\n return optionsRef.current.fetchText\n },\n onExecution: (execution) => {\n optionsRef.current.onExecution?.(execution)\n const limit = optionsRef.current.historyLimit ?? 50\n setExecutions((prev) => [\n ...prev.filter((e) => e.executionId !== execution.executionId),\n execution,\n ].slice(-limit))\n },\n })\n return () => host.dispose()\n }, [handle, options.enabled])\n\n return { executions }\n}\n","import type { TranscriptItem } from './transcript.ts'\n\n/**\n * \"What happened while you were away\", counted rather than written.\n *\n * Deterministic on purpose. A prose recap would mean spending a turn — tokens,\n * context and latency — on a summary nobody asked the model for, and it would\n * be wrong in the one case that matters most (a session that failed while\n * unattended, where the model is exactly who you shouldn't ask). Everything\n * here is already in the transcript; this only counts it.\n *\n * Framework-free and pure, like the reducer it reads from: both clients render\n * the same recap from the same numbers.\n */\nexport type RecapSummary = {\n /** Completed turns — `turn_result` rows, the engine's own unit of work. */\n turns: number\n /** Messages the model wrote. Streaming ones count: they are on screen. */\n replies: number\n /** Tool calls started, and the distinct names, most-used first. */\n tools: number\n toolNames: string[]\n /** Files the agent handed over (`file_delivered`). */\n files: number\n /** Failed turns and failed tool calls, together — what you'd want to know\n * first on coming back. */\n errors: number\n /** Approvals still waiting. Not a count of what happened, but the reason to\n * look now rather than later. */\n pending: number\n /** Any of the above non-zero. A recap of nothing is noise. */\n any: boolean\n}\n\n/** The `TranscriptState` fields a recap reads — structural, so a caller can\n * pass the whole state or just these. */\nexport type RecapInput = {\n items: readonly TranscriptItem[]\n pendingApprovals?: readonly unknown[]\n}\n\n/**\n * Summarize the items from `fromIndex` onward — the boundary being the number\n * of items that existed when the session was last looked at.\n *\n * An out-of-range boundary is clamped rather than rejected: a transcript can\n * *shrink* (a `/clear`, a fresh attach after a compaction), and the honest\n * reading of \"you last saw 40 items, there are now 12\" is \"everything here is\n * new\", not a negative count.\n */\nexport function summarizeSince(state: RecapInput, fromIndex: number): RecapSummary {\n const start = Math.max(0, Math.min(fromIndex, state.items.length))\n const fresh = state.items.slice(start)\n const toolCounts = new Map<string, number>()\n let turns = 0\n let replies = 0\n let tools = 0\n let files = 0\n let errors = 0\n\n for (const item of fresh) {\n switch (item.kind) {\n case 'turn_result':\n turns += 1\n if (item.isError) errors += 1\n break\n case 'assistant_text':\n replies += 1\n break\n case 'tool_call':\n tools += 1\n toolCounts.set(item.name, (toolCounts.get(item.name) ?? 0) + 1)\n if (item.status === 'failed' || item.result?.isError) errors += 1\n break\n case 'file_delivered':\n files += 1\n break\n case 'notice':\n if (item.level === 'error') errors += 1\n break\n default:\n break\n }\n }\n\n const toolNames = [...toolCounts.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([name]) => name)\n const pending = state.pendingApprovals?.length ?? 0\n return {\n turns,\n replies,\n tools,\n toolNames,\n files,\n errors,\n pending,\n any: turns + replies + tools + files + errors + pending > 0,\n }\n}\n\n/**\n * The recap as one line of text, in the order a person reads it: what got done,\n * what it used, what went wrong, what is waiting.\n *\n * Returns `undefined` when there is nothing to say, so a caller can render the\n * row or not on the value alone.\n */\nexport function recapLine(summary: RecapSummary): string | undefined {\n if (!summary.any) return undefined\n const parts: string[] = []\n if (summary.turns > 0) parts.push(plural(summary.turns, 'turn'))\n else if (summary.replies > 0) parts.push(plural(summary.replies, 'reply', 'replies'))\n if (summary.tools > 0) {\n // Three names is enough to recognise what it was doing; beyond that the\n // count carries more than the list.\n const named = summary.toolNames.slice(0, 3).join(', ')\n const rest = summary.toolNames.length - 3\n parts.push(`${plural(summary.tools, 'tool call')}${named ? ` (${named}${rest > 0 ? `, +${rest}` : ''})` : ''}`)\n }\n if (summary.files > 0) parts.push(plural(summary.files, 'file'))\n if (summary.errors > 0) parts.push(plural(summary.errors, 'error'))\n if (summary.pending > 0) parts.push(`${plural(summary.pending, 'approval')} waiting`)\n return parts.join(' · ')\n}\n\nfunction plural(count: number, one: string, many = `${one}s`): string {\n return `${count} ${count === 1 ? one : many}`\n}\n"],"mappings":";;;;AA4JA,MAAa,yBAA0C;CACrD,QAAQ;CAGR,cAAc,oBAAoB;CAClC,OAAO,EAAE;CACT,kBAAkB,EAAE;CACpB,cAAc;CACd,SAAS;CACV;AAED,MAAM,eAAe;AACrB,MAAM,wBAAwB;AAE9B,SAAS,UAAU,SAA6C;AAC9D,KAAI,YAAY,KAAA,EAAW,QAAO;AAClC,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAO,QACJ,KAAK,SAAU,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,GAAI,CAC/D,OAAO,QAAQ,CACf,KAAK,KAAK;;AAGf,SAAS,gBAAgB,SAAkD;AACzE,QAAO,OAAO,YAAY,WAAW,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAS,CAAC,GAAG;;;AAI3E,SAAS,WAAW,QAAqC;AACvD,KAAI,OAAO,SAAS,OAAQ,QAAO,OAAO;AAC1C,KAAI;AACF,SAAO,KAAK,UAAU,OAAO,MAAM;SAC7B;AACN,SAAO,OAAO,OAAO,MAAM;;;;AAK/B,MAAM,uBAAuB;AAE7B,SAAS,OAAO,OAAyB,MAAwC;CAC/E,MAAM,QAAQ,MAAM,WAAW,aAAa,SAAS,OAAO,KAAK,MAAM,SAAS,SAAS,KAAK,KAAK;AACnG,KAAI,UAAU,GAAI,QAAO,CAAC,GAAG,OAAO,KAAK;CACzC,MAAM,OAAO,CAAC,GAAG,MAAM;AACvB,MAAK,SAAS;AACd,QAAO;;;;;;;;AAST,SAAgB,oBAAoB,OAAwB,MAAoC;CAG9F,MAAM,SAAS,KAAK,UAAU,MAAM;AACpC,QAAO;EACL,GAAG;EAEH,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@
1
1
  {
2
2
  "name": "@workerdeck/react",
3
- "version": "0.7.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Headless React layer for WorkerDeck: useClaudeSession hook + pure transcript reducer. No styling opinion — @workerdeck/ui is the styled layer on top.",
6
6
  "license": "MIT",
@@ -17,9 +17,9 @@
17
17
  }
18
18
  },
19
19
  "dependencies": {
20
- "@workerdeck/client": "0.7.0",
21
- "@workerdeck/protocol": "0.7.0",
22
- "@workerdeck/sandbox": "0.7.0"
20
+ "@workerdeck/client": "0.11.0",
21
+ "@workerdeck/sandbox": "0.11.0",
22
+ "@workerdeck/protocol": "0.11.0"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "react": "^18.0.0 || ^19.0.0",
@@ -41,8 +41,8 @@
41
41
  "tsdown": "^0.21.10",
42
42
  "vitest": "^3.2.0",
43
43
  "ws": "^8.21.1",
44
- "@workerdeck/core": "0.7.0",
45
- "@workerdeck/server": "0.7.0"
44
+ "@workerdeck/core": "0.11.0",
45
+ "@workerdeck/server": "0.11.0"
46
46
  },
47
47
  "author": "Tobias Strebitzer",
48
48
  "repository": {