Skip to content

Commit 1531544

Browse files
committed
🤖 refactor: migrate IPC layer to ORPC for type-safe RPC
Replace Electron's loosely-typed ipcMain/ipcRenderer with ORPC, providing end-to-end type safety between frontend and backend. Key changes: - Add @orpc/client, @orpc/server, @orpc/zod dependencies - Create ORPC router (src/node/orpc/router.ts) with typed procedures - Add React ORPC provider and useORPC hook (src/browser/orpc/react.tsx) - Extract services: WorkspaceService, ProjectService, ProviderService, TokenizerService, TerminalService, WindowService, UpdateService - Replace window.api.* calls with typed client.* calls throughout frontend - Update test infrastructure to use ORPC test client (orpcTestClient.ts) - Switch Jest transform from ts-jest to babel-jest for ESM compatibility Breaking: Removes src/common/types/ipc.ts and src/common/constants/ipc-constants.ts in favor of src/common/orpc/types.ts and src/common/orpc/schemas.ts _Generated with mux_ Change-Id: Ibfeb8345e27baf663ca53ae04e4906621fda3b62 Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 refactor: complete ORPC migration Phase 5 cleanup - Delete obsolete src/browser/api.test.ts (tested legacy invokeIPC pattern) - Update src/desktop/preload.ts comment to reflect ORPC architecture - Remove unused StreamErrorType re-export from src/common/orpc/types.ts _Generated with mux_ Change-Id: I27a79252ee4256558f4aab8a3c4d60d7820d6599 Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: fix E2E test failures after ORPC migration 1. Fix ORPCProvider platform detection: check for window.api existence instead of window.api.platform === 'electron' (preload exposes process.platform which is 'darwin'/'win32'/'linux', not 'electron') 2. Fix E2E stream capture: replace assert() with inline throw since page.evaluate() stringifies code and loses import references _Generated with mux_ Change-Id: I9e4b35b830cea0d689845c2f4f2e68653f756e3d Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 test: fix E2E /compact test expectation Remove outdated '📦 compacted' expectation - the compaction feature now shows only summary text without the label marker. _Generated with mux_ Change-Id: Ic43a3dd9d099545a58832ebf60183775843f697f Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: migrate WorkspaceConsumerManager to use ORPC client for tokenization The tokenizer was still using the old window.api.tokenizer bridge which no longer exists after the ORPC migration. Updated to use window.__ORPC_CLIENT__.tokenizer instead. This fixes the repeated 'Tokenizer IPC bridge unavailable' assertion errors during E2E tests. Change-Id: I43820079337ca98e0dc97e863cde9414536d107f Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: fix flaky E2E toast tests with longer duration in E2E mode Changes: - Expose isE2E flag via preload to renderer for E2E-specific behavior - Increase toast auto-dismiss duration from 3s to 10s in E2E mode - Add sendCommandAndExpectStatus helper that waits for toast concurrently - Disable fullyParallel for Electron tests to avoid timing issues - Update tests to use new helper for reliable toast assertions The root cause was that toasts auto-dismiss after 3 seconds, but under parallel test execution the timing variance meant assertions could miss observing the toast before it disappeared. Change-Id: I Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: fix StreamCollector race condition in integration tests The StreamCollector was marking the subscription as ready immediately after getting the async iterator, but the ORPC generator body (which sets up the actual subscription) doesn't run until iteration starts. Changes: - Add waitForSubscription() method that waits for first event - Mark subscription as ready after receiving first event (from history replay) - Add small delay after subscription ready to stabilize under load - Update sendMessageAndWait to use the new synchronization This fixes flaky integration tests in runtimeFileEditing.test.ts where streaming events were sometimes missed due to the race condition. Change-Id: I1f697dbf9486a45c9335fd00c42fb54853715ed3 Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: restore native terminal opening for Electron desktop mode The ORPC migration inadvertently changed the terminal opening behavior: - Before: Clicking terminal button opened the user's native terminal app (Ghostty, Terminal.app, etc.) with cwd set to workspace path - After: It opened an xterm.js web terminal in an Electron popup window This restores the original behavior by: 1. Adding TerminalService.openNative() method with platform-specific logic: - macOS: Ghostty (if available) or Terminal.app - Windows: cmd.exe - Linux: x-terminal-emulator, ghostty, alacritty, kitty, etc. 2. Adding ORPC endpoint terminal.openNative for the new method 3. Updating useOpenTerminal hook to call openNative for Electron mode The web terminal (openWindow) is still available for browser mode. Added comprehensive unit tests to prevent this regression: - Tests for macOS Terminal.app and Ghostty detection - Tests for Windows cmd opening - Tests for Linux terminal emulator discovery - Tests for SSH workspace handling - Tests for error conditions Change-Id: Ib01af78cab49cb6ed3486eaaee85277f4b3daa15 Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: guard against undefined event.key in matchesKeybind Certain keyboard events (dead keys for accents, modifier-only events, etc.) can have event.key as undefined, causing a TypeError when calling toLowerCase(). Added defensive check to return false early when event.key is falsy. Added unit tests for the keybinds utility. Change-Id: I3784275ea2f0bd1206c548e3014854f259bc7a3e Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 refactor: rename IpcMain to ServiceContainer and fix review issues - Rename IpcMain class to ServiceContainer to reflect its actual purpose as a dependency container for ORPC services - Move tests/ipcMain/ to tests/integration/ for clarity - Fix provider config: empty string values now delete keys (allows clearing API keys) - Fix WorkspaceContext: add missing `client` dependency in createWorkspace - Fix schemas: add missing compacted/cmuxMetadata fields, remove stale entries - Fix updater: remove unused mainWindow field and setMainWindow method Change-Id: Iea939ecdcbb986f5a4f38a8cd2d7f250e8497dcf Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 fix: guard TitleBar against missing window.api in browser mode Change-Id: Ic6d1ddef2d3a9e3b047d1d6598e583d4ca345c57 Signed-off-by: Thomas Kosiewski <tk@coder.com> cleanup Change-Id: Ia6374d2f4e3696709536c93b2488d4bf0f3fda0f Signed-off-by: Thomas Kosiewski <tk@coder.com> 🤖 feat: add auth middleware to oRPC router Add bearer token authentication for HTTP and WebSocket endpoints using oRPC's native middleware pattern. Headers are injected into context at the transport layer, allowing a unified middleware to handle both. - Create authMiddleware.ts with createAuthMiddleware and extractWsHeaders - Update ORPCContext to include optional headers field - Apply auth middleware to router via t.use() - Inject headers into context in orpcServer.ts for HTTP and WS - Support WS auth fallbacks: query param, Authorization header, protocol Change-Id: Ief9b8b6d03d1f0161b996ac5d88ce2807e910c94 Signed-off-by: Thomas Kosiewski <tk@coder.com> fix: return actual path from listDirectory, not empty string The listDirectory function was using buildFileTree() which creates a synthetic root with name: '' and path: ''. This broke DirectoryPickerModal which relies on root.path for: - Displaying the current directory path in the UI - Computing parent directory via ${root.path}/.. - Returning the selected path to the caller Fixed by returning a FileTreeNode with the resolved absolute path as both name and path, matching the original IPC handler behavior. Added regression tests to prevent this from happening again. Change-Id: Iaddcbc3982c4f2440bcd92420e295881bf4fe90c Signed-off-by: Thomas Kosiewski <tk@coder.com>
1 parent a21aa5e commit 1531544

File tree

158 files changed

+12003
-11900
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

158 files changed

+12003
-11900
lines changed

.storybook/mocks/orpc.ts

Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
/**
2+
* Mock ORPC client factory for Storybook stories.
3+
*
4+
* Creates a client that matches the AppRouter interface with configurable mock data.
5+
*/
6+
import type { ORPCClient } from "@/browser/orpc/react";
7+
import type { FrontendWorkspaceMetadata } from "@/common/types/workspace";
8+
import type { ProjectConfig } from "@/node/config";
9+
import type { WorkspaceChatMessage } from "@/common/orpc/types";
10+
import type { ChatStats } from "@/common/types/chatStats";
11+
import { DEFAULT_RUNTIME_CONFIG } from "@/common/constants/workspace";
12+
13+
export interface MockORPCClientOptions {
14+
projects?: Map<string, ProjectConfig>;
15+
workspaces?: FrontendWorkspaceMetadata[];
16+
/** Per-workspace chat callback. Return messages to emit, or use the callback for streaming. */
17+
onChat?: (
18+
workspaceId: string,
19+
emit: (msg: WorkspaceChatMessage) => void
20+
) => (() => void) | void;
21+
/** Mock for executeBash per workspace */
22+
executeBash?: (
23+
workspaceId: string,
24+
script: string
25+
) => Promise<{ success: true; output: string; exitCode: number; wall_duration_ms: number }>;
26+
}
27+
28+
/**
29+
* Creates a mock ORPC client for Storybook.
30+
*
31+
* Usage:
32+
* ```tsx
33+
* const client = createMockORPCClient({
34+
* projects: new Map([...]),
35+
* workspaces: [...],
36+
* onChat: (wsId, emit) => {
37+
* emit({ type: "caught-up" });
38+
* // optionally return cleanup function
39+
* },
40+
* });
41+
*
42+
* return <AppLoader client={client} />;
43+
* ```
44+
*/
45+
export function createMockORPCClient(options: MockORPCClientOptions = {}): ORPCClient {
46+
const {
47+
projects = new Map(),
48+
workspaces = [],
49+
onChat,
50+
executeBash,
51+
} = options;
52+
53+
const workspaceMap = new Map(workspaces.map((w) => [w.id, w]));
54+
55+
const mockStats: ChatStats = {
56+
consumers: [],
57+
totalTokens: 0,
58+
model: "mock-model",
59+
tokenizerName: "mock-tokenizer",
60+
usageHistory: [],
61+
};
62+
63+
// Cast to ORPCClient - TypeScript can't fully validate the proxy structure
64+
return {
65+
tokenizer: {
66+
countTokens: async () => 0,
67+
countTokensBatch: async (_input: { model: string; texts: string[] }) =>
68+
_input.texts.map(() => 0),
69+
calculateStats: async () => mockStats,
70+
},
71+
server: {
72+
getLaunchProject: async () => null,
73+
},
74+
providers: {
75+
list: async () => [],
76+
getConfig: async () => ({}),
77+
setProviderConfig: async () => ({ success: true, data: undefined }),
78+
setModels: async () => ({ success: true, data: undefined }),
79+
},
80+
general: {
81+
listDirectory: async () => ({ entries: [], hasMore: false }),
82+
ping: async (input: string) => `Pong: ${input}`,
83+
tick: async function* () {
84+
// No-op generator
85+
},
86+
},
87+
projects: {
88+
list: async () => Array.from(projects.entries()),
89+
create: async () => ({
90+
success: true,
91+
data: { projectConfig: { workspaces: [] }, normalizedPath: "/mock/project" },
92+
}),
93+
pickDirectory: async () => null,
94+
listBranches: async () => ({
95+
branches: ["main", "develop"],
96+
recommendedTrunk: "main",
97+
}),
98+
remove: async () => ({ success: true, data: undefined }),
99+
secrets: {
100+
get: async () => [],
101+
update: async () => ({ success: true, data: undefined }),
102+
},
103+
},
104+
workspace: {
105+
list: async () => workspaces,
106+
create: async (input: { projectPath: string; branchName: string }) => ({
107+
success: true,
108+
metadata: {
109+
id: Math.random().toString(36).substring(2, 12),
110+
name: input.branchName,
111+
projectPath: input.projectPath,
112+
projectName: input.projectPath.split("/").pop() ?? "project",
113+
namedWorkspacePath: `/mock/workspace/${input.branchName}`,
114+
runtimeConfig: DEFAULT_RUNTIME_CONFIG,
115+
},
116+
}),
117+
remove: async () => ({ success: true }),
118+
rename: async (input: { workspaceId: string }) => ({
119+
success: true,
120+
data: { newWorkspaceId: input.workspaceId },
121+
}),
122+
fork: async () => ({ success: false, error: "Not implemented in mock" }),
123+
sendMessage: async () => ({ success: true, data: undefined }),
124+
resumeStream: async () => ({ success: true, data: undefined }),
125+
interruptStream: async () => ({ success: true, data: undefined }),
126+
clearQueue: async () => ({ success: true, data: undefined }),
127+
truncateHistory: async () => ({ success: true, data: undefined }),
128+
replaceChatHistory: async () => ({ success: true, data: undefined }),
129+
getInfo: async (input: { workspaceId: string }) => workspaceMap.get(input.workspaceId) ?? null,
130+
executeBash: async (input: { workspaceId: string; script: string }) => {
131+
if (executeBash) {
132+
const result = await executeBash(input.workspaceId, input.script);
133+
return { success: true, data: result };
134+
}
135+
return {
136+
success: true,
137+
data: { success: true, output: "", exitCode: 0, wall_duration_ms: 0 },
138+
};
139+
},
140+
onChat: async function* (input: { workspaceId: string }) {
141+
if (!onChat) {
142+
yield { type: "caught-up" } as WorkspaceChatMessage;
143+
return;
144+
}
145+
146+
// Create a queue-based async iterator
147+
const queue: WorkspaceChatMessage[] = [];
148+
let resolveNext: ((msg: WorkspaceChatMessage) => void) | null = null;
149+
let ended = false;
150+
151+
const emit = (msg: WorkspaceChatMessage) => {
152+
if (ended) return;
153+
if (resolveNext) {
154+
const resolve = resolveNext;
155+
resolveNext = null;
156+
resolve(msg);
157+
} else {
158+
queue.push(msg);
159+
}
160+
};
161+
162+
// Call the user's onChat handler
163+
const cleanup = onChat(input.workspaceId, emit);
164+
165+
try {
166+
while (!ended) {
167+
if (queue.length > 0) {
168+
yield queue.shift()!;
169+
} else {
170+
const msg = await new Promise<WorkspaceChatMessage>((resolve) => {
171+
resolveNext = resolve;
172+
});
173+
yield msg;
174+
}
175+
}
176+
} finally {
177+
ended = true;
178+
cleanup?.();
179+
}
180+
},
181+
onMetadata: async function* () {
182+
// Empty generator - no metadata updates in mock
183+
await new Promise(() => {}); // Never resolves, keeps stream open
184+
},
185+
activity: {
186+
list: async () => ({}),
187+
subscribe: async function* () {
188+
await new Promise(() => {}); // Never resolves
189+
},
190+
},
191+
},
192+
window: {
193+
setTitle: async () => undefined,
194+
},
195+
terminal: {
196+
create: async () => ({
197+
sessionId: "mock-session",
198+
workspaceId: "mock-workspace",
199+
cols: 80,
200+
rows: 24,
201+
}),
202+
close: async () => undefined,
203+
resize: async () => undefined,
204+
sendInput: () => undefined,
205+
onOutput: async function* () {
206+
await new Promise(() => {});
207+
},
208+
onExit: async function* () {
209+
await new Promise(() => {});
210+
},
211+
openWindow: async () => undefined,
212+
closeWindow: async () => undefined,
213+
openNative: async () => undefined,
214+
},
215+
update: {
216+
check: async () => undefined,
217+
download: async () => undefined,
218+
install: () => undefined,
219+
onStatus: async function* () {
220+
await new Promise(() => {});
221+
},
222+
},
223+
} as unknown as ORPCClient;
224+
}

.storybook/preview.tsx

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import React from "react";
1+
import React, { useMemo } from "react";
22
import type { Preview } from "@storybook/react-vite";
33
import { ThemeProvider, type ThemeMode } from "../src/browser/contexts/ThemeContext";
4+
import { ORPCProvider } from "../src/browser/orpc/react";
5+
import { createMockORPCClient } from "./mocks/orpc";
46
import "../src/browser/styles/globals.css";
57

68
const preview: Preview = {
@@ -22,6 +24,16 @@ const preview: Preview = {
2224
theme: "dark",
2325
},
2426
decorators: [
27+
// Global ORPC provider - ensures useORPC works in all stories
28+
(Story) => {
29+
const client = useMemo(() => createMockORPCClient(), []);
30+
return (
31+
<ORPCProvider client={client}>
32+
<Story />
33+
</ORPCProvider>
34+
);
35+
},
36+
// Theme provider
2537
(Story, context) => {
2638
// Default to dark if mode not set (e.g., Chromatic headless browser defaults to light)
2739
const mode = (context.globals.theme as ThemeMode | undefined) ?? "dark";

babel.config.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module.exports = {
2+
presets: [
3+
[
4+
"@babel/preset-env",
5+
{
6+
targets: {
7+
node: "current",
8+
},
9+
modules: "commonjs",
10+
},
11+
],
12+
[
13+
"@babel/preset-typescript",
14+
{
15+
allowDeclareFields: true,
16+
},
17+
],
18+
],
19+
};

0 commit comments

Comments
 (0)