From cf568902cdf682b1393c7dd5502ced06735a0391 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Feb 2026 21:52:30 +0000 Subject: [PATCH] Add renderer websocket native API adapter and bootstrap flow Co-authored-by: Theo Browne --- apps/renderer/src/App.tsx | 37 ++++- apps/renderer/src/session-logic.ts | 3 +- apps/renderer/src/store.test.ts | 31 ++++ apps/renderer/src/store.ts | 72 ++++++++- apps/renderer/src/wsNativeApi.ts | 244 +++++++++++++++++++++++++++++ 5 files changed, 380 insertions(+), 7 deletions(-) create mode 100644 apps/renderer/src/wsNativeApi.ts diff --git a/apps/renderer/src/App.tsx b/apps/renderer/src/App.tsx index a525c7caeb..a81c65edea 100644 --- a/apps/renderer/src/App.tsx +++ b/apps/renderer/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef } from "react"; +import { useEffect, useRef } from "react"; import ChatView from "./components/ChatView"; import DiffPanel from "./components/DiffPanel"; @@ -7,7 +7,7 @@ import { readNativeApi } from "./session-logic"; import { StoreProvider, useStore } from "./store"; function EventRouter() { - const api = useMemo(() => readNativeApi(), []); + const api = readNativeApi(); const { dispatch } = useStore(); const activeAssistantItemRef = useRef(null); @@ -25,8 +25,36 @@ function EventRouter() { return null; } +function BootstrapRouter() { + const api = readNativeApi(); + const { dispatch } = useStore(); + + useEffect(() => { + if (!api) return; + let cancelled = false; + void api.app + .bootstrap() + .then((bootstrap) => { + if (cancelled) return; + dispatch({ + type: "BOOTSTRAP_FROM_SERVER", + bootstrap, + }); + }) + .catch(() => { + // Keep existing renderer state if bootstrap is unavailable. + }); + + return () => { + cancelled = true; + }; + }, [api, dispatch]); + + return null; +} + function Layout() { - const api = useMemo(() => readNativeApi(), []); + const api = readNativeApi(); const { state } = useStore(); if (!api) { @@ -35,7 +63,7 @@ function Layout() {

- Native bridge unavailable. Launch through Electron. + Local t3 runtime unavailable.

@@ -44,6 +72,7 @@ function Layout() { return (
+ diff --git a/apps/renderer/src/session-logic.ts b/apps/renderer/src/session-logic.ts index 3329f8b196..6e7bb8e9cd 100644 --- a/apps/renderer/src/session-logic.ts +++ b/apps/renderer/src/session-logic.ts @@ -1,5 +1,6 @@ import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts"; import type { ChatMessage, SessionPhase } from "./types"; +import { getOrCreateWsNativeApi } from "./wsNativeApi"; export const PROVIDER_OPTIONS: Array<{ value: ProviderKind; @@ -12,7 +13,7 @@ export const PROVIDER_OPTIONS: Array<{ export function readNativeApi() { if (typeof window === "undefined") return undefined; - return window.nativeApi; + return window.nativeApi ?? getOrCreateWsNativeApi(); } export function asObject(value: unknown): Record | undefined { diff --git a/apps/renderer/src/store.test.ts b/apps/renderer/src/store.test.ts index 666f11c70f..e4cd03025f 100644 --- a/apps/renderer/src/store.test.ts +++ b/apps/renderer/src/store.test.ts @@ -64,6 +64,37 @@ function makeState(thread: Thread): AppState { } describe("store reducer thread continuity", () => { + it("bootstraps project and active thread from runtime response", () => { + const state: AppState = { + projects: [], + threads: [], + activeThreadId: null, + runtimeMode: "full-access", + diffOpen: false, + }; + const session = makeSession({ + sessionId: "sess-bootstrap", + threadId: "thr-bootstrap", + }); + + const next = reducer(state, { + type: "BOOTSTRAP_FROM_SERVER", + bootstrap: { + launchCwd: "/workspace", + projectName: "workspace", + provider: "codex", + model: "gpt-5.3-codex", + session, + }, + }); + + expect(next.projects).toHaveLength(1); + expect(next.projects[0]?.cwd).toBe("/workspace"); + expect(next.threads).toHaveLength(1); + expect(next.threads[0]?.session?.sessionId).toBe("sess-bootstrap"); + expect(next.activeThreadId).toBe(next.threads[0]?.id ?? null); + }); + it("stores codexThreadId from UPDATE_SESSION", () => { const state = makeState( makeThread({ diff --git a/apps/renderer/src/store.ts b/apps/renderer/src/store.ts index 1363a9a624..a9d194c69e 100644 --- a/apps/renderer/src/store.ts +++ b/apps/renderer/src/store.ts @@ -8,7 +8,7 @@ import { useReducer, } from "react"; -import type { ProviderEvent, ProviderSession } from "@acme/contracts"; +import type { AppBootstrapResult, ProviderEvent, ProviderSession } from "@acme/contracts"; import { resolveModelSlug } from "./model-logic"; import { hydratePersistedState, toPersistedState } from "./persistenceSchema"; import { @@ -42,7 +42,8 @@ type Action = | { type: "SET_ERROR"; threadId: string; error: string | null } | { type: "SET_THREAD_TITLE"; threadId: string; title: string } | { type: "SET_THREAD_MODEL"; threadId: string; model: string } - | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode }; + | { type: "SET_RUNTIME_MODE"; mode: RuntimeMode } + | { type: "BOOTSTRAP_FROM_SERVER"; bootstrap: AppBootstrapResult }; // ── State ──────────────────────────────────────────────────────────── @@ -328,6 +329,73 @@ export function reducer(state: AppState, action: Action): AppState { runtimeMode: action.mode, }; + case "BOOTSTRAP_FROM_SERVER": { + const { bootstrap } = action; + const existingProject = state.projects.find((project) => project.cwd === bootstrap.launchCwd); + const projectId = existingProject?.id ?? crypto.randomUUID(); + const project = + existingProject ?? + ({ + id: projectId, + name: bootstrap.projectName, + cwd: bootstrap.launchCwd, + model: resolveModelSlug(bootstrap.model), + expanded: true, + } satisfies Project); + + const projectThreads = state.threads.filter((thread) => thread.projectId === projectId); + const existingThread = + state.threads.find( + (thread) => thread.session?.sessionId === bootstrap.session.sessionId, + ) ?? + projectThreads.find( + (thread) => + bootstrap.session.threadId !== undefined && + thread.codexThreadId === bootstrap.session.threadId, + ) ?? + projectThreads[0]; + + const activeThreadId = existingThread?.id ?? crypto.randomUUID(); + const thread = + existingThread ?? + ({ + id: activeThreadId, + codexThreadId: bootstrap.session.threadId ?? null, + projectId, + title: "New thread", + model: resolveModelSlug(bootstrap.model), + session: bootstrap.session, + messages: [], + events: [], + error: null, + createdAt: new Date().toISOString(), + } satisfies Thread); + + return { + ...state, + projects: existingProject + ? state.projects.map((entry) => + entry.id === existingProject.id + ? { + ...entry, + model: resolveModelSlug(bootstrap.model), + } + : entry, + ) + : [project, ...state.projects], + threads: state.threads.map((entry) => + entry.id === thread.id + ? { + ...entry, + session: bootstrap.session, + codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId, + } + : entry, + ).concat(existingThread ? [] : [thread]), + activeThreadId, + }; + } + default: return state; } diff --git a/apps/renderer/src/wsNativeApi.ts b/apps/renderer/src/wsNativeApi.ts new file mode 100644 index 0000000000..bf703b0673 --- /dev/null +++ b/apps/renderer/src/wsNativeApi.ts @@ -0,0 +1,244 @@ +import type { + AppBootstrapResult, + NativeApi, + ProviderEvent, + WsClientMessage, + WsEventMessage, + WsResponseMessage, + OutputChunk, + AgentExit, +} from "@acme/contracts"; +import { WS_EVENT_CHANNELS, wsServerMessageSchema } from "@acme/contracts"; + +type PendingRequest = { + resolve: (value: unknown) => void; + reject: (error: Error) => void; +}; + +type SubscriptionSet = Set<(value: TValue) => void>; + +class WsNativeApiClient { + private socket: WebSocket | null = null; + private connectPromise: Promise | null = null; + private nextRequestId = 1; + private pending = new Map(); + private providerEventListeners: SubscriptionSet = new Set(); + private agentOutputListeners: SubscriptionSet = new Set(); + private agentExitListeners: SubscriptionSet = new Set(); + + constructor(private readonly wsUrl: string) {} + + private connect() { + if (this.socket && this.socket.readyState === WebSocket.OPEN) { + return Promise.resolve(this.socket); + } + + if (this.connectPromise) { + return this.connectPromise; + } + + this.connectPromise = new Promise((resolve, reject) => { + const socket = new WebSocket(this.wsUrl); + this.socket = socket; + + socket.addEventListener("open", () => { + this.connectPromise = null; + resolve(socket); + }); + + socket.addEventListener("error", () => { + this.connectPromise = null; + reject(new Error("Failed to connect to local t3 runtime.")); + }); + + socket.addEventListener("message", (event) => { + this.handleMessage(event.data); + }); + + socket.addEventListener("close", () => { + this.socket = null; + for (const [id, pending] of this.pending.entries()) { + pending.reject(new Error(`Request ${id} failed: websocket disconnected.`)); + } + this.pending.clear(); + }); + }); + + return this.connectPromise; + } + + private async request(method: string, params?: unknown) { + const socket = await this.connect(); + const id = String(this.nextRequestId); + this.nextRequestId += 1; + + const requestMessage: WsClientMessage = { + type: "request", + id, + method, + params, + }; + + const requestPromise = new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }); + }); + + socket.send(JSON.stringify(requestMessage)); + return requestPromise; + } + + private handleResponse(message: WsResponseMessage) { + const pending = this.pending.get(message.id); + if (!pending) { + return; + } + + this.pending.delete(message.id); + if (message.ok) { + pending.resolve(message.result); + return; + } + + pending.reject(new Error(message.error?.message ?? "Unknown runtime request failure.")); + } + + private handleEvent(message: WsEventMessage) { + if (message.channel === WS_EVENT_CHANNELS.providerEvent) { + for (const listener of this.providerEventListeners) { + listener(message.payload as ProviderEvent); + } + return; + } + + if (message.channel === WS_EVENT_CHANNELS.agentOutput) { + for (const listener of this.agentOutputListeners) { + listener(message.payload as OutputChunk); + } + return; + } + + if (message.channel === WS_EVENT_CHANNELS.agentExit) { + for (const listener of this.agentExitListeners) { + listener(message.payload as AgentExit); + } + } + } + + private handleMessage(raw: unknown) { + let parsedRaw: unknown; + try { + parsedRaw = + typeof raw === "string" + ? JSON.parse(raw) + : JSON.parse(new TextDecoder().decode(raw as ArrayBuffer)); + } catch { + return; + } + + const parsed = wsServerMessageSchema.safeParse(parsedRaw); + if (!parsed.success) { + return; + } + + if (parsed.data.type === "response") { + this.handleResponse(parsed.data); + return; + } + + if (parsed.data.type === "event") { + this.handleEvent(parsed.data); + } + } + + asNativeApi(): NativeApi { + return { + app: { + bootstrap: async () => + this.request("app.bootstrap").then((value) => value as AppBootstrapResult), + }, + todos: { + list: async () => this.request("todos.list").then((value) => value as Awaited>), + add: async (input) => + this.request("todos.add", input).then((value) => value as Awaited>), + toggle: async (id) => + this.request("todos.toggle", id).then((value) => value as Awaited>), + remove: async (id) => + this.request("todos.remove", id).then((value) => value as Awaited>), + }, + dialogs: { + pickFolder: async () => + this.request("dialogs.pickFolder").then((value) => value as string | null), + }, + terminal: { + run: async (input) => + this.request("terminal.run", input).then((value) => value as Awaited>), + }, + agent: { + spawn: async (config) => + this.request("agent.spawn", config).then((value) => value as string), + kill: async (sessionId) => { + await this.request("agent.kill", sessionId); + }, + write: async (sessionId, data) => { + await this.request("agent.write", { sessionId, data }); + }, + onOutput: (callback) => { + this.agentOutputListeners.add(callback); + return () => { + this.agentOutputListeners.delete(callback); + }; + }, + onExit: (callback) => { + this.agentExitListeners.add(callback); + return () => { + this.agentExitListeners.delete(callback); + }; + }, + }, + providers: { + startSession: async (input) => + this.request("providers.startSession", input).then((value) => value as Awaited>), + sendTurn: async (input) => + this.request("providers.sendTurn", input).then((value) => value as Awaited>), + interruptTurn: async (input) => { + await this.request("providers.interruptTurn", input); + }, + respondToRequest: async (input) => { + await this.request("providers.respondToRequest", input); + }, + stopSession: async (input) => { + await this.request("providers.stopSession", input); + }, + listSessions: async () => + this.request("providers.listSessions").then((value) => value as Awaited>), + onEvent: (callback) => { + this.providerEventListeners.add(callback); + return () => { + this.providerEventListeners.delete(callback); + }; + }, + }, + shell: { + openInEditor: async (cwd, editor) => { + await this.request("shell.openInEditor", { cwd, editor }); + }, + }, + }; + } +} + +function resolveWsUrl() { + const params = new URLSearchParams(window.location.search); + return params.get("ws") ?? "ws://127.0.0.1:4317"; +} + +let cachedApi: NativeApi | undefined; + +export function getOrCreateWsNativeApi() { + if (cachedApi) { + return cachedApi; + } + + cachedApi = new WsNativeApiClient(resolveWsUrl()).asNativeApi(); + return cachedApi; +}