Add renderer websocket native API adapter and bootstrap flow

Co-authored-by: Theo Browne <[email protected]>
This commit is contained in:
Cursor AgentandTheo Browne committed 2026-02-09 21:52:30 +00:00
1 parent 1f4ff504bb
commit cf568902cd
5 files changed
+380 -7

No files matched your search

+33 -4
View File
@@ -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<string | null>(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() {
<div className="drag-region h-[52px] shrink-0" />
<div className="flex flex-1 items-center justify-center">
<p className="text-sm text-muted-foreground">
Native bridge unavailable. Launch through Electron.
Local t3 runtime unavailable.
</p>
</div>
</div>
@@ -44,6 +72,7 @@ function Layout() {
return (
<div className="flex h-screen overflow-hidden bg-background text-foreground">
<BootstrapRouter />
<EventRouter />
<Sidebar />
<ChatView />
+2 -1
View File
@@ -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<string, unknown> | undefined {
+31
View File
@@ -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({
+70 -2
View File
@@ -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;
}
+244
View File
@@ -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<TValue> = Set<(value: TValue) => void>;
class WsNativeApiClient {
private socket: WebSocket | null = null;
private connectPromise: Promise<WebSocket> | null = null;
private nextRequestId = 1;
private pending = new Map<string, PendingRequest>();
private providerEventListeners: SubscriptionSet<ProviderEvent> = new Set();
private agentOutputListeners: SubscriptionSet<OutputChunk> = new Set();
private agentExitListeners: SubscriptionSet<AgentExit> = 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<WebSocket>((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<unknown>((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<ReturnType<NativeApi["todos"]["list"]>>),
add: async (input) =>
this.request("todos.add", input).then((value) => value as Awaited<ReturnType<NativeApi["todos"]["add"]>>),
toggle: async (id) =>
this.request("todos.toggle", id).then((value) => value as Awaited<ReturnType<NativeApi["todos"]["toggle"]>>),
remove: async (id) =>
this.request("todos.remove", id).then((value) => value as Awaited<ReturnType<NativeApi["todos"]["remove"]>>),
},
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<ReturnType<NativeApi["terminal"]["run"]>>),
},
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<ReturnType<NativeApi["providers"]["startSession"]>>),
sendTurn: async (input) =>
this.request("providers.sendTurn", input).then((value) => value as Awaited<ReturnType<NativeApi["providers"]["sendTurn"]>>),
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<ReturnType<NativeApi["providers"]["listSessions"]>>),
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;
}