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

ws.ts

785 lines30.6 KB

1import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
2import {
3 CommandId,
4 EventId,
5 type OrchestrationCommand,
6 type GitActionProgressEvent,
7 type GitManagerServiceError,
8 OrchestrationDispatchCommandError,
9 type OrchestrationEvent,
10 OrchestrationGetFullThreadDiffError,
11 OrchestrationGetSnapshotError,
12 OrchestrationGetTurnDiffError,
13 ORCHESTRATION_WS_METHODS,
14 ProjectSearchEntriesError,
15 ProjectWriteFileError,
16 OrchestrationReplayEventsError,
17 ThreadId,
18 type TerminalEvent,
19 WS_METHODS,
20 WsRpcGroup,
21} from "@t3tools/contracts";
22import { clamp } from "effect/Number";
23import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
24import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
25​
26import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
27import { ServerConfig } from "./config";
28import { GitCore } from "./git/Services/GitCore";
29import { GitManager } from "./git/Services/GitManager";
30import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster";
31import { Keybindings } from "./keybindings";
32import { Open, resolveAvailableEditors } from "./open";
33import { normalizeDispatchCommand } from "./orchestration/Normalizer";
34import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
35import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
36import {
37 observeRpcEffect,
38 observeRpcStream,
39 observeRpcStreamEffect,
40} from "./observability/RpcInstrumentation";
41import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
42import { ServerLifecycleEvents } from "./serverLifecycleEvents";
43import { ServerRuntimeStartup } from "./serverRuntimeStartup";
44import { ServerSettingsService } from "./serverSettings";
45import { TerminalManager } from "./terminal/Services/Manager";
46import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries";
47import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem";
48import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths";
49import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner";
50​
51const WsRpcLayer = WsRpcGroup.toLayer(
52 Effect.gen(function* () {
53 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
54 const orchestrationEngine = yield* OrchestrationEngineService;
55 const checkpointDiffQuery = yield* CheckpointDiffQuery;
56 const keybindings = yield* Keybindings;
57 const open = yield* Open;
58 const gitManager = yield* GitManager;
59 const git = yield* GitCore;
60 const gitStatusBroadcaster = yield* GitStatusBroadcaster;
61 const terminalManager = yield* TerminalManager;
62 const providerRegistry = yield* ProviderRegistry;
63 const config = yield* ServerConfig;
64 const lifecycleEvents = yield* ServerLifecycleEvents;
65 const serverSettings = yield* ServerSettingsService;
66 const startup = yield* ServerRuntimeStartup;
67 const workspaceEntries = yield* WorkspaceEntries;
68 const workspaceFileSystem = yield* WorkspaceFileSystem;
69 const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
70 const serverCommandId = (tag: string) =>
71 CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
72​
73 const appendSetupScriptActivity = (input: {
74 readonly threadId: ThreadId;
75 readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed";
76 readonly summary: string;
77 readonly createdAt: string;
78 readonly payload: Record<string, unknown>;
79 readonly tone: "info" | "error";
80 }) =>
81 orchestrationEngine.dispatch({
82 type: "thread.activity.append",
83 commandId: serverCommandId("setup-script-activity"),
84 threadId: input.threadId,
85 activity: {
86 id: EventId.makeUnsafe(crypto.randomUUID()),
87 tone: input.tone,
88 kind: input.kind,
89 summary: input.summary,
90 payload: input.payload,
91 turnId: null,
92 createdAt: input.createdAt,
93 },
94 createdAt: input.createdAt,
95 });
96​
97 const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
98 Schema.is(OrchestrationDispatchCommandError)(cause)
99 ? cause
100 : new OrchestrationDispatchCommandError({
101 message: cause instanceof Error ? cause.message : fallbackMessage,
102 cause,
103 });
104​
105 const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
106 const error = Cause.squash(cause);
107 return Schema.is(OrchestrationDispatchCommandError)(error)
108 ? error
109 : new OrchestrationDispatchCommandError({
110 message:
111 error instanceof Error ? error.message : "Failed to bootstrap thread turn start.",
112 cause,
113 });
114 };
115​
116 const dispatchBootstrapTurnStart = (
117 command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
118 ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
119 Effect.gen(function* () {
120 const bootstrap = command.bootstrap;
121 const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;
122 let createdThread = false;
123 let targetProjectId = bootstrap?.createThread?.projectId;
124 let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;
125 let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;
126​
127 const cleanupCreatedThread = () =>
128 createdThread
129 ? orchestrationEngine
130 .dispatch({
131 type: "thread.delete",
132 commandId: serverCommandId("bootstrap-thread-delete"),
133 threadId: command.threadId,
134 })
135 .pipe(Effect.ignoreCause({ log: true }))
136 : Effect.void;
137​
138 const recordSetupScriptLaunchFailure = (input: {
139 readonly error: unknown;
140 readonly requestedAt: string;
141 readonly worktreePath: string;
142 }) => {
143 const detail =
144 input.error instanceof Error ? input.error.message : "Unknown setup failure.";
145 return appendSetupScriptActivity({
146 threadId: command.threadId,
147 kind: "setup-script.failed",
148 summary: "Setup script failed to start",
149 createdAt: input.requestedAt,
150 payload: {
151 detail,
152 worktreePath: input.worktreePath,
153 },
154 tone: "error",
155 }).pipe(
156 Effect.ignoreCause({ log: false }),
157 Effect.flatMap(() =>
158 Effect.logWarning("bootstrap turn start failed to launch setup script", {
159 threadId: command.threadId,
160 worktreePath: input.worktreePath,
161 detail,
162 }),
163 ),
164 );
165 };
166​
167 const recordSetupScriptStarted = (input: {
168 readonly requestedAt: string;
169 readonly worktreePath: string;
170 readonly scriptId: string;
171 readonly scriptName: string;
172 readonly terminalId: string;
173 }) => {
174 const payload = {
175 scriptId: input.scriptId,
176 scriptName: input.scriptName,
177 terminalId: input.terminalId,
178 worktreePath: input.worktreePath,
179 };
180 return Effect.all([
181 appendSetupScriptActivity({
182 threadId: command.threadId,
183 kind: "setup-script.requested",
184 summary: "Starting setup script",
185 createdAt: input.requestedAt,
186 payload,
187 tone: "info",
188 }),
189 appendSetupScriptActivity({
190 threadId: command.threadId,
191 kind: "setup-script.started",
192 summary: "Setup script started",
193 createdAt: new Date().toISOString(),
194 payload,
195 tone: "info",
196 }),
197 ]).pipe(
198 Effect.asVoid,
199 Effect.catch((error) =>
200 Effect.logWarning(
201 "bootstrap turn start launched setup script but failed to record setup activity",
202 {
203 threadId: command.threadId,
204 worktreePath: input.worktreePath,
205 scriptId: input.scriptId,
206 terminalId: input.terminalId,
207 detail:
208 error instanceof Error
209 ? error.message
210 : "Unknown setup activity dispatch failure.",
211 },
212 ),
213 ),
214 );
215 };
216​
217 const runSetupProgram = () =>
218 bootstrap?.runSetupScript && targetWorktreePath
219 ? (() => {
220 const worktreePath = targetWorktreePath;
221 const requestedAt = new Date().toISOString();
222 return projectSetupScriptRunner
223 .runForThread({
224 threadId: command.threadId,
225 ...(targetProjectId ? { projectId: targetProjectId } : {}),
226 ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),
227 worktreePath,
228 })
229 .pipe(
230 Effect.matchEffect({
231 onFailure: (error) =>
232 recordSetupScriptLaunchFailure({
233 error,
234 requestedAt,
235 worktreePath,
236 }),
237 onSuccess: (setupResult) => {
238 if (setupResult.status !== "started") {
239 return Effect.void;
240 }
241 return recordSetupScriptStarted({
242 requestedAt,
243 worktreePath,
244 scriptId: setupResult.scriptId,
245 scriptName: setupResult.scriptName,
246 terminalId: setupResult.terminalId,
247 });
248 },
249 }),
250 );
251 })()
252 : Effect.void;
253​
254 const bootstrapProgram = Effect.gen(function* () {
255 if (bootstrap?.createThread) {
256 yield* orchestrationEngine.dispatch({
257 type: "thread.create",
258 commandId: serverCommandId("bootstrap-thread-create"),
259 threadId: command.threadId,
260 projectId: bootstrap.createThread.projectId,
261 title: bootstrap.createThread.title,
262 modelSelection: bootstrap.createThread.modelSelection,
263 runtimeMode: bootstrap.createThread.runtimeMode,
264 interactionMode: bootstrap.createThread.interactionMode,
265 branch: bootstrap.createThread.branch,
266 worktreePath: bootstrap.createThread.worktreePath,
267 createdAt: bootstrap.createThread.createdAt,
268 });
269 createdThread = true;
270 }
271​
272 if (bootstrap?.prepareWorktree) {
273 const worktree = yield* git.createWorktree({
274 cwd: bootstrap.prepareWorktree.projectCwd,
275 branch: bootstrap.prepareWorktree.baseBranch,
276 newBranch: bootstrap.prepareWorktree.branch,
277 path: null,
278 });
279 targetWorktreePath = worktree.worktree.path;
280 yield* orchestrationEngine.dispatch({
281 type: "thread.meta.update",
282 commandId: serverCommandId("bootstrap-thread-meta-update"),
283 threadId: command.threadId,
284 branch: worktree.worktree.branch,
285 worktreePath: targetWorktreePath,
286 });
287 }
288​
289 yield* runSetupProgram();
290​
291 return yield* orchestrationEngine.dispatch(finalTurnStartCommand);
292 });
293​
294 return yield* bootstrapProgram.pipe(
295 Effect.catchCause((cause) => {
296 const dispatchError = toBootstrapDispatchCommandCauseError(cause);
297 if (Cause.hasInterruptsOnly(cause)) {
298 return Effect.fail(dispatchError);
299 }
300 return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));
301 }),
302 );
303 });
304​
305 const dispatchNormalizedCommand = (
306 normalizedCommand: OrchestrationCommand,
307 ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {
308 const dispatchEffect =
309 normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap
310 ? dispatchBootstrapTurnStart(normalizedCommand)
311 : orchestrationEngine
312 .dispatch(normalizedCommand)
313 .pipe(
314 Effect.mapError((cause) =>
315 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
316 ),
317 );
318​
319 return startup
320 .enqueueCommand(dispatchEffect)
321 .pipe(
322 Effect.mapError((cause) =>
323 toDispatchCommandError(cause, "Failed to dispatch orchestration command"),
324 ),
325 );
326 };
327​
328 const loadServerConfig = Effect.gen(function* () {
329 const keybindingsConfig = yield* keybindings.loadConfigState;
330 const providers = yield* providerRegistry.getProviders;
331 const settings = yield* serverSettings.getSettings;
332​
333 return {
334 cwd: config.cwd,
335 keybindingsConfigPath: config.keybindingsConfigPath,
336 keybindings: keybindingsConfig.keybindings,
337 issues: keybindingsConfig.issues,
338 providers,
339 availableEditors: resolveAvailableEditors(),
340 observability: {
341 logsDirectoryPath: config.logsDir,
342 localTracingEnabled: true,
343 ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),
344 otlpTracesEnabled: config.otlpTracesUrl !== undefined,
345 ...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}),
346 otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,
347 },
348 settings,
349 };
350 });
351​
352 const refreshGitStatus = (cwd: string) =>
353 gitStatusBroadcaster
354 .refreshStatus(cwd)
355 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
356​
357 return WsRpcGroup.of({
358 [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) =>
359 observeRpcEffect(
360 ORCHESTRATION_WS_METHODS.getSnapshot,
361 projectionSnapshotQuery.getSnapshot().pipe(
362 Effect.mapError(
363 (cause) =>
364 new OrchestrationGetSnapshotError({
365 message: "Failed to load orchestration snapshot",
366 cause,
367 }),
368 ),
369 ),
370 { "rpc.aggregate": "orchestration" },
371 ),
372 [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>
373 observeRpcEffect(
374 ORCHESTRATION_WS_METHODS.dispatchCommand,
375 Effect.gen(function* () {
376 const normalizedCommand = yield* normalizeDispatchCommand(command);
377 const result = yield* dispatchNormalizedCommand(normalizedCommand);
378 if (normalizedCommand.type === "thread.archive") {
379 yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(
380 Effect.catch((error) =>
381 Effect.logWarning("failed to close thread terminals after archive", {
382 threadId: normalizedCommand.threadId,
383 error: error.message,
384 }),
385 ),
386 );
387 }
388 return result;
389 }).pipe(
390 Effect.mapError((cause) =>
391 Schema.is(OrchestrationDispatchCommandError)(cause)
392 ? cause
393 : new OrchestrationDispatchCommandError({
394 message: "Failed to dispatch orchestration command",
395 cause,
396 }),
397 ),
398 ),
399 { "rpc.aggregate": "orchestration" },
400 ),
401 [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>
402 observeRpcEffect(
403 ORCHESTRATION_WS_METHODS.getTurnDiff,
404 checkpointDiffQuery.getTurnDiff(input).pipe(
405 Effect.mapError(
406 (cause) =>
407 new OrchestrationGetTurnDiffError({
408 message: "Failed to load turn diff",
409 cause,
410 }),
411 ),
412 ),
413 { "rpc.aggregate": "orchestration" },
414 ),
415 [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
416 observeRpcEffect(
417 ORCHESTRATION_WS_METHODS.getFullThreadDiff,
418 checkpointDiffQuery.getFullThreadDiff(input).pipe(
419 Effect.mapError(
420 (cause) =>
421 new OrchestrationGetFullThreadDiffError({
422 message: "Failed to load full thread diff",
423 cause,
424 }),
425 ),
426 ),
427 { "rpc.aggregate": "orchestration" },
428 ),
429 [ORCHESTRATION_WS_METHODS.replayEvents]: (input) =>
430 observeRpcEffect(
431 ORCHESTRATION_WS_METHODS.replayEvents,
432 Stream.runCollect(
433 orchestrationEngine.readEvents(
434 clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }),
435 ),
436 ).pipe(
437 Effect.map((events) => Array.from(events)),
438 Effect.mapError(
439 (cause) =>
440 new OrchestrationReplayEventsError({
441 message: "Failed to replay orchestration events",
442 cause,
443 }),
444 ),
445 ),
446 { "rpc.aggregate": "orchestration" },
447 ),
448 [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) =>
449 observeRpcStreamEffect(
450 WS_METHODS.subscribeOrchestrationDomainEvents,
451 Effect.gen(function* () {
452 const snapshot = yield* orchestrationEngine.getReadModel();
453 const fromSequenceExclusive = snapshot.snapshotSequence;
454 const replayEvents: Array<OrchestrationEvent> = yield* Stream.runCollect(
455 orchestrationEngine.readEvents(fromSequenceExclusive),
456 ).pipe(
457 Effect.map((events) => Array.from(events)),
458 Effect.catch(() => Effect.succeed([] as Array<OrchestrationEvent>)),
459 );
460 const replayStream = Stream.fromIterable(replayEvents);
461 const source = Stream.merge(replayStream, orchestrationEngine.streamDomainEvents);
462 type SequenceState = {
463 readonly nextSequence: number;
464 readonly pendingBySequence: Map<number, OrchestrationEvent>;
465 };
466 const state = yield* Ref.make<SequenceState>({
467 nextSequence: fromSequenceExclusive + 1,
468 pendingBySequence: new Map<number, OrchestrationEvent>(),
469 });
470​
471 return source.pipe(
472 Stream.mapEffect((event) =>
473 Ref.modify(
474 state,
475 ({
476 nextSequence,
477 pendingBySequence,
478 }): [Array<OrchestrationEvent>, SequenceState] => {
479 if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) {
480 return [[], { nextSequence, pendingBySequence }];
481 }
482​
483 const updatedPending = new Map(pendingBySequence);
484 updatedPending.set(event.sequence, event);
485​
486 const emit: Array<OrchestrationEvent> = [];
487 let expected = nextSequence;
488 for (;;) {
489 const expectedEvent = updatedPending.get(expected);
490 if (!expectedEvent) {
491 break;
492 }
493 emit.push(expectedEvent);
494 updatedPending.delete(expected);
495 expected += 1;
496 }
497​
498 return [emit, { nextSequence: expected, pendingBySequence: updatedPending }];
499 },
500 ),
501 ),
502 Stream.flatMap((events) => Stream.fromIterable(events)),
503 );
504 }),
505 { "rpc.aggregate": "orchestration" },
506 ),
507 [WS_METHODS.serverGetConfig]: (_input) =>
508 observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {
509 "rpc.aggregate": "server",
510 }),
511 [WS_METHODS.serverRefreshProviders]: (_input) =>
512 observeRpcEffect(
513 WS_METHODS.serverRefreshProviders,
514 providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))),
515 { "rpc.aggregate": "server" },
516 ),
517 [WS_METHODS.serverUpsertKeybinding]: (rule) =>
518 observeRpcEffect(
519 WS_METHODS.serverUpsertKeybinding,
520 Effect.gen(function* () {
521 const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
522 return { keybindings: keybindingsConfig, issues: [] };
523 }),
524 { "rpc.aggregate": "server" },
525 ),
526 [WS_METHODS.serverGetSettings]: (_input) =>
527 observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, {
528 "rpc.aggregate": "server",
529 }),
530 [WS_METHODS.serverUpdateSettings]: ({ patch }) =>
531 observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), {
532 "rpc.aggregate": "server",
533 }),
534 [WS_METHODS.projectsSearchEntries]: (input) =>
535 observeRpcEffect(
536 WS_METHODS.projectsSearchEntries,
537 workspaceEntries.search(input).pipe(
538 Effect.mapError(
539 (cause) =>
540 new ProjectSearchEntriesError({
541 message: `Failed to search workspace entries: ${cause.detail}`,
542 cause,
543 }),
544 ),
545 ),
546 { "rpc.aggregate": "workspace" },
547 ),
548 [WS_METHODS.projectsWriteFile]: (input) =>
549 observeRpcEffect(
550 WS_METHODS.projectsWriteFile,
551 workspaceFileSystem.writeFile(input).pipe(
552 Effect.mapError((cause) => {
553 const message = Schema.is(WorkspacePathOutsideRootError)(cause)
554 ? "Workspace file path must stay within the project root."
555 : "Failed to write workspace file";
556 return new ProjectWriteFileError({
557 message,
558 cause,
559 });
560 }),
561 ),
562 { "rpc.aggregate": "workspace" },
563 ),
564 [WS_METHODS.shellOpenInEditor]: (input) =>
565 observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), {
566 "rpc.aggregate": "workspace",
567 }),
568 [WS_METHODS.subscribeGitStatus]: (input) =>
569 observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), {
570 "rpc.aggregate": "git",
571 }),
572 [WS_METHODS.gitRefreshStatus]: (input) =>
573 observeRpcEffect(
574 WS_METHODS.gitRefreshStatus,
575 gitStatusBroadcaster.refreshStatus(input.cwd),
576 {
577 "rpc.aggregate": "git",
578 },
579 ),
580 [WS_METHODS.gitPull]: (input) =>
581 observeRpcEffect(
582 WS_METHODS.gitPull,
583 git.pullCurrentBranch(input.cwd).pipe(
584 Effect.matchCauseEffect({
585 onFailure: (cause) => Effect.failCause(cause),
586 onSuccess: (result) =>
587 refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),
588 }),
589 ),
590 { "rpc.aggregate": "git" },
591 ),
592 [WS_METHODS.gitRunStackedAction]: (input) =>
593 observeRpcStream(
594 WS_METHODS.gitRunStackedAction,
595 Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
596 gitManager
597 .runStackedAction(input, {
598 actionId: input.actionId,
599 progressReporter: {
600 publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),
601 },
602 })
603 .pipe(
604 Effect.matchCauseEffect({
605 onFailure: (cause) => Queue.failCause(queue, cause),
606 onSuccess: () =>
607 refreshGitStatus(input.cwd).pipe(
608 Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),
609 ),
610 }),
611 ),
612 ),
613 { "rpc.aggregate": "git" },
614 ),
615 [WS_METHODS.gitResolvePullRequest]: (input) =>
616 observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
617 "rpc.aggregate": "git",
618 }),
619 [WS_METHODS.gitPreparePullRequestThread]: (input) =>
620 observeRpcEffect(
621 WS_METHODS.gitPreparePullRequestThread,
622 gitManager
623 .preparePullRequestThread(input)
624 .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
625 { "rpc.aggregate": "git" },
626 ),
627 [WS_METHODS.gitListBranches]: (input) =>
628 observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
629 "rpc.aggregate": "git",
630 }),
631 [WS_METHODS.gitCreateWorktree]: (input) =>
632 observeRpcEffect(
633 WS_METHODS.gitCreateWorktree,
634 git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
635 { "rpc.aggregate": "git" },
636 ),
637 [WS_METHODS.gitRemoveWorktree]: (input) =>
638 observeRpcEffect(
639 WS_METHODS.gitRemoveWorktree,
640 git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
641 { "rpc.aggregate": "git" },
642 ),
643 [WS_METHODS.gitCreateBranch]: (input) =>
644 observeRpcEffect(
645 WS_METHODS.gitCreateBranch,
646 git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
647 { "rpc.aggregate": "git" },
648 ),
649 [WS_METHODS.gitCheckout]: (input) =>
650 observeRpcEffect(
651 WS_METHODS.gitCheckout,
652 Effect.scoped(git.checkoutBranch(input)).pipe(
653 Effect.tap(() => refreshGitStatus(input.cwd)),
654 ),
655 { "rpc.aggregate": "git" },
656 ),
657 [WS_METHODS.gitInit]: (input) =>
658 observeRpcEffect(
659 WS_METHODS.gitInit,
660 git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
661 { "rpc.aggregate": "git" },
662 ),
663 [WS_METHODS.terminalOpen]: (input) =>
664 observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
665 "rpc.aggregate": "terminal",
666 }),
667 [WS_METHODS.terminalWrite]: (input) =>
668 observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {
669 "rpc.aggregate": "terminal",
670 }),
671 [WS_METHODS.terminalResize]: (input) =>
672 observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {
673 "rpc.aggregate": "terminal",
674 }),
675 [WS_METHODS.terminalClear]: (input) =>
676 observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {
677 "rpc.aggregate": "terminal",
678 }),
679 [WS_METHODS.terminalRestart]: (input) =>
680 observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {
681 "rpc.aggregate": "terminal",
682 }),
683 [WS_METHODS.terminalClose]: (input) =>
684 observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {
685 "rpc.aggregate": "terminal",
686 }),
687 [WS_METHODS.subscribeTerminalEvents]: (_input) =>
688 observeRpcStream(
689 WS_METHODS.subscribeTerminalEvents,
690 Stream.callback<TerminalEvent>((queue) =>
691 Effect.acquireRelease(
692 terminalManager.subscribe((event) => Queue.offer(queue, event)),
693 (unsubscribe) => Effect.sync(unsubscribe),
694 ),
695 ),
696 { "rpc.aggregate": "terminal" },
697 ),
698 [WS_METHODS.subscribeServerConfig]: (_input) =>
699 observeRpcStreamEffect(
700 WS_METHODS.subscribeServerConfig,
701 Effect.gen(function* () {
702 const keybindingsUpdates = keybindings.streamChanges.pipe(
703 Stream.map((event) => ({
704 version: 1 as const,
705 type: "keybindingsUpdated" as const,
706 payload: {
707 issues: event.issues,
708 },
709 })),
710 );
711 const providerStatuses = providerRegistry.streamChanges.pipe(
712 Stream.map((providers) => ({
713 version: 1 as const,
714 type: "providerStatuses" as const,
715 payload: { providers },
716 })),
717 );
718 const settingsUpdates = serverSettings.streamChanges.pipe(
719 Stream.map((settings) => ({
720 version: 1 as const,
721 type: "settingsUpdated" as const,
722 payload: { settings },
723 })),
724 );
725​
726 return Stream.concat(
727 Stream.make({
728 version: 1 as const,
729 type: "snapshot" as const,
730 config: yield* loadServerConfig,
731 }),
732 Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)),
733 );
734 }),
735 { "rpc.aggregate": "server" },
736 ),
737 [WS_METHODS.subscribeServerLifecycle]: (_input) =>
738 observeRpcStreamEffect(
739 WS_METHODS.subscribeServerLifecycle,
740 Effect.gen(function* () {
741 const snapshot = yield* lifecycleEvents.snapshot;
742 const snapshotEvents = Array.from(snapshot.events).toSorted(
743 (left, right) => left.sequence - right.sequence,
744 );
745 const liveEvents = lifecycleEvents.stream.pipe(
746 Stream.filter((event) => event.sequence > snapshot.sequence),
747 );
748 return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
749 }),
750 { "rpc.aggregate": "server" },
751 ),
752 });
753 }),
754);
755​
756export const websocketRpcRouteLayer = Layer.unwrap(
757 Effect.gen(function* () {
758 const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
759 spanPrefix: "ws.rpc",
760 spanAttributes: {
761 "rpc.transport": "websocket",
762 "rpc.system": "effect-rpc",
763 },
764 }).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)));
765 return HttpRouter.add(
766 "GET",
767 "/ws",
768 Effect.gen(function* () {
769 const request = yield* HttpServerRequest.HttpServerRequest;
770 const config = yield* ServerConfig;
771 if (config.authToken) {
772 const url = HttpServerRequest.toURL(request);
773 if (Option.isNone(url)) {
774 return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 });
775 }
776 const token = url.value.searchParams.get("token");
777 if (token !== config.authToken) {
778 return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 });
779 }
780 }
781 return yield* rpcWebSocketHttpEffect;
782 }),
783 );
784 }),
785);