Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

main.ts

349 lines9.0 KB

1import { fixPath } from "./fixPath";
2fixPath();
3​
4import { spawn } from "node:child_process";
5import path from "node:path";
6import { BrowserWindow, app, dialog, ipcMain, session, shell } from "electron";
7​
8import {
9 EDITORS,
10 IPC_CHANNELS,
11 type TerminalCommandInput,
12 type TerminalCommandResult,
13 agentConfigSchema,
14 agentSessionIdSchema,
15 newTodoInputSchema,
16 providerInterruptTurnInputSchema,
17 providerRespondToRequestInputSchema,
18 providerSendTurnInputSchema,
19 providerSessionStartInputSchema,
20 providerStopSessionInputSchema,
21 terminalCommandInputSchema,
22 todoIdSchema,
23} from "@acme/contracts";
24import { withParsedArgs, withParsedPayload } from "./ipcHelpers";
25import { ProcessManager } from "./processManager";
26import { ProviderManager } from "./providerManager";
27import { TodoStore } from "./todoStore";
28​
29const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
30​
31let todoStore: TodoStore;
32const processManager = new ProcessManager();
33const providerManager = new ProviderManager();
34const agentWriteArgsParser = {
35 parse(args: unknown[]): [string, string] {
36 const [sessionId, data] = args;
37 if (typeof data !== "string") {
38 throw new Error("agent:write data must be a string");
39 }
40​
41 return [agentSessionIdSchema.parse(sessionId), data];
42 },
43};
44​
45function createWindow(): BrowserWindow {
46 const window = new BrowserWindow({
47 width: 1100,
48 height: 780,
49 minWidth: 840,
50 minHeight: 620,
51 show: false,
52 autoHideMenuBar: true,
53 titleBarStyle: "hiddenInset",
54 trafficLightPosition: { x: 16, y: 18 },
55 webPreferences: {
56 preload: path.join(__dirname, "preload.js"),
57 contextIsolation: true,
58 nodeIntegration: false,
59 sandbox: true,
60 },
61 });
62​
63 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
64​
65 window.once("ready-to-show", () => {
66 window.show();
67 });
68​
69 setupEventForwarding(window);
70​
71 if (isDevelopment) {
72 void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
73 return window;
74 }
75​
76 void window.loadFile(path.join(__dirname, "../../renderer/dist/index.html"));
77 return window;
79​
80function registerIpcHandlers(): void {
81 // Todo handlers
82 ipcMain.handle(IPC_CHANNELS.todosList, async () => {
83 return todoStore.list();
84 });
85​
86 ipcMain.handle(
87 IPC_CHANNELS.todosAdd,
88 withParsedPayload(newTodoInputSchema, async (_event, payload) => {
89 return todoStore.add(payload);
90 }),
91 );
92​
93 ipcMain.handle(
94 IPC_CHANNELS.todosToggle,
95 withParsedPayload(todoIdSchema, async (_event, id) => {
96 return todoStore.toggle(id);
97 }),
98 );
99​
100 ipcMain.handle(
101 IPC_CHANNELS.todosRemove,
102 withParsedPayload(todoIdSchema, async (_event, id) => {
103 return todoStore.remove(id);
104 }),
105 );
106​
107 ipcMain.handle(IPC_CHANNELS.dialogPickFolder, async () => {
108 const owner = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];
109 const result = owner
110 ? await dialog.showOpenDialog(owner, {
111 properties: ["openDirectory", "createDirectory"],
112 })
113 : await dialog.showOpenDialog({
114 properties: ["openDirectory", "createDirectory"],
115 });
116​
117 if (result.canceled) return null;
118 return result.filePaths[0] ?? null;
119 });
120​
121 // Terminal handlers
122 ipcMain.handle(
123 IPC_CHANNELS.terminalRun,
124 withParsedPayload(terminalCommandInputSchema, async (_event, payload) => {
125 return runTerminalCommand(payload);
126 }),
127 );
128​
129 // Shell handlers
130 ipcMain.handle(
131 IPC_CHANNELS.shellOpenInEditor,
132 async (_event, cwd: string, editor: string) => {
133 if (!cwd) throw new Error("cwd is required");
134 const editorDef = EDITORS.find((e) => e.id === editor);
135 if (!editorDef) throw new Error(`Unknown editor: ${editor}`);
136 if (!editorDef.command) {
137 const error = await shell.openPath(cwd);
138 if (error) throw new Error(error);
139 return;
140 }
141 const child = spawn(editorDef.command, [cwd], {
142 detached: true,
143 stdio: "ignore",
144 });
145 child.on("error", () => {
146 /* ignore spawn failures for detached editors */
147 });
148 child.unref();
149 },
150 );
151​
152 // Agent handlers
153 ipcMain.handle(
154 IPC_CHANNELS.agentSpawn,
155 withParsedPayload(agentConfigSchema, async (_event, config) => {
156 return processManager.spawn(config);
157 }),
158 );
159​
160 ipcMain.handle(
161 IPC_CHANNELS.agentKill,
162 withParsedPayload(agentSessionIdSchema, async (_event, sessionId) => {
163 processManager.kill(sessionId);
164 }),
165 );
166​
167 ipcMain.handle(
168 IPC_CHANNELS.agentWrite,
169 withParsedArgs(agentWriteArgsParser, async (_event, sessionId, data) => {
170 processManager.write(sessionId, data);
171 }),
172 );
173​
174 // Provider handlers
175 ipcMain.handle(
176 IPC_CHANNELS.providerSessionStart,
177 withParsedPayload(providerSessionStartInputSchema, async (_event, payload) => {
178 return providerManager.startSession(payload);
179 }),
180 );
181​
182 ipcMain.handle(
183 IPC_CHANNELS.providerTurnStart,
184 withParsedPayload(providerSendTurnInputSchema, async (_event, payload) => {
185 return providerManager.sendTurn(payload);
186 }),
187 );
188​
189 ipcMain.handle(
190 IPC_CHANNELS.providerTurnInterrupt,
191 withParsedPayload(providerInterruptTurnInputSchema, async (_event, payload) => {
192 await providerManager.interruptTurn(payload);
193 }),
194 );
195​
196 ipcMain.handle(
197 IPC_CHANNELS.providerRequestRespond,
198 withParsedPayload(
199 providerRespondToRequestInputSchema,
200 async (_event, payload) => {
201 await providerManager.respondToRequest(payload);
202 },
203 ),
204 );
205​
206 ipcMain.handle(
207 IPC_CHANNELS.providerSessionStop,
208 withParsedPayload(providerStopSessionInputSchema, async (_event, payload) => {
209 providerManager.stopSession(payload);
210 }),
211 );
212​
213 ipcMain.handle(IPC_CHANNELS.providerSessionList, async () => {
214 return providerManager.listSessions();
215 });
217​
218async function runTerminalCommand(input: TerminalCommandInput): Promise<TerminalCommandResult> {
219 const shellPath =
220 process.platform === "win32"
221 ? (process.env.ComSpec ?? "cmd.exe")
222 : (process.env.SHELL ?? "/bin/sh");
223​
224 const args =
225 process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
226​
227 return new Promise((resolve, reject) => {
228 const child = spawn(shellPath, args, {
229 cwd: input.cwd,
230 env: process.env,
231 stdio: ["ignore", "pipe", "pipe"],
232 });
233​
234 let stdout = "";
235 let stderr = "";
236 let timedOut = false;
237​
238 const timeout = setTimeout(() => {
239 timedOut = true;
240 child.kill("SIGTERM");
241 setTimeout(() => {
242 if (!child.killed) {
243 child.kill("SIGKILL");
244 }
245 }, 1_000).unref();
246 }, input.timeoutMs ?? 30_000);
247​
248 child.stdout?.on("data", (chunk: Buffer) => {
249 stdout += chunk.toString();
250 });
251​
252 child.stderr?.on("data", (chunk: Buffer) => {
253 stderr += chunk.toString();
254 });
255​
256 child.on("error", (error) => {
257 clearTimeout(timeout);
258 reject(error);
259 });
260​
261 child.on("close", (code, signal) => {
262 clearTimeout(timeout);
263 resolve({
264 stdout,
265 stderr,
266 code: code ?? null,
267 signal: signal ?? null,
268 timedOut,
269 });
270 });
271 });
273​
274function setupEventForwarding(window: BrowserWindow): void {
275 const onOutput = (chunk: unknown) => {
276 if (!window.isDestroyed()) {
277 window.webContents.send(IPC_CHANNELS.agentOutput, chunk);
278 }
279 };
280​
281 const onExit = (exit: unknown) => {
282 if (!window.isDestroyed()) {
283 window.webContents.send(IPC_CHANNELS.agentExit, exit);
284 }
285 };
286​
287 const onProviderEvent = (event: unknown) => {
288 if (!window.isDestroyed()) {
289 window.webContents.send(IPC_CHANNELS.providerEvent, event);
290 }
291 };
292​
293 processManager.on("output", onOutput);
294 processManager.on("exit", onExit);
295 providerManager.on("event", onProviderEvent);
296​
297 window.on("closed", () => {
298 processManager.off("output", onOutput);
299 processManager.off("exit", onExit);
300 providerManager.off("event", onProviderEvent);
301 });
303​
304function setupCSP(): void {
305 session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
306 const csp = isDevelopment
307 ? "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://localhost:* http://localhost:*"
308 : "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'";
309​
310 callback({
311 responseHeaders: {
312 ...details.responseHeaders,
313 "Content-Security-Policy": [csp],
314 },
315 });
316 });
318​
319async function bootstrap(): Promise<void> {
320 setupCSP();
321​
322 todoStore = new TodoStore(path.join(app.getPath("userData"), "todos.json"));
323 await todoStore.init();
324​
325 registerIpcHandlers();
326 createWindow();
327​
328 app.on("activate", () => {
329 if (BrowserWindow.getAllWindows().length === 0) {
330 createWindow();
331 }
332 });
334​
335app.on("before-quit", () => {
336 processManager.killAll();
337 providerManager.stopAll();
338 providerManager.dispose();
339});
340​
341app.whenReady().then(() => {
342 void bootstrap();
343});
344​
345app.on("window-all-closed", () => {
346 if (process.platform !== "darwin") {
347 app.quit();
348 }
349});