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

wsServer.ts

691 lines21.0 KB

1/**
2 * Server - HTTP/WebSocket server service interface.
3 *
4 * Owns startup and shutdown lifecycle of the HTTP server, static asset serving,
5 * and WebSocket request routing.
6 *
7 * @module Server
8 */
9import fs from "node:fs";
10import http from "node:http";
11import path from "node:path";
12import type { Duplex } from "node:stream";
13​
14import {
15 CommandId,
16 ORCHESTRATION_WS_CHANNELS,
17 ORCHESTRATION_WS_METHODS,
18 ProjectId,
19 ThreadId,
20 TerminalEvent,
21 WS_CHANNELS,
22 WS_METHODS,
23 WebSocketRequest,
24 WsPush,
25 WsResponse,
26} from "@t3tools/contracts";
27import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
28import { Cause, Effect, Exit, Layer, Ref, Schema, Scope, ServiceMap, Stream, Struct } from "effect";
29import { WebSocketServer, type WebSocket } from "ws";
30​
31import { createLogger } from "./logger";
32import { GitManager } from "./git/Services/GitManager.ts";
33import { TerminalManager } from "./terminal/Services/Manager.ts";
34import { Keybindings } from "./keybindings";
35import { searchWorkspaceEntries } from "./workspaceEntries";
36import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
37import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
38import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
39import { ProviderService } from "./provider/Services/ProviderService";
40import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
41import { clamp } from "effect/Number";
42import { Open } from "./open";
43import { ServerConfig } from "./config";
44import { GitCore } from "./git/Services/GitCore.ts";
45​
46const MIME_TYPES: Record<string, string> = {
47 ".html": "text/html; charset=utf-8",
48 ".js": "application/javascript; charset=utf-8",
49 ".css": "text/css; charset=utf-8",
50 ".json": "application/json; charset=utf-8",
51 ".png": "image/png",
52 ".jpg": "image/jpeg",
53 ".svg": "image/svg+xml",
54 ".ico": "image/x-icon",
55 ".woff": "font/woff",
56 ".woff2": "font/woff2",
57 ".ttf": "font/ttf",
58 ".map": "application/json",
59};
60​
61/**
62 * ServerShape - Service API for server lifecycle control.
63 */
64export interface ServerShape {
65 /**
66 * Start HTTP and WebSocket listeners.
67 */
68 readonly start: Effect.Effect<
69 http.Server,
70 ServerLifecycleError,
71 Scope.Scope | ServerRuntimeServices | ServerConfig
72 >;
73​
74 /**
75 * Wait for process shutdown signals.
76 */
77 readonly stopSignal: Effect.Effect<void, never>;
79​
80/**
81 * Server - Service tag for HTTP/WebSocket lifecycle management.
82 */
83export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
84​
85const isServerNotRunningError = (error: unknown): boolean => {
86 if (!(error instanceof Error)) return false;
87 const maybeCode = (error as NodeJS.ErrnoException).code;
88 return (
89 maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
90 );
91};
92​
93function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
94 socket.end(
95 `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
96 "Connection: close\r\n" +
97 "Content-Type: text/plain\r\n" +
98 `Content-Length: ${Buffer.byteLength(message)}\r\n` +
99 "\r\n" +
100 message,
101 );
103​
104function websocketRawToString(raw: unknown): string | null {
105 if (typeof raw === "string") {
106 return raw;
107 }
108 if (raw instanceof Uint8Array) {
109 return Buffer.from(raw).toString("utf8");
110 }
111 if (raw instanceof ArrayBuffer) {
112 return Buffer.from(new Uint8Array(raw)).toString("utf8");
113 }
114 if (Array.isArray(raw)) {
115 const chunks: string[] = [];
116 for (const chunk of raw) {
117 if (typeof chunk === "string") {
118 chunks.push(chunk);
119 continue;
120 }
121 if (chunk instanceof Uint8Array) {
122 chunks.push(Buffer.from(chunk).toString("utf8"));
123 continue;
124 }
125 if (chunk instanceof ArrayBuffer) {
126 chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
127 continue;
128 }
129 return null;
130 }
131 return chunks.join("");
132 }
133 return null;
135​
136function stripRequestTag<T extends { _tag: string }>(body: T) {
137 return Struct.omit(body, ["_tag"]);
139​
140export type ServerCoreRuntimeServices =
141 | OrchestrationEngineService
142 | ProjectionSnapshotQuery
143 | CheckpointDiffQuery
144 | OrchestrationReactor
145 | ProviderService;
146​
147export type ServerRuntimeServices =
148 | ServerCoreRuntimeServices
149 | GitManager
150 | GitCore
151 | TerminalManager
152 | Keybindings
153 | Open;
154​
155export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
156 "ServerLifecycleError",
157 {
158 operation: Schema.String,
159 cause: Schema.optional(Schema.Defect),
160 },
161) {}
162​
163class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("RouteRequestError", {
164 message: Schema.String,
165}) {}
166​
167export const createServer = Effect.fn(function* (): Effect.fn.Return<
168 http.Server,
169 ServerLifecycleError,
170 Scope.Scope | ServerRuntimeServices | ServerConfig
171> {
172 const serverConfig = yield* ServerConfig;
173 const {
174 port,
175 cwd,
176 keybindingsConfigPath,
177 staticDir,
178 devUrl,
179 authToken,
180 host,
181 logWebSocketEvents,
182 autoBootstrapProjectFromCwd,
183 } = serverConfig;
184​
185 const gitManager = yield* GitManager;
186 const terminalManager = yield* TerminalManager;
187 const keybindingsManager = yield* Keybindings;
188 const git = yield* GitCore;
189​
190 yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
191 Effect.catch((error) =>
192 Effect.logWarning("failed to sync keybindings defaults on startup", {
193 path: error.configPath,
194 detail: error.detail,
195 cause: error.cause,
196 }),
197 ),
198 );
199​
200 const clients = yield* Ref.make(new Set<WebSocket>());
201 const logger = createLogger("ws");
202​
203 function logOutgoingPush(push: WsPush, recipients: number) {
204 if (!logWebSocketEvents) return;
205 logger.event("outgoing push", {
206 channel: push.channel,
207 recipients,
208 payload: push.data,
209 });
210 }
211​
212 const encodePush = Schema.encodeEffect(Schema.fromJsonString(WsPush));
213 const broadcastPush = Effect.fnUntraced(function* (push: WsPush) {
214 const message = yield* encodePush(push);
215 let recipients = 0;
216 for (const client of yield* Ref.get(clients)) {
217 if (client.readyState === client.OPEN) {
218 client.send(message);
219 recipients += 1;
220 }
221 }
222 logOutgoingPush(push, recipients);
223 });
224​
225 const onTerminalEvent = Effect.fnUntraced(function* (event: TerminalEvent) {
226 yield* broadcastPush({
227 type: "push",
228 channel: WS_CHANNELS.terminalEvent,
229 data: event,
230 });
231 });
232​
233 // HTTP server — serves static files or redirects to Vite dev server
234 const httpServer = http.createServer((req, res) => {
235 // In dev mode, redirect to Vite dev server
236 if (devUrl) {
237 res.writeHead(302, { Location: devUrl.href });
238 res.end();
239 return;
240 }
241​
242 // Serve static files from the web app build
243 if (!staticDir) {
244 res.writeHead(503, { "Content-Type": "text/plain" });
245 res.end("No static directory configured and no dev URL set.");
246 return;
247 }
248​
249 const url = new URL(req.url ?? "/", `http://localhost:${port}`);
250 let filePath = path.join(staticDir, url.pathname);
251​
252 // SPA fallback: if no file extension and not found, serve index.html
253 const ext = path.extname(filePath);
254 if (!ext) {
255 filePath = path.join(filePath, "index.html");
256 }
257​
258 fs.stat(filePath, (err, stats) => {
259 if (err || !stats?.isFile()) {
260 // SPA fallback
261 const indexPath = path.join(staticDir, "index.html");
262 fs.readFile(indexPath, (readErr, data) => {
263 if (readErr) {
264 res.writeHead(404, { "Content-Type": "text/plain" });
265 res.end("Not Found");
266 return;
267 }
268 res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
269 res.end(data);
270 });
271 return;
272 }
273​
274 const fileExt = path.extname(filePath);
275 const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
276​
277 fs.readFile(filePath, (readErr, data) => {
278 if (readErr) {
279 res.writeHead(500, { "Content-Type": "text/plain" });
280 res.end("Internal Server Error");
281 return;
282 }
283 res.writeHead(200, { "Content-Type": contentType });
284 res.end(data);
285 });
286 });
287 });
288​
289 // WebSocket server — upgrades from the HTTP server
290 const wss = new WebSocketServer({ noServer: true });
291​
292 const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => {
293 wss.close((error) => {
294 if (error && !isServerNotRunningError(error)) {
295 resume(
296 Effect.fail(
297 new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }),
298 ),
299 );
300 } else {
301 resume(Effect.void);
302 }
303 });
304 });
305​
306 const closeAllClients = Ref.get(clients).pipe(
307 Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))),
308 Effect.flatMap(() => Ref.set(clients, new Set())),
309 );
310​
311 const listenOptions = host ? { host, port } : { port };
312​
313 const orchestrationEngine = yield* OrchestrationEngineService;
314 const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
315 const checkpointDiffQuery = yield* CheckpointDiffQuery;
316 const liveProviderService = yield* ProviderService;
317 const orchestrationReactor = yield* OrchestrationReactor;
318 const { openInEditor } = yield* Open;
319​
320 const subscriptionsScope = yield* Scope.make("sequential");
321 yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
322​
323 yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
324 broadcastPush({
325 type: "push",
326 channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
327 data: event,
328 }),
329 ).pipe(Effect.forkIn(subscriptionsScope));
330​
331 yield* Stream.runForEach(keybindingsManager.changes, (event) =>
332 broadcastPush({
333 type: "push",
334 channel: WS_CHANNELS.serverConfigUpdated,
335 data: event,
336 }),
337 ).pipe(Effect.forkIn(subscriptionsScope));
338​
339 yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
340​
341 let welcomeBootstrapProjectId: ProjectId | undefined;
342 let welcomeBootstrapThreadId: ThreadId | undefined;
343​
344 if (autoBootstrapProjectFromCwd) {
345 yield* Effect.gen(function* () {
346 const snapshot = yield* projectionReadModelQuery.getSnapshot();
347 const existingProject = snapshot.projects.find(
348 (project) => project.workspaceRoot === cwd && project.deletedAt === null,
349 );
350 let bootstrapProjectId: ProjectId;
351 let bootstrapProjectDefaultModel: string;
352​
353 if (!existingProject) {
354 const createdAt = new Date().toISOString();
355 bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
356 const bootstrapProjectTitle = path.basename(cwd) || "project";
357 bootstrapProjectDefaultModel = "gpt-5-codex";
358 yield* orchestrationEngine.dispatch({
359 type: "project.create",
360 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
361 projectId: bootstrapProjectId,
362 title: bootstrapProjectTitle,
363 workspaceRoot: cwd,
364 defaultModel: bootstrapProjectDefaultModel,
365 createdAt,
366 });
367 } else {
368 bootstrapProjectId = existingProject.id;
369 bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
370 }
371​
372 const existingThread = snapshot.threads.find(
373 (thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
374 );
375 if (!existingThread) {
376 const createdAt = new Date().toISOString();
377 const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
378 yield* orchestrationEngine.dispatch({
379 type: "thread.create",
380 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
381 threadId,
382 projectId: bootstrapProjectId,
383 title: "New thread",
384 model: bootstrapProjectDefaultModel,
385 branch: null,
386 worktreePath: null,
387 createdAt,
388 });
389 welcomeBootstrapProjectId = bootstrapProjectId;
390 welcomeBootstrapThreadId = threadId;
391 } else {
392 welcomeBootstrapProjectId = bootstrapProjectId;
393 welcomeBootstrapThreadId = existingThread.id;
394 }
395 }).pipe(
396 Effect.mapError(
397 (cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
398 ),
399 );
400 }
401​
402 const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
403 switch (request.body._tag) {
404 case ORCHESTRATION_WS_METHODS.getSnapshot:
405 return yield* projectionReadModelQuery.getSnapshot();
406​
407 case ORCHESTRATION_WS_METHODS.dispatchCommand: {
408 const { command } = request.body;
409 return yield* orchestrationEngine.dispatch(command);
410 }
411​
412 case ORCHESTRATION_WS_METHODS.getTurnDiff: {
413 const body = stripRequestTag(request.body);
414 return yield* checkpointDiffQuery.getTurnDiff(body);
415 }
416​
417 case ORCHESTRATION_WS_METHODS.getFullThreadDiff: {
418 const body = stripRequestTag(request.body);
419 return yield* checkpointDiffQuery.getFullThreadDiff(body);
420 }
421​
422 case ORCHESTRATION_WS_METHODS.replayEvents: {
423 const { fromSequenceExclusive } = request.body;
424 return yield* Stream.runCollect(
425 orchestrationEngine.readEvents(
426 clamp(fromSequenceExclusive, {
427 maximum: Number.MAX_SAFE_INTEGER,
428 minimum: 0,
429 }),
430 ),
431 ).pipe(Effect.map((events) => Array.from(events)));
432 }
433​
434 case WS_METHODS.projectsSearchEntries: {
435 const body = stripRequestTag(request.body);
436 return yield* Effect.tryPromise({
437 try: () => searchWorkspaceEntries(body),
438 catch: (cause) =>
439 new RouteRequestError({
440 message: `Failed to search workspace entries: ${String(cause)}`,
441 }),
442 });
443 }
444​
445 case WS_METHODS.shellOpenInEditor: {
446 const body = stripRequestTag(request.body);
447 return yield* openInEditor(body);
448 }
449​
450 case WS_METHODS.gitStatus: {
451 const body = stripRequestTag(request.body);
452 return yield* gitManager.status(body);
453 }
454​
455 case WS_METHODS.gitPull: {
456 const body = stripRequestTag(request.body);
457 return yield* git.pullCurrentBranch(body.cwd);
458 }
459​
460 case WS_METHODS.gitRunStackedAction: {
461 const body = stripRequestTag(request.body);
462 return yield* gitManager.runStackedAction(body);
463 }
464​
465 case WS_METHODS.gitListBranches: {
466 const body = stripRequestTag(request.body);
467 return yield* git.listBranches(body);
468 }
469​
470 case WS_METHODS.gitCreateWorktree: {
471 const body = stripRequestTag(request.body);
472 return yield* git.createWorktree(body);
473 }
474​
475 case WS_METHODS.gitRemoveWorktree: {
476 const body = stripRequestTag(request.body);
477 return yield* git.removeWorktree(body);
478 }
479​
480 case WS_METHODS.gitCreateBranch: {
481 const body = stripRequestTag(request.body);
482 return yield* git.createBranch(body);
483 }
484​
485 case WS_METHODS.gitCheckout: {
486 const body = stripRequestTag(request.body);
487 return yield* git.checkoutBranch(body);
488 }
489​
490 case WS_METHODS.gitInit: {
491 const body = stripRequestTag(request.body);
492 return yield* git.initRepo(body);
493 }
494​
495 case WS_METHODS.terminalOpen: {
496 const body = stripRequestTag(request.body);
497 return yield* terminalManager.open(body);
498 }
499​
500 case WS_METHODS.terminalWrite: {
501 const body = stripRequestTag(request.body);
502 return yield* terminalManager.write(body);
503 }
504​
505 case WS_METHODS.terminalResize: {
506 const body = stripRequestTag(request.body);
507 return yield* terminalManager.resize(body);
508 }
509​
510 case WS_METHODS.terminalClear: {
511 const body = stripRequestTag(request.body);
512 return yield* terminalManager.clear(body);
513 }
514​
515 case WS_METHODS.terminalRestart: {
516 const body = stripRequestTag(request.body);
517 return yield* terminalManager.restart(body);
518 }
519​
520 case WS_METHODS.terminalClose: {
521 const body = stripRequestTag(request.body);
522 return yield* terminalManager.close(body);
523 }
524​
525 case WS_METHODS.serverGetConfig:
526 const keybindingsConfig = yield* keybindingsManager.loadConfigState;
527 return {
528 cwd,
529 keybindingsConfigPath,
530 keybindings: keybindingsConfig.keybindings,
531 issues: keybindingsConfig.issues,
532 };
533​
534 case WS_METHODS.serverUpsertKeybinding: {
535 const body = stripRequestTag(request.body);
536 const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
537 return { keybindings: keybindingsConfig, issues: [] };
538 }
539​
540 default: {
541 const _exhaustiveCheck: never = request.body;
542 return yield* new RouteRequestError({
543 message: `Unknown method: ${String(_exhaustiveCheck)}`,
544 });
545 }
546 }
547 });
548​
549 const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
550 const encodeResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
551​
552 const messageText = websocketRawToString(raw);
553 if (messageText === null) {
554 const errorResponse = yield* encodeResponse({
555 id: "unknown",
556 error: { message: "Invalid request format: Failed to read message" },
557 });
558 ws.send(errorResponse);
559 return;
560 }
561​
562 const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText);
563 if (request._tag === "Failure") {
564 const errorResponse = yield* encodeResponse({
565 id: "unknown",
566 error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
567 });
568 ws.send(errorResponse);
569 return;
570 }
571​
572 const result = yield* Effect.exit(routeRequest(request.value));
573 if (result._tag === "Failure") {
574 const errorResponse = yield* encodeResponse({
575 id: request.value.id,
576 error: { message: Cause.pretty(result.cause) },
577 });
578 ws.send(errorResponse);
579 return;
580 }
581​
582 const response = yield* encodeResponse({
583 id: request.value.id,
584 result: result.value,
585 });
586 ws.send(response);
587 });
588​
589 httpServer.on("upgrade", (request, socket, head) => {
590 socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
591​
592 if (authToken) {
593 let providedToken: string | null = null;
594 try {
595 const url = new URL(request.url ?? "/", `http://localhost:${port}`);
596 providedToken = url.searchParams.get("token");
597 } catch {
598 rejectUpgrade(socket, 400, "Invalid WebSocket URL");
599 return;
600 }
601​
602 if (providedToken !== authToken) {
603 rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
604 return;
605 }
606 }
607​
608 wss.handleUpgrade(request, socket, head, (ws) => {
609 wss.emit("connection", ws, request);
610 });
611 });
612​
613 wss.on("connection", (ws) => {
614 void Effect.runPromise(Ref.update(clients, (clients) => clients.add(ws)));
615​
616 const segments = cwd.split(/[/\\]/).filter(Boolean);
617 const projectName = segments[segments.length - 1] ?? "project";
618​
619 const welcome: WsPush = {
620 type: "push",
621 channel: WS_CHANNELS.serverWelcome,
622 data: {
623 cwd,
624 projectName,
625 ...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
626 ...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
627 },
628 };
629 logOutgoingPush(welcome, 1);
630 ws.send(JSON.stringify(welcome));
631​
632 ws.on("message", (raw) => {
633 void Effect.runPromise(
634 handleMessage(ws, raw).pipe(
635 Effect.catch((error) => Effect.logError("Error handling message", error)),
636 ),
637 );
638 });
639​
640 ws.on("close", () => {
641 void Effect.runPromise(
642 Ref.update(clients, (clients) => {
643 clients.delete(ws);
644 return clients;
645 }),
646 );
647 });
648​
649 ws.on("error", () => {
650 void Effect.runPromise(
651 Ref.update(clients, (clients) => {
652 clients.delete(ws);
653 return clients;
654 }),
655 );
656 });
657 });
658​
659 yield* Effect.addFinalizer(() =>
660 Effect.catch(liveProviderService.stopAll(), (cause) =>
661 Effect.logWarning("failed to stop provider service", { cause }),
662 ),
663 );
664​
665 const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
666 (event) => void Effect.runPromise(onTerminalEvent(event)),
667 );
668 yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
669​
670 yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
671 Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
672 );
673​
674 yield* Effect.addFinalizer(() =>
675 Effect.all([
676 closeAllClients,
677 closeWebSocketServer.pipe(
678 Effect.catch((error) =>
679 Effect.logWarning("failed to close web socket server", { cause: error }),
680 ),
681 ),
682 ]),
683 );
684​
685 return httpServer;
686});
687​
688export const ServerLive = Layer.succeed(Server, {
689 start: createServer(),
690 stopSignal: Effect.never,
691} satisfies ServerShape);