import { isSpeedMode } from '@/lib/speed-mode' import type { UserProfile } from '@/lib/collab/types' import { isMessageAttachments } from '@/lib/message-attachments' import type { ClientMessage, StatusSnapshotMessage } from '@/lib/types' import { isMoiContext } from '@/lib/moi-context' import { rm } from 'node:fs/promises' import index from '../client/index.html' import devSandbox from '../client/dev/index.html' import { api } from './api' import { getAppConfig } from './app-config' import { harnessStore } from './harness/auth' import { PORT } from './constants' import { control } from './control' import { proxyUserState } from './collab/cloudflare-access' import { isCollabEnabled } from './collab/config' import { collabManager } from './collab/manager' import { EVENTS_TOPIC, setEventServer } from './events' import { killBuildWorkers } from './applets/build-worker' import { killAllWorkers } from './applets/functions' import { startScratchpadSweeper } from './scratchpad/document' import { navigationRelay } from './navigation-relay' import { resolveScratchOp } from './scratchpad/relay' import { allHarnesses, harnessFor } from './harness/registry' import { getWorkspace, listWorkspaces } from './workspaces/registry' import { failInterruptedViewStarts, sendWorkspaceMessage } from './sessions/view-sessions' import { prepareWorkspaceStates } from './workspace-state' import { migrateLegacyWorkspaceState } from './workspace-state/legacy-migration' import { addClient, broadcast, broadcastAll, getClientCount, removeClient, sendToClient } from './state' import { startServiceLogMaintenance } from './service' import { distShell, prebuilt } from './static' import { renderStatus } from './status' import { serveVendorEmojibase, serveVendorReact } from './vendor' type WsData = { channel: 'chat' | 'events' | 'collab' workspaceId: string workspacePath?: string // The collab profile a proxy (Cloudflare Access) verified for the upgrade. verifiedProfile?: UserProfile } function isClientMessage(value: unknown): value is ClientMessage { if (typeof value !== 'object' || value === null || !('type' in value)) return false const v = value as { type: string workspaceId?: unknown sessionId?: unknown content?: unknown isNew?: unknown selectedSessionScope?: unknown optimisticId?: unknown model?: unknown effort?: unknown speedMode?: unknown stream?: unknown context?: unknown attachments?: unknown opId?: unknown } if (v.type === 'chat') return ( typeof v.workspaceId === 'string' && typeof v.content === 'string' && typeof v.sessionId === 'string' && typeof v.isNew === 'boolean' && (v.selectedSessionScope === undefined || v.selectedSessionScope === 'shared' || v.selectedSessionScope === 'browser-tab') && (v.optimisticId === undefined || typeof v.optimisticId === 'string') && (v.model === undefined || typeof v.model === 'string') && (v.effort === undefined || typeof v.effort === 'string') && (v.speedMode === undefined || isSpeedMode(v.speedMode)) && (v.stream === undefined || typeof v.stream === 'boolean') && (v.context === undefined || isMoiContext(v.context)) && (v.attachments === undefined || isMessageAttachments(v.attachments)) ) if (v.type === 'stop') return typeof v.workspaceId === 'string' && typeof v.sessionId === 'string' if (v.type === 'scratchpad:op-result') return typeof v.opId === 'string' return false } // The SPA shell: prebuilt index.html in prod (served statically), the // live-bundled HTML import in dev (Bun.serve's bundler + HMR). The HTML import // stays here, in the routes table, so Bun's dev bundler keys off it. const shell = prebuilt ? distShell : index // Authoritative activity snapshot across all harnesses. Sent on chat-socket // connect and re-broadcast periodically (below) so a spinner whose terminal // status frame was lost self-heals without a reconnect. function statusSnapshot(): StatusSnapshotMessage { return { type: 'status_snapshot', sessions: allHarnesses().flatMap(h => h.activeSessions()) } } type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean } function upgrade(server: Upgradable, req: Request, data: WsData) { return server.upgrade(req, { data }) ? new Response(null, { status: 101 }) : new Response('Upgrade failed', { status: 500 }) } // Bun owns the fullstack surface: the HTML shell + dev bundler/HMR, and the two // WebSocket channels (which need Bun's native `server.upgrade` + pub/sub). Every // HTTP API route is delegated to the Hono app (`./api`) via `fetch`. const registeredWorkspaces = await listWorkspaces() await migrateLegacyWorkspaceState(registeredWorkspaces) await prepareWorkspaceStates(registeredWorkspaces) await Promise.all(registeredWorkspaces.map(failInterruptedViewStarts)) // Managed machines serve the web side on a Unix socket file that only the // machine's gateway can open, so nothing else running there reaches the API // meant for people (docs/config.md). A socket file left by a previous // run would make the bind fail. const { unixSocket } = getAppConfig() if (unixSocket) await rm(unixSocket, { force: true }) const listen = unixSocket ? { unix: unixSocket } : { port: PORT, hostname: process.env.HOST ?? '127.0.0.1' } export const app = Bun.serve({ // Bun types the port and Unix-socket listeners as separate overloads, so a // listener picked at runtime is cast to one of them; the runtime takes either. ...(listen as { port: number; hostname: string }), // Agent startup/discovery can outlast Bun's 10s HTTP default. Allow the // harness's 30s RPC timeout to return an error before the socket closes. idleTimeout: 60, // HMR only in dev; prod serves prebuilt static assets (no bundler). development: prebuilt ? false : { hmr: true }, routes: { // Plain-text server introspection — live sessions held in cache, connected // tabs, last message per thread. A quick peek into the process when a chat // seems stuck. Served as text/plain so curl/browser both show it raw. '/status': () => new Response(renderStatus(), { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } }), // Locally-vendored React ESM (offline; no CDN), under a versioned path so // production can cache it for good. The importmap in client/index.html // points here; the handler picks dev/prod per env. '/vendor/react/*': (req: Request) => serveVendorReact(req), // Vendored emojibase-data for the settings emoji picker (offline; no CDN). '/vendor/emojibase/*': (req: Request) => serveVendorEmojibase(req), // Client-side routes — serve the SPA shell. '/': shell, '/dev': shell, '/dev/*': shell, // Isolated sandboxes bypass app startup and share the client/dev entry point. '/dev/workspace-setup/preview': prebuilt ? new Response('Not found', { status: 404 }) : devSandbox, '/workspace/*': shell, '/settings': shell, '/onboarding': shell, // Chat websocket — app-wide (one per client, not per workspace). Each chat // frame carries its own workspaceId. '/ws': (req: Request, server: Bun.Server) => upgrade(server, req, { channel: 'chat', workspaceId: '' }), // Live widget-event stream (build/refresh pushes). A static path, so Bun // routes it ahead of the Hono-served `/api/workspaces/:id`; the upgrade // happens in-handler via the route's `server` argument. '/api/workspaces/ws': (req: Request, server: Bun.Server) => upgrade(server, req, { channel: 'events', workspaceId: '' }), '/api/workspaces/:id/collab/ws': async (req: Request, server: Bun.Server) => { const workspaceId = decodeURIComponent(new URL(req.url).pathname.split('/')[3] ?? '') const workspace = await getWorkspace(workspaceId) if (!workspace) return new Response('Workspace not found', { status: 404 }) if (!isCollabEnabled()) { return new Response('Collab is not enabled for this workspace', { status: 403 }) } // Behind Cloudflare Access, presence is joined only as the verified viewer. const { provider, profile } = await proxyUserState(req) if (provider && !profile) { return new Response('Sign in through Cloudflare Access to join', { status: 401 }) } return upgrade(server, req, { channel: 'collab', workspaceId, workspacePath: workspace.path, ...(profile ? { verifiedProfile: profile } : {}) }) } }, // Anything not matched above (the whole HTTP API + prod static assets + 404) // is handled by Hono. fetch: (req, server) => { // Downloads can exceed the normal HTTP idle timeout; the installer has its own deadline. if ( req.method === 'POST' && /^\/api\/harnesses\/(claude-code|codex)\/auth\/install$/.test(new URL(req.url).pathname) ) { server.timeout(req, 0) } return api.fetch(req) }, websocket: { open(ws) { if (ws.data.channel === 'collab') { if (ws.data.workspacePath) collabManager.open(ws, ws.data.workspacePath, ws.data.verifiedProfile) else ws.close(1008, 'Missing workspace') } else if (ws.data.channel === 'chat') { addClient(ws) // Authoritative snapshot of every non-idle session across all // harnesses so the client can light/clear spinners correctly even for // runs whose status transitions it missed while disconnected. sendToClient(ws, statusSnapshot()) } else { ws.subscribe(EVENTS_TOPIC) } }, async message(ws, message) { if (ws.data.channel === 'collab') { collabManager.message(ws, message) return } if (ws.data.channel === 'events') { try { navigationRelay.receive(ws, JSON.parse(String(message))) } catch {} return } try { const data = JSON.parse(String(message)) if (!isClientMessage(data)) return // Allow a message that carries only attachments (no text). if (data.type === 'chat' && (data.content?.trim() || data.attachments?.length)) { const workspace = await getWorkspace(data.workspaceId) if (!workspace) return void sendWorkspaceMessage(workspace, { workspaceId: data.workspaceId, workspacePath: workspace.path, sessionId: data.sessionId, isNew: data.isNew, selectedSessionScope: data.selectedSessionScope, content: data.content.trim(), attachments: data.attachments, optimisticId: data.optimisticId, model: data.model, effort: data.effort, speedMode: data.speedMode, stream: data.stream, context: data.context, agentId: workspace.agentId }).catch(error => { if (error instanceof Error) { broadcast(workspace.id, { kind: 'error', sessionId: data.sessionId, content: error.message }) } }) } if (data.type === 'stop') { const workspace = await getWorkspace(data.workspaceId) void harnessFor(workspace ?? undefined) .interrupt(data.workspaceId, data.sessionId) .catch(() => {}) } // A tab's reply to a relayed Scratchpad op — settle the pending CLI // request (first reply wins; later/duplicate replies are ignored). if (data.type === 'scratchpad:op-result') { resolveScratchOp(data.opId, data.result, data.error) } } catch {} }, close(ws) { if (ws.data.channel === 'collab') collabManager.close(ws) else if (ws.data.channel === 'chat') removeClient(ws) else { navigationRelay.remove(ws) ws.unsubscribe(EVENTS_TOPIC) } } } }) // Wire the live-event publisher (`publishEvent`) to this server instance now // that it exists. Kept in ./events so control.ts and ./api can publish without // importing web.ts (which binds ports on load). setEventServer(app) // The snapshot heartbeat: the client's reconcile fully replaces its activity // map from each snapshot, so any stale spinner clears within one interval. const SNAPSHOT_INTERVAL_MS = 30_000 setInterval(() => { if (getClientCount() > 0) broadcastAll(statusSnapshot()) }, SNAPSHOT_INTERVAL_MS) // Periodically reclaim scratchpad asset files nothing references anymore — // deleting an image in the browser (or an upload whose tab died) otherwise // leaves its file behind forever. See sweepOrphanAssets. startScratchpadSweeper() // Under launchd the service log is a plain file nothing rotates — bound it // here. No-op outside the macOS service context. startServiceLogMaintenance() // Graceful shutdown. In dev the supervisor sends SIGTERM on server-file // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the // per-workspace function workers and any in-flight applet build child so no // child processes are orphaned. let shuttingDown = false async function shutdown() { if (shuttingDown) return shuttingDown = true try { app.stop(true) } catch {} try { control.stop(true) } catch {} harnessStore.shutdown() for (const h of allHarnesses()) h.shutdown?.() killAllWorkers() killBuildWorkers() await collabManager.shutdown() process.exit() } process.on('SIGTERM', shutdown) process.on('SIGINT', shutdown)