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