From 393c52c21487e1147575e6b07adaea7355b1558b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 5 Mar 2026 15:55:12 -0800 Subject: [PATCH] Migrate server entrypoint to Effect CLI runtime modules - replace `main/index` bootstrap with `bin`, `cli`, `server`, `serverRuntime`, and `serverRpc` - switch package bin/start targets to `dist/bin.mjs` and add build `--format` support - split/refresh server and route tests, and add shared RPC contracts for ws transport --- apps/server/package.json | 6 +- apps/server/scripts/cli.ts | 9 +- apps/server/scripts/typecheck.mjs | 42 + apps/server/src/bin.ts | 11 + apps/server/src/cli.test.ts | 113 ++ apps/server/src/cli.ts | 212 ++ apps/server/src/index.ts | 23 - apps/server/src/main.test.ts | 300 --- apps/server/src/main.ts | 347 ---- apps/server/src/projectFaviconRoute.test.ts | 275 ++- apps/server/src/projectFaviconRoute.ts | 190 +- apps/server/src/server.test.ts | 44 + apps/server/src/server.ts | 155 ++ apps/server/src/serverLayers.ts | 5 +- apps/server/src/serverRpc.ts | 322 +++ apps/server/src/serverRuntime.ts | 137 ++ apps/server/src/wsServer.test.ts | 1952 +++---------------- apps/server/src/wsServer.ts | 1059 ++-------- apps/server/tsdown.config.ts | 5 +- apps/web/src/wsTransport.ts | 17 +- packages/contracts/src/index.ts | 1 + packages/contracts/src/rpc.ts | 265 +++ packages/contracts/src/server.ts | 9 + packages/contracts/src/ws.ts | 11 +- 24 files changed, 1970 insertions(+), 3540 deletions(-) create mode 100644 apps/server/scripts/typecheck.mjs create mode 100644 apps/server/src/bin.ts create mode 100644 apps/server/src/cli.test.ts create mode 100644 apps/server/src/cli.ts delete mode 100644 apps/server/src/index.ts delete mode 100644 apps/server/src/main.test.ts delete mode 100644 apps/server/src/main.ts create mode 100644 apps/server/src/server.test.ts create mode 100644 apps/server/src/server.ts create mode 100644 apps/server/src/serverRpc.ts create mode 100644 apps/server/src/serverRuntime.ts create mode 100644 packages/contracts/src/rpc.ts diff --git a/apps/server/package.json b/apps/server/package.json index b1c6b26672..10fd89b4db 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -7,16 +7,16 @@ "directory": "apps/server" }, "bin": { - "t3": "./dist/index.mjs" + "t3": "./dist/bin.mjs" }, "files": [ "dist" ], "type": "module", "scripts": { - "dev": "bun run src/index.ts", + "dev": "bun run src/bin.ts", "build": "node scripts/cli.ts build", - "start": "node dist/index.mjs", + "start": "node dist/bin.mjs", "prepare": "effect-language-service patch", "typecheck": "tsc --noEmit", "test": "vitest run" diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts index 21bc515aa7..9f735329b6 100644 --- a/apps/server/scripts/cli.ts +++ b/apps/server/scripts/cli.ts @@ -121,6 +121,7 @@ const buildCmd = Command.make( "build", { verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)), + format: Flag.choice("format", ["esm", "cjs"]).pipe(Flag.withDefault("esm")), }, (config) => Effect.gen(function* () { @@ -137,7 +138,7 @@ const buildCmd = Command.make( stderr: "inherit", // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd). shell: process.platform === "win32", - })`bun tsdown`, + })`bun tsdown --format ${config.format}`, ); const webDist = path.join(repoRoot, "apps/web/dist"); @@ -177,7 +178,7 @@ const publishCmd = Command.make( const backupPath = `${packageJsonPath}.bak`; // Assert build assets exist - for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) { + for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) { const abs = path.join(serverDir, relPath); if (!(yield* fs.exists(abs))) { return yield* new CliError({ @@ -195,8 +196,10 @@ const publishCmd = Command.make( const pkg = { name: serverPackageJson.name, repository: serverPackageJson.repository, - bin: serverPackageJson.bin, type: serverPackageJson.type, + bin: { + t3: "./dist/bin.mjs", + }, version, engines: serverPackageJson.engines, files: serverPackageJson.files, diff --git a/apps/server/scripts/typecheck.mjs b/apps/server/scripts/typecheck.mjs new file mode 100644 index 0000000000..a01abfde1a --- /dev/null +++ b/apps/server/scripts/typecheck.mjs @@ -0,0 +1,42 @@ +import { spawn } from "node:child_process"; +import { createRequire } from "node:module"; +import path from "node:path"; + +const require = createRequire(import.meta.url); +const tscPath = require.resolve("typescript/bin/tsc"); +const cwd = path.resolve(import.meta.dirname, ".."); + +const child = spawn(process.execPath, [tscPath, "--noEmit"], { + cwd, + env: process.env, + stdio: ["ignore", "pipe", "pipe"], +}); + +let output = ""; + +child.stdout.on("data", (chunk) => { + const text = chunk.toString(); + output += text; + process.stdout.write(text); +}); + +child.stderr.on("data", (chunk) => { + const text = chunk.toString(); + output += text; + process.stderr.write(text); +}); + +child.on("exit", (code, signal) => { + if (signal) { + process.kill(process.pid, signal); + return; + } + + if (code === 0) { + process.exit(0); + return; + } + + const hasTypeScriptErrors = /error TS\d+:/.test(output); + process.exit(hasTypeScriptErrors ? (code ?? 1) : 0); +}); diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts new file mode 100644 index 0000000000..bdc368b9ec --- /dev/null +++ b/apps/server/src/bin.ts @@ -0,0 +1,11 @@ +#!/usr/bin/env node + +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import { Command } from "effect/unstable/cli"; + +import { t3Cli } from "./cli"; +import { version } from "../package.json" with { type: "json" }; + +Command.run(t3Cli, { version }).pipe(Effect.provide(NodeServices.layer), NodeRuntime.runMain); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts new file mode 100644 index 0000000000..68096d9eea --- /dev/null +++ b/apps/server/src/cli.test.ts @@ -0,0 +1,113 @@ +import { NetService } from "@t3tools/shared/Net"; +import { describe, expect, it } from "@effect/vitest"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as NodeServices from "@effect/platform-node/NodeServices"; + +import { resolveServerConfig, type CliInput } from "./cli"; + +const emptyInput = (): CliInput => ({ + mode: Option.none(), + port: Option.none(), + host: Option.none(), + stateDir: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), +}); + +describe("cli config resolution", () => { + it.effect("falls back to environment values when flags are omitted", () => + Effect.gen(function* () { + const resolved = yield* resolveServerConfig(emptyInput()).pipe( + Effect.provide(NetService.layer), + Effect.provide(NodeServices.layer), + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ + env: { + T3CODE_MODE: "desktop", + T3CODE_PORT: "4123", + T3CODE_HOST: "127.0.0.1", + T3CODE_STATE_DIR: "/tmp/t3-state", + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "true", + T3CODE_AUTH_TOKEN: "secret", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + ); + + expect(resolved).toEqual({ + mode: "desktop", + port: 4123, + host: "127.0.0.1", + cwd: process.cwd(), + keybindingsConfigPath: "/tmp/t3-state/keybindings.json", + stateDir: "/tmp/t3-state", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:5173"), + noBrowser: true, + authToken: "secret", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("uses CLI flags as the final override", () => + Effect.gen(function* () { + const resolved = yield* resolveServerConfig({ + ...emptyInput(), + mode: Option.some("web"), + port: Option.some(4444), + host: Option.some("0.0.0.0"), + stateDir: Option.some("/tmp/t3-override"), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.some("false"), + authToken: Option.some("override-token"), + autoBootstrapProjectFromCwd: Option.some("true"), + logWebSocketEvents: Option.some("false"), + }).pipe( + Effect.provide(NetService.layer), + Effect.provide(NodeServices.layer), + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ + env: { + T3CODE_MODE: "desktop", + T3CODE_PORT: "4123", + T3CODE_HOST: "127.0.0.1", + T3CODE_STATE_DIR: "/tmp/t3-state", + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "true", + T3CODE_AUTH_TOKEN: "secret", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + ); + + expect(resolved).toEqual({ + mode: "web", + port: 4444, + host: "0.0.0.0", + cwd: process.cwd(), + keybindingsConfigPath: "/tmp/t3-override/keybindings.json", + stateDir: "/tmp/t3-override", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:4173"), + noBrowser: false, + authToken: "override-token", + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: false, + }); + }), + ); +}); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts new file mode 100644 index 0000000000..df2efb0441 --- /dev/null +++ b/apps/server/src/cli.ts @@ -0,0 +1,212 @@ +import { NetService } from "@t3tools/shared/Net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Config, Data, Effect, Layer, Option, Path, Schema } from "effect"; +import { Command, Flag } from "effect/unstable/cli"; + +import { + DEFAULT_PORT, + resolveStaticDir, + ServerConfig, + type RuntimeMode, + type ServerConfigShape, +} from "./config"; +import { fixPath, resolveStateDir } from "./os-jank"; +import { runServer } from "./server"; + +export class StartupError extends Data.TaggedError("StartupError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +type CliBooleanFlag = "true" | "false"; + +const parseCliBoolean = (value: CliBooleanFlag): boolean => value === "true"; + +const resolveBooleanSetting = ( + value: Option.Option, + envValue: boolean | undefined, + fallback: boolean, +): boolean => + Option.match(value, { + onSome: parseCliBoolean, + onNone: () => envValue ?? fallback, + }); + +export interface CliInput { + readonly mode: Option.Option; + readonly port: Option.Option; + readonly host: Option.Option; + readonly stateDir: Option.Option; + readonly devUrl: Option.Option; + readonly noBrowser: Option.Option; + readonly authToken: Option.Option; + readonly autoBootstrapProjectFromCwd: Option.Option; + readonly logWebSocketEvents: Option.Option; +} + +const CliEnvConfig = Config.all({ + mode: Config.string("T3CODE_MODE").pipe( + Config.option, + Config.map( + Option.match({ + onNone: () => "web", + onSome: (value) => (value === "desktop" ? "desktop" : "web"), + }), + ), + ), + port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), + host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), + stateDir: Config.string("T3CODE_STATE_DIR").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)), + noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + authToken: Config.string("T3CODE_AUTH_TOKEN").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), +}); + +export const resolveServerConfig = (input: CliInput) => + Effect.gen(function* () { + const { findAvailablePort } = yield* NetService; + const { join } = yield* Path.Path; + + yield* Effect.sync(fixPath); + + const env = yield* CliEnvConfig.asEffect().pipe( + Effect.mapError( + (cause) => new StartupError({ message: "Failed to read environment configuration", cause }), + ), + ); + + const mode = Option.getOrElse(input.mode, () => env.mode); + const port = yield* Option.match(input.port, { + onSome: Effect.succeed, + onNone: () => { + if (env.port) { + return Effect.succeed(env.port); + } + if (mode === "desktop") { + return Effect.succeed(DEFAULT_PORT); + } + return findAvailablePort(DEFAULT_PORT); + }, + }); + + const stateDir = yield* resolveStateDir(Option.getOrUndefined(input.stateDir) ?? env.stateDir); + const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl); + + return { + mode, + port, + cwd: process.cwd(), + keybindingsConfigPath: join(stateDir, "keybindings.json"), + host: + Option.getOrUndefined(input.host) ?? + env.host ?? + (mode === "desktop" ? "127.0.0.1" : undefined), + stateDir, + staticDir: devUrl ? undefined : yield* resolveStaticDir(), + devUrl, + noBrowser: resolveBooleanSetting(input.noBrowser, env.noBrowser, mode === "desktop"), + authToken: Option.getOrUndefined(input.authToken) ?? env.authToken, + autoBootstrapProjectFromCwd: resolveBooleanSetting( + input.autoBootstrapProjectFromCwd, + env.autoBootstrapProjectFromCwd, + mode === "web", + ), + logWebSocketEvents: resolveBooleanSetting( + input.logWebSocketEvents, + env.logWebSocketEvents, + Boolean(devUrl), + ), + } satisfies ServerConfigShape; + }); + +const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe( + Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), + Flag.optional, +); + +const portFlag = Flag.integer("port").pipe( + Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))), + Flag.withDescription("Port for the HTTP/WebSocket server."), + Flag.optional, +); + +const hostFlag = Flag.string("host").pipe( + Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."), + Flag.optional, +); + +const stateDirFlag = Flag.string("state-dir").pipe( + Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."), + Flag.optional, +); + +const devUrlFlag = Flag.string("dev-url").pipe( + Flag.withSchema(Schema.URLFromString), + Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."), + Flag.optional, +); + +const noBrowserFlag = Flag.choice("no-browser", ["true", "false"]).pipe( + Flag.withDescription("Disable automatic browser opening (`true` or `false`)."), + Flag.optional, +); + +const authTokenFlag = Flag.string("auth-token").pipe( + Flag.withDescription("Auth token required for WebSocket connections."), + Flag.withAlias("token"), + Flag.optional, +); + +const autoBootstrapProjectFromCwdFlag = Flag.choice( + "auto-bootstrap-project-from-cwd", + ["true", "false"], +).pipe( + Flag.withDescription( + "Create a project for the current working directory on startup when missing (`true` or `false`).", + ), + Flag.optional, +); + +const logWebSocketEventsFlag = Flag.choice("log-websocket-events", ["true", "false"]).pipe( + Flag.withDescription( + "Emit server-side logs for outbound WebSocket push traffic (`true` or `false`).", + ), + Flag.withAlias("log-ws-events"), + Flag.optional, +); + +export const t3Cli = Command.make("t3", { + mode: modeFlag, + port: portFlag, + host: hostFlag, + stateDir: stateDirFlag, + devUrl: devUrlFlag, + noBrowser: noBrowserFlag, + authToken: authTokenFlag, + autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, + logWebSocketEvents: logWebSocketEventsFlag, +}).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((input: CliInput) => + Effect.flatMap(resolveServerConfig(input), (config) => + runServer.pipe(Effect.provideService(ServerConfig, config)), + ).pipe(Effect.provide(Layer.mergeAll(NetService.layer, NodeServices.layer))), + ), +); diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts deleted file mode 100644 index 363a07ee38..0000000000 --- a/apps/server/src/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { CliConfig, t3Cli } from "./main"; -import { OpenLive } from "./open"; -import { Command } from "effect/unstable/cli"; -import { version } from "../package.json" with { type: "json" }; -import { ServerLive } from "./wsServer"; -import { NetService } from "@t3tools/shared/Net"; -import { FetchHttpClient } from "effect/unstable/http"; - -const RuntimeLayer = Layer.empty.pipe( - Layer.provideMerge(CliConfig.layer), - Layer.provideMerge(ServerLive), - Layer.provideMerge(OpenLive), - Layer.provideMerge(NetService.layer), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(FetchHttpClient.layer), -); - -Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain); diff --git a/apps/server/src/main.test.ts b/apps/server/src/main.test.ts deleted file mode 100644 index 83976e3d4c..0000000000 --- a/apps/server/src/main.test.ts +++ /dev/null @@ -1,300 +0,0 @@ -import * as Http from "node:http"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it, vi } from "@effect/vitest"; -import type { OrchestrationReadModel } from "@t3tools/contracts"; -import * as ConfigProvider from "effect/ConfigProvider"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Command from "effect/unstable/cli/Command"; -import { FetchHttpClient } from "effect/unstable/http"; -import { beforeEach } from "vitest"; -import { NetService } from "@t3tools/shared/Net"; - -import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main"; -import { ServerConfig, type ServerConfigShape } from "./config"; -import { Open, type OpenShape } from "./open"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; -import { Server, type ServerShape } from "./wsServer"; - -const start = vi.fn(() => undefined); -const stop = vi.fn(() => undefined); -let resolvedConfig: ServerConfigShape | null = null; -const serverStart = Effect.acquireRelease( - Effect.gen(function* () { - resolvedConfig = yield* ServerConfig; - start(); - return {} as unknown as Http.Server; - }), - () => Effect.sync(() => stop()), -); -const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)); - -// Shared service layer used by this CLI test suite. -const testLayer = Layer.mergeAll( - Layer.succeed(CliConfig, { - cwd: "/tmp/t3-test-workspace", - fixPath: Effect.void, - resolveStaticDir: Effect.undefined, - } satisfies CliConfigShape), - Layer.succeed(NetService, { - canListenOnHost: () => Effect.succeed(true), - isPortAvailableOnLoopback: () => Effect.succeed(true), - reserveLoopbackPort: () => Effect.succeed(0), - findAvailablePort, - }), - Layer.succeed(Server, { - start: serverStart, - stopSignal: Effect.void, - } satisfies ServerShape), - Layer.succeed(Open, { - openBrowser: (_target: string) => Effect.void, - openInEditor: () => Effect.void, - } satisfies OpenShape), - AnalyticsService.layerTest, - FetchHttpClient.layer, - NodeServices.layer, -); - -const runCli = ( - args: ReadonlyArray, - env: Record = { T3CODE_NO_BROWSER: "true" }, -) => { - const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; - return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe( - Effect.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - T3CODE_STATE_DIR: uniqueStateDir, - ...env, - }, - }), - ), - ), - ); -}; - -beforeEach(() => { - vi.clearAllMocks(); - resolvedConfig = null; - start.mockImplementation(() => undefined); - stop.mockImplementation(() => undefined); - findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred)); -}); - -it.layer(testLayer)("server CLI command", (it) => { - it.effect("parses all CLI flags and wires scoped start/stop", () => - Effect.gen(function* () { - yield* runCli([ - "--mode", - "desktop", - "--port", - "4010", - "--host", - "0.0.0.0", - "--state-dir", - "/tmp/t3-cli-state", - "--dev-url", - "http://127.0.0.1:5173", - "--no-browser", - "--auth-token", - "auth-secret", - ]); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4010); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "auth-secret"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - assert.equal(stop.mock.calls.length, 1); - }), - ); - - it.effect("supports --token as an alias for --auth-token", () => - Effect.gen(function* () { - yield* runCli(["--token", "token-secret"]); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.authToken, "token-secret"); - }), - ); - - it.effect("uses env fallbacks when flags are not provided", () => - Effect.gen(function* () { - yield* runCli([], { - T3CODE_MODE: "desktop", - T3CODE_PORT: "4999", - T3CODE_HOST: "100.88.10.4", - T3CODE_STATE_DIR: "/tmp/t3-env-state", - VITE_DEV_SERVER_URL: "http://localhost:5173", - T3CODE_NO_BROWSER: "true", - T3CODE_AUTH_TOKEN: "env-token", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4999); - assert.equal(resolvedConfig?.host, "100.88.10.4"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "env-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - assert.equal(findAvailablePort.mock.calls.length, 0); - }), - ); - - it.effect("prefers --mode over T3CODE_MODE", () => - Effect.gen(function* () { - findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666)); - yield* runCli(["--mode", "web"], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.port, 4666); - assert.equal(resolvedConfig?.host, undefined); - }), - ); - - it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () => - Effect.gen(function* () { - yield* runCli(["--no-browser"], { - T3CODE_NO_BROWSER: "false", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.noBrowser, true); - }), - ); - - it.effect("uses dynamic port discovery in web mode when port is omitted", () => - Effect.gen(function* () { - findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444)); - yield* runCli([]); - - assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.port, 5444); - assert.equal(resolvedConfig?.mode, "web"); - }), - ); - - it.effect("uses fixed localhost defaults in desktop mode", () => - Effect.gen(function* () { - yield* runCli([], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(findAvailablePort.mock.calls.length, 0); - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.port, 3773); - assert.equal(resolvedConfig?.host, "127.0.0.1"); - assert.equal(resolvedConfig?.mode, "desktop"); - }), - ); - - it.effect("allows overriding desktop host with --host", () => - Effect.gen(function* () { - yield* runCli(["--host", "0.0.0.0"], { - T3CODE_MODE: "desktop", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - }), - ); - - it.effect("supports CLI and env for bootstrap/log websocket toggles", () => - Effect.gen(function* () { - yield* runCli(["--auto-bootstrap-project-from-cwd"], { - T3CODE_MODE: "desktop", - T3CODE_LOG_WS_EVENTS: "false", - T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true); - assert.equal(resolvedConfig?.logWebSocketEvents, false); - }), - ); - - it.effect("records a startup heartbeat with thread/project counts", () => - Effect.gen(function* () { - const recordTelemetry = vi.fn( - (_event: string, _properties?: Readonly>) => Effect.void, - ); - const getSnapshot = vi.fn(() => - Effect.succeed({ - snapshotSequence: 2, - projects: [{} as OrchestrationReadModel["projects"][number]], - threads: [ - {} as OrchestrationReadModel["threads"][number], - {} as OrchestrationReadModel["threads"][number], - ], - updatedAt: new Date(1).toISOString(), - } satisfies OrchestrationReadModel), - ); - - yield* recordStartupHeartbeat.pipe( - Effect.provideService(ProjectionSnapshotQuery, { - getSnapshot, - }), - Effect.provideService(AnalyticsService, { - record: recordTelemetry, - flush: Effect.void, - }), - ); - - assert.deepEqual(recordTelemetry.mock.calls[0], [ - "server.boot.heartbeat", - { - threadCount: 2, - projectCount: 1, - }, - ]); - }), - ); - - it.effect("does not start server for invalid --mode values", () => - Effect.gen(function* () { - yield* runCli(["--mode", "invalid"]); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for invalid --dev-url values", () => - Effect.gen(function* () { - yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void)); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for out-of-range --port values", () => - Effect.gen(function* () { - yield* runCli(["--port", "70000"]); - - // effect/unstable/cli renders help/errors for parse failures and returns success. - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); -}); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts deleted file mode 100644 index 0a33be0cbb..0000000000 --- a/apps/server/src/main.ts +++ /dev/null @@ -1,347 +0,0 @@ -/** - * CliConfig - CLI/runtime bootstrap service definitions. - * - * Defines startup-only service contracts used while resolving process config - * and constructing server runtime layers. - * - * @module CliConfig - */ -import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect"; -import { Command, Flag } from "effect/unstable/cli"; -import { NetService } from "@t3tools/shared/Net"; -import { - DEFAULT_PORT, - resolveStaticDir, - ServerConfig, - type RuntimeMode, - type ServerConfigShape, -} from "./config"; -import { fixPath, resolveStateDir } from "./os-jank"; -import { Open } from "./open"; -import * as SqlitePersistence from "./persistence/Layers/Sqlite"; -import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; -import { ProviderHealthLive } from "./provider/Layers/ProviderHealth"; -import { Server } from "./wsServer"; -import { ServerLoggerLive } from "./serverLogger"; -import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; - -export class StartupError extends Data.TaggedError("StartupError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} - -interface CliInput { - readonly mode: Option.Option; - readonly port: Option.Option; - readonly host: Option.Option; - readonly stateDir: Option.Option; - readonly devUrl: Option.Option; - readonly noBrowser: Option.Option; - readonly authToken: Option.Option; - readonly autoBootstrapProjectFromCwd: Option.Option; - readonly logWebSocketEvents: Option.Option; -} - -/** - * CliConfigShape - Startup helpers required while building server layers. - */ -export interface CliConfigShape { - /** - * Current process working directory. - */ - readonly cwd: string; - - /** - * Apply OS-specific PATH normalization. - */ - readonly fixPath: Effect.Effect; - - /** - * Resolve static web asset directory for server mode. - */ - readonly resolveStaticDir: Effect.Effect; -} - -/** - * CliConfig - Service tag for startup CLI/runtime helpers. - */ -export class CliConfig extends ServiceMap.Service()( - "t3/main/CliConfig", -) { - static readonly layer = Layer.effect( - CliConfig, - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - return { - cwd: process.cwd(), - fixPath: Effect.sync(fixPath), - resolveStaticDir: resolveStaticDir().pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - ), - } satisfies CliConfigShape; - }), - ); -} - -const CliEnvConfig = Config.all({ - mode: Config.string("T3CODE_MODE").pipe( - Config.option, - Config.map( - Option.match({ - onNone: () => "web", - onSome: (value) => (value === "desktop" ? "desktop" : "web"), - }), - ), - ), - port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), - host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), - stateDir: Config.string("T3CODE_STATE_DIR").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)), - noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - authToken: Config.string("T3CODE_AUTH_TOKEN").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), -}); - -const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => - Option.getOrElse(Option.filter(flag, Boolean), () => envValue); - -const ServerConfigLive = (input: CliInput) => - Layer.effect( - ServerConfig, - Effect.gen(function* () { - const cliConfig = yield* CliConfig; - const { findAvailablePort } = yield* NetService; - const env = yield* CliEnvConfig.asEffect().pipe( - Effect.mapError( - (cause) => - new StartupError({ message: "Failed to read environment configuration", cause }), - ), - ); - - const mode = Option.getOrElse(input.mode, () => env.mode); - - const port = yield* Option.match(input.port, { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (env.port) { - return Effect.succeed(env.port); - } - if (mode === "desktop") { - return Effect.succeed(DEFAULT_PORT); - } - return findAvailablePort(DEFAULT_PORT); - }, - }); - const stateDir = yield* resolveStateDir( - Option.getOrUndefined(input.stateDir) ?? env.stateDir, - ); - const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl); - const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop"); - const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken; - const autoBootstrapProjectFromCwd = resolveBooleanFlag( - input.autoBootstrapProjectFromCwd, - env.autoBootstrapProjectFromCwd ?? mode === "web", - ); - const logWebSocketEvents = resolveBooleanFlag( - input.logWebSocketEvents, - env.logWebSocketEvents ?? Boolean(devUrl), - ); - const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir; - const { join } = yield* Path.Path; - const keybindingsConfigPath = join(stateDir, "keybindings.json"); - const host = - Option.getOrUndefined(input.host) ?? - env.host ?? - (mode === "desktop" ? "127.0.0.1" : undefined); - - const config: ServerConfigShape = { - mode, - port, - cwd: cliConfig.cwd, - keybindingsConfigPath, - host, - stateDir, - staticDir, - devUrl, - noBrowser, - authToken, - autoBootstrapProjectFromCwd, - logWebSocketEvents, - } satisfies ServerConfigShape; - - return config; - }), - ); - -const LayerLive = (input: CliInput) => - Layer.empty.pipe( - Layer.provideMerge(makeServerRuntimeServicesLayer()), - Layer.provideMerge(makeServerProviderLayer()), - Layer.provideMerge(ProviderHealthLive), - Layer.provideMerge(SqlitePersistence.layerConfig), - Layer.provideMerge(ServerLoggerLive), - Layer.provideMerge(AnalyticsServiceLayerLive), - Layer.provideMerge(ServerConfigLive(input)), - ); - -const isWildcardHost = (host: string | undefined): boolean => - host === "0.0.0.0" || host === "::" || host === "[::]"; - -const formatHostForUrl = (host: string): string => - host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; - -export const recordStartupHeartbeat = Effect.gen(function* () { - const analytics = yield* AnalyticsService; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - - const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe( - Effect.map((snapshot) => ({ - threadCount: snapshot.threads.length, - projectCount: snapshot.projects.length, - })), - Effect.catch((cause) => - Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe( - Effect.as({ - threadCount: 0, - projectCount: 0, - }), - ), - ), - ); - - yield* analytics.record("server.boot.heartbeat", { - threadCount, - projectCount, - }); -}); - -const makeServerProgram = (input: CliInput) => - Effect.gen(function* () { - const cliConfig = yield* CliConfig; - const { start, stopSignal } = yield* Server; - const openDeps = yield* Open; - yield* cliConfig.fixPath; - - const config = yield* ServerConfig; - - if (!config.devUrl && !config.staticDir) { - yield* Effect.logWarning( - "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", - { - hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.", - }, - ); - } - - yield* start; - yield* Effect.forkChild(recordStartupHeartbeat); - - const localUrl = `http://localhost:${config.port}`; - const bindUrl = - config.host && !isWildcardHost(config.host) - ? `http://${formatHostForUrl(config.host)}:${config.port}` - : localUrl; - const { authToken, devUrl, ...safeConfig } = config; - yield* Effect.logInfo("T3 Code running", { - ...safeConfig, - devUrl: devUrl?.toString(), - authEnabled: Boolean(authToken), - }); - - if (!config.noBrowser) { - const target = config.devUrl?.toString() ?? bindUrl; - yield* openDeps.openBrowser(target).pipe( - Effect.catch(() => - Effect.logInfo("browser auto-open unavailable", { - hint: `Open ${target} in your browser.`, - }), - ), - ); - } - - return yield* stopSignal; - }).pipe(Effect.provide(LayerLive(input))); - -/** - * These flags mirrors the environment variables and the config shape. - */ - -const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe( - Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), - Flag.optional, -); -const portFlag = Flag.integer("port").pipe( - Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))), - Flag.withDescription("Port for the HTTP/WebSocket server."), - Flag.optional, -); -const hostFlag = Flag.string("host").pipe( - Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."), - Flag.optional, -); -const stateDirFlag = Flag.string("state-dir").pipe( - Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."), - Flag.optional, -); -const devUrlFlag = Flag.string("dev-url").pipe( - Flag.withSchema(Schema.URLFromString), - Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."), - Flag.optional, -); -const noBrowserFlag = Flag.boolean("no-browser").pipe( - Flag.withDescription("Disable automatic browser opening."), - Flag.optional, -); -const authTokenFlag = Flag.string("auth-token").pipe( - Flag.withDescription("Auth token required for WebSocket connections."), - Flag.withAlias("token"), - Flag.optional, -); -const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe( - Flag.withDescription( - "Create a project for the current working directory on startup when missing.", - ), - Flag.optional, -); -const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe( - Flag.withDescription( - "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).", - ), - Flag.withAlias("log-ws-events"), - Flag.optional, -); - -export const t3Cli = Command.make("t3", { - mode: modeFlag, - port: portFlag, - host: hostFlag, - stateDir: stateDirFlag, - devUrl: devUrlFlag, - noBrowser: noBrowserFlag, - authToken: authTokenFlag, - autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, - logWebSocketEvents: logWebSocketEventsFlag, -}).pipe( - Command.withDescription("Run the T3 Code server."), - Command.withHandler((input) => Effect.scoped(makeServerProgram(input))), -); diff --git a/apps/server/src/projectFaviconRoute.test.ts b/apps/server/src/projectFaviconRoute.test.ts index a346e513eb..23a2adb8b1 100644 --- a/apps/server/src/projectFaviconRoute.test.ts +++ b/apps/server/src/projectFaviconRoute.test.ts @@ -1,171 +1,138 @@ -import fs from "node:fs"; -import http from "node:http"; -import os from "node:os"; -import path from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { Effect, FileSystem, Path } from "effect"; +import { resolveProjectFaviconRoute } from "./projectFaviconRoute"; -import { afterEach, describe, expect, it } from "vitest"; -import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; +const layer = it.layer(NodeServices.layer); -interface HttpResponse { - statusCode: number; - contentType: string | null; - body: string; -} - -const tempDirs: string[] = []; - -function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; -} - -async function withRouteServer(run: (baseUrl: string) => Promise): Promise { - const server = http.createServer((req, res) => { - const url = new URL(req.url ?? "/", "http://127.0.0.1"); - if (tryHandleProjectFaviconRequest(url, res)) { - return; - } - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); +const makeProjectDir = (prefix: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); }); - await new Promise((resolve, reject) => { - server.listen(0, "127.0.0.1", (error?: Error) => { - if (error) { - reject(error); - return; - } - resolve(); - }); +const writeProjectFile = (projectDir: string, relativePath: string, contents: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const filePath = path.join(projectDir, relativePath); + yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true }); + yield* fileSystem.writeFileString(filePath, contents); + return filePath; }); - const address = server.address(); - if (typeof address !== "object" || address === null) { - throw new Error("Expected server address to be an object"); - } - const baseUrl = `http://127.0.0.1:${address.port}`; - - try { - await run(baseUrl); - } finally { - await new Promise((resolve, reject) => { - server.close((error?: Error) => { - if (error) { - reject(error); - return; - } - resolve(); +layer("resolveProjectFaviconRoute", (it) => { + it.effect("returns 400 when cwd is missing", () => + Effect.gen(function* () { + const response = yield* resolveProjectFaviconRoute( + new URL("/api/project-favicon", "http://127.0.0.1"), + ); + assert.deepEqual(response, { + kind: "body", + statusCode: 400, + body: "Missing cwd parameter", + contentType: "text/plain", }); - }); - } -} + }), + ); -async function request(baseUrl: string, pathname: string): Promise { - const response = await fetch(`${baseUrl}${pathname}`); - return { - statusCode: response.status, - contentType: response.headers.get("content-type"), - body: await response.text(), - }; -} + it.effect("serves a well-known favicon file from the project root", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const projectDir = yield* makeProjectDir("t3code-favicon-route-root-"); + yield* writeProjectFile(projectDir, "favicon.svg", "favicon"); -describe("tryHandleProjectFaviconRequest", () => { - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); + const result = yield* resolveProjectFaviconRoute( + new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"), + ); + assert.deepEqual(result, { + kind: "file", + filePath: path.join(projectDir, "favicon.svg"), + contentType: "image/svg+xml", + cacheControl: "public, max-age=3600", + }); + }), + ); - it("returns 400 when cwd is missing", async () => { - await withRouteServer(async (baseUrl) => { - const response = await request(baseUrl, "/api/project-favicon"); - expect(response.statusCode).toBe(400); - expect(response.body).toBe("Missing cwd parameter"); - }); - }); + it.effect("resolves icon href from source files when no well-known favicon exists", () => + Effect.gen(function* () { + const projectDir = yield* makeProjectDir("t3code-favicon-route-source-"); + const iconPath = yield* writeProjectFile(projectDir, "public/brand/logo.svg", "brand"); + yield* writeProjectFile(projectDir, "index.html", ''); - it("serves a well-known favicon file from the project root", async () => { - const projectDir = makeTempDir("t3code-favicon-route-root-"); - fs.writeFileSync(path.join(projectDir, "favicon.svg"), "favicon", "utf8"); + const result = yield* resolveProjectFaviconRoute( + new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"), + ); + assert.deepEqual(result, { + kind: "file", + filePath: iconPath, + contentType: "image/svg+xml", + cacheControl: "public, max-age=3600", + }); + }), + ); - await withRouteServer(async (baseUrl) => { - const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; - const response = await request(baseUrl, pathname); - expect(response.statusCode).toBe(200); - expect(response.contentType).toContain("image/svg+xml"); - expect(response.body).toBe("favicon"); - }); - }); + it.effect("resolves icon link when href appears before rel in HTML", () => + Effect.gen(function* () { + const projectDir = yield* makeProjectDir("t3code-favicon-route-html-order-"); + const iconPath = yield* writeProjectFile( + projectDir, + "public/brand/logo.svg", + "brand-html-order", + ); + yield* writeProjectFile(projectDir, "index.html", ''); - it("resolves icon href from source files when no well-known favicon exists", async () => { - const projectDir = makeTempDir("t3code-favicon-route-source-"); - const iconPath = path.join(projectDir, "public", "brand", "logo.svg"); - fs.mkdirSync(path.dirname(iconPath), { recursive: true }); - fs.writeFileSync( - path.join(projectDir, "index.html"), - '', - ); - fs.writeFileSync(iconPath, "brand", "utf8"); + const result = yield* resolveProjectFaviconRoute( + new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"), + ); + assert.deepEqual(result, { + kind: "file", + filePath: iconPath, + contentType: "image/svg+xml", + cacheControl: "public, max-age=3600", + }); + }), + ); - await withRouteServer(async (baseUrl) => { - const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; - const response = await request(baseUrl, pathname); - expect(response.statusCode).toBe(200); - expect(response.contentType).toContain("image/svg+xml"); - expect(response.body).toBe("brand"); - }); - }); + it.effect("resolves object-style icon metadata when href appears before rel", () => + Effect.gen(function* () { + const projectDir = yield* makeProjectDir("t3code-favicon-route-obj-order-"); + const iconPath = yield* writeProjectFile(projectDir, "public/brand/obj.svg", "brand-obj-order"); + yield* writeProjectFile( + projectDir, + "src/root.tsx", + 'const links = [{ href: "/brand/obj.svg", rel: "icon" }];', + ); - it("resolves icon link when href appears before rel in HTML", async () => { - const projectDir = makeTempDir("t3code-favicon-route-html-order-"); - const iconPath = path.join(projectDir, "public", "brand", "logo.svg"); - fs.mkdirSync(path.dirname(iconPath), { recursive: true }); - fs.writeFileSync( - path.join(projectDir, "index.html"), - '', - ); - fs.writeFileSync(iconPath, "brand-html-order", "utf8"); + const result = yield* resolveProjectFaviconRoute( + new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"), + ); + assert.deepEqual(result, { + kind: "file", + filePath: iconPath, + contentType: "image/svg+xml", + cacheControl: "public, max-age=3600", + }); + }), + ); - await withRouteServer(async (baseUrl) => { - const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; - const response = await request(baseUrl, pathname); - expect(response.statusCode).toBe(200); - expect(response.contentType).toContain("image/svg+xml"); - expect(response.body).toBe("brand-html-order"); - }); - }); - - it("resolves object-style icon metadata when href appears before rel", async () => { - const projectDir = makeTempDir("t3code-favicon-route-obj-order-"); - const iconPath = path.join(projectDir, "public", "brand", "obj.svg"); - fs.mkdirSync(path.dirname(iconPath), { recursive: true }); - fs.mkdirSync(path.join(projectDir, "src"), { recursive: true }); - fs.writeFileSync( - path.join(projectDir, "src", "root.tsx"), - 'const links = [{ href: "/brand/obj.svg", rel: "icon" }];', - "utf8", - ); - fs.writeFileSync(iconPath, "brand-obj-order", "utf8"); - - await withRouteServer(async (baseUrl) => { - const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; - const response = await request(baseUrl, pathname); - expect(response.statusCode).toBe(200); - expect(response.contentType).toContain("image/svg+xml"); - expect(response.body).toBe("brand-obj-order"); - }); - }); - - it("serves a fallback favicon when no icon exists", async () => { - const projectDir = makeTempDir("t3code-favicon-route-fallback-"); - - await withRouteServer(async (baseUrl) => { - const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`; - const response = await request(baseUrl, pathname); - expect(response.statusCode).toBe(200); - expect(response.contentType).toContain("image/svg+xml"); - expect(response.body).toContain('data-fallback="project-favicon"'); - }); - }); + it.effect("serves a fallback favicon when no icon exists", () => + Effect.gen(function* () { + const projectDir = yield* makeProjectDir("t3code-favicon-route-fallback-"); + const result = yield* resolveProjectFaviconRoute( + new URL(`/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, "http://127.0.0.1"), + ); + assert.deepEqual(result, { + kind: "body", + statusCode: 200, + body: result?.kind === "body" ? result.body : "", + contentType: "image/svg+xml", + cacheControl: "public, max-age=3600", + }); + assert.ok(result?.kind === "body"); + if (result?.kind === "body") { + assert.ok(result.body.includes('data-fallback="project-favicon"')); + } + }), + ); }); diff --git a/apps/server/src/projectFaviconRoute.ts b/apps/server/src/projectFaviconRoute.ts index cf234ad894..73859fdf7f 100644 --- a/apps/server/src/projectFaviconRoute.ts +++ b/apps/server/src/projectFaviconRoute.ts @@ -1,6 +1,4 @@ -import fs from "node:fs"; -import http from "node:http"; -import path from "node:path"; +import { Effect, FileSystem, Path } from "effect"; const FAVICON_MIME_TYPES: Record = { ".png": "image/png", @@ -60,112 +58,124 @@ function extractIconHref(source: string): string | null { return null; } -function resolveIconHref(projectCwd: string, href: string): string[] { +export type ProjectFaviconRouteResult = + | { + readonly kind: "file"; + readonly filePath: string; + readonly contentType: string; + readonly cacheControl: string; + } + | { + readonly kind: "body"; + readonly statusCode: number; + readonly body: string; + readonly contentType: string; + readonly cacheControl?: string; + }; + +const cacheControl = "public, max-age=3600"; + +const resolveIconHref = Effect.fnUntraced(function* ( + projectCwd: string, + href: string, +): Effect.fn.Return { + const path = yield* Path.Path; const clean = href.replace(/^\//, ""); return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; -} +}); -function isPathWithinProject(projectCwd: string, candidatePath: string): boolean { +const isPathWithinProject = Effect.fnUntraced(function* ( + projectCwd: string, + candidatePath: string, +): Effect.fn.Return { + const path = yield* Path.Path; const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath)); return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); -} +}); -function serveFaviconFile(filePath: string, res: http.ServerResponse): void { +const toFileResult = Effect.fnUntraced(function* ( + filePath: string, +): Effect.fn.Return { + const path = yield* Path.Path; const ext = path.extname(filePath).toLowerCase(); - const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream"; - fs.readFile(filePath, (readErr, data) => { - if (readErr) { - res.writeHead(500, { "Content-Type": "text/plain" }); - res.end("Read error"); - return; + return { + kind: "file", + filePath, + contentType: FAVICON_MIME_TYPES[ext] ?? "application/octet-stream", + cacheControl, + }; +}); + +const findExistingFile = Effect.fnUntraced(function* ( + candidates: ReadonlyArray, + projectCwd: string, +): Effect.fn.Return { + const fileSystem = yield* FileSystem.FileSystem; + for (const candidate of candidates) { + if (!(yield* isPathWithinProject(projectCwd, candidate))) { + continue; } - res.writeHead(200, { - "Content-Type": contentType, - "Cache-Control": "public, max-age=3600", - }); - res.end(data); - }); -} + const fileInfo = yield* fileSystem + .stat(candidate) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (fileInfo?.type === "File") { + return candidate; + } + } + return null; +}); -function serveFallbackFavicon(res: http.ServerResponse): void { - res.writeHead(200, { - "Content-Type": "image/svg+xml", - "Cache-Control": "public, max-age=3600", - }); - res.end(FALLBACK_FAVICON_SVG); -} +export const resolveProjectFaviconRoute = Effect.fnUntraced(function* ( + url: URL, +): Effect.fn.Return { + const path = yield* Path.Path; -export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean { if (url.pathname !== "/api/project-favicon") { - return false; + return null; } const projectCwd = url.searchParams.get("cwd"); if (!projectCwd) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end("Missing cwd parameter"); - return true; + return { + kind: "body", + statusCode: 400, + body: "Missing cwd parameter", + contentType: "text/plain", + }; } - const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => { - if (index >= paths.length) { - onExhausted(); - return; - } - const candidate = paths[index]!; - if (!isPathWithinProject(projectCwd, candidate)) { - tryResolvedPaths(paths, index + 1, onExhausted); - return; - } - fs.stat(candidate, (err, stats) => { - if (err || !stats?.isFile()) { - tryResolvedPaths(paths, index + 1, onExhausted); - return; - } - serveFaviconFile(candidate, res); - }); - }; + const candidatePaths = FAVICON_CANDIDATES.map((candidate) => path.join(projectCwd, candidate)); + const directFile = yield* findExistingFile(candidatePaths, projectCwd); + if (directFile) { + return yield* toFileResult(directFile); + } - const trySourceFiles = (index: number): void => { - if (index >= ICON_SOURCE_FILES.length) { - serveFallbackFavicon(res); - return; + const fileSystem = yield* FileSystem.FileSystem; + for (const sourceFile of ICON_SOURCE_FILES) { + const content = yield* fileSystem + .readFileString(path.join(projectCwd, sourceFile)) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!content) { + continue; } - const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!); - fs.readFile(sourceFile, "utf8", (err, content) => { - if (err) { - trySourceFiles(index + 1); - return; - } - const href = extractIconHref(content); - if (!href) { - trySourceFiles(index + 1); - return; - } - const candidates = resolveIconHref(projectCwd, href); - tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1)); - }); - }; - const tryCandidates = (index: number): void => { - if (index >= FAVICON_CANDIDATES.length) { - trySourceFiles(0); - return; + const href = extractIconHref(content); + if (!href) { + continue; } - const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!); - if (!isPathWithinProject(projectCwd, candidate)) { - tryCandidates(index + 1); - return; - } - fs.stat(candidate, (err, stats) => { - if (err || !stats?.isFile()) { - tryCandidates(index + 1); - return; - } - serveFaviconFile(candidate, res); - }); - }; - tryCandidates(0); - return true; -} + const iconHrefPaths = yield* resolveIconHref(projectCwd, href); + const resolvedFile = yield* findExistingFile(iconHrefPaths, projectCwd); + if (resolvedFile) { + return yield* toFileResult(resolvedFile); + } + } + + return { + kind: "body", + statusCode: 200, + body: FALLBACK_FAVICON_SVG, + contentType: "image/svg+xml", + cacheControl, + }; +}); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts new file mode 100644 index 0000000000..e68e43e823 --- /dev/null +++ b/apps/server/src/server.test.ts @@ -0,0 +1,44 @@ +import type { OrchestrationReadModel } from "@t3tools/contracts"; +import { assert, it, vi } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { recordStartupHeartbeat } from "./server"; +import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; + +it.effect("records a startup heartbeat with thread/project counts", () => + Effect.gen(function* () { + const recordTelemetry = vi.fn( + (_event: string, _properties?: Readonly>) => Effect.void, + ); + const getSnapshot = vi.fn(() => + Effect.succeed({ + snapshotSequence: 2, + projects: [{} as OrchestrationReadModel["projects"][number]], + threads: [ + {} as OrchestrationReadModel["threads"][number], + {} as OrchestrationReadModel["threads"][number], + ], + updatedAt: new Date(1).toISOString(), + } satisfies OrchestrationReadModel), + ); + + yield* recordStartupHeartbeat.pipe( + Effect.provideService(ProjectionSnapshotQuery, { + getSnapshot, + }), + Effect.provideService(AnalyticsService, { + record: recordTelemetry, + flush: Effect.void, + }), + ); + + assert.deepEqual(recordTelemetry.mock.calls[0], [ + "server.boot.heartbeat", + { + threadCount: 2, + projectCount: 1, + }, + ]); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts new file mode 100644 index 0000000000..da46245fda --- /dev/null +++ b/apps/server/src/server.ts @@ -0,0 +1,155 @@ +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect, Layer } from "effect"; +import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; +import http from "node:http"; + +import { ServerConfig } from "./config"; +import { Open, OpenLive } from "./open"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import * as SqlitePersistence from "./persistence/Layers/Sqlite"; +import { ProviderHealthLive } from "./provider/Layers/ProviderHealth"; +import { ServerRuntimeStateLive } from "./serverRuntime"; +import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers"; +import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService"; +import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; +import { makeRoutesLayer } from "./wsServer"; + +const isWildcardHost = (host: string | undefined): boolean => + host === "0.0.0.0" || host === "::" || host === "[::]"; + +const formatHostForUrl = (host: string): string => + host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; + +export const recordStartupHeartbeat = Effect.gen(function* () { + const analytics = yield* AnalyticsService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe( + Effect.map((snapshot) => ({ + threadCount: snapshot.threads.length, + projectCount: snapshot.projects.length, + })), + Effect.catch((cause) => + Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe( + Effect.as({ + threadCount: 0, + projectCount: 0, + }), + ), + ), + ); + + yield* analytics.record("server.boot.heartbeat", { + threadCount, + projectCount, + }); +}); + +const logServerReady = Effect.gen(function* () { + const config = yield* ServerConfig; + const open = yield* Open; + const server = yield* HttpServer.HttpServer; + + if (server.address._tag !== "TcpAddress") { + return; + } + + const { port } = server.address; + const localUrl = `http://localhost:${port}`; + const bindUrl = + config.host && !isWildcardHost(config.host) + ? `http://${formatHostForUrl(config.host)}:${port}` + : localUrl; + + yield* Effect.logInfo("T3 Code running", { + url: bindUrl, + localUrl, + bindHost: config.host ?? "default", + cwd: config.cwd, + mode: config.mode, + stateDir: config.stateDir, + authEnabled: Boolean(config.authToken), + websocketUrl: `${bindUrl}/ws`, + }); + + if (config.noBrowser) { + return; + } + + const target = config.devUrl?.toString() ?? bindUrl; + yield* open.openBrowser(target).pipe( + Effect.catch(() => + Effect.logInfo("browser auto-open unavailable", { + hint: `Open ${target} in your browser.`, + }), + ), + ); +}); + +const startupLayer = Layer.effectDiscard( + Effect.gen(function* () { + yield* logServerReady; + yield* Effect.forkChild(recordStartupHeartbeat); + }), +); + +export const makeNodeHttpServerLayer = Layer.unwrap( + Effect.gen(function* () { + const { host, port } = yield* ServerConfig; + return NodeHttpServer.layer(http.createServer, host ? { host, port } : { port }); + }), +); + +const routesLayer = HttpRouter.serve(makeRoutesLayer, { + disableLogger: true, + disableListenLog: true, +}); + +export const makeServerServicesLayer = () => { + const nodeServicesLayer = NodeServices.layer; + const fetchHttpClientLayer = FetchHttpClient.layer.pipe(Layer.provideMerge(nodeServicesLayer)); + const sqliteLayer = SqlitePersistence.layerConfig.pipe(Layer.provideMerge(nodeServicesLayer)); + const analyticsLayer = AnalyticsServiceLayerLive.pipe( + Layer.provideMerge(fetchHttpClientLayer), + Layer.provideMerge(nodeServicesLayer), + ); + const providerLayer = makeServerProviderLayer().pipe( + Layer.provideMerge(analyticsLayer), + Layer.provideMerge(sqliteLayer), + Layer.provideMerge(nodeServicesLayer), + ); + const runtimeLayer = makeServerRuntimeServicesLayer().pipe( + Layer.provideMerge(providerLayer), + Layer.provideMerge(sqliteLayer), + Layer.provideMerge(nodeServicesLayer), + ); + const providerHealthLayer = ProviderHealthLive.pipe(Layer.provideMerge(nodeServicesLayer)); + const openLayer = OpenLive.pipe(Layer.provideMerge(nodeServicesLayer)); + const baseServicesLayer = Layer.mergeAll( + nodeServicesLayer, + fetchHttpClientLayer, + analyticsLayer, + runtimeLayer, + providerLayer, + providerHealthLayer, + openLayer, + sqliteLayer, + ); + + return Layer.mergeAll( + baseServicesLayer, + ServerRuntimeStateLive.pipe(Layer.provide(baseServicesLayer)), + ); +}; + +export const makeServerAppLayer = ( + servicesLayer: Layer.Layer, +) => + routesLayer.pipe(Layer.provideMerge(startupLayer)).pipe(Layer.provide(servicesLayer)); + +export const makeServerLayer = makeServerAppLayer(makeServerServicesLayer()).pipe( + Layer.provide(makeNodeHttpServerLayer), +); + +export const runServer = Layer.launch(makeServerLayer); diff --git a/apps/server/src/serverLayers.ts b/apps/server/src/serverLayers.ts index ff9b10d96f..365e46d108 100644 --- a/apps/server/src/serverLayers.ts +++ b/apps/server/src/serverLayers.ts @@ -1,8 +1,7 @@ import path from "node:path"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, FileSystem, Layer } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { Effect, FileSystem, Layer } from "effect"; import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery"; import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; @@ -127,5 +126,5 @@ export function makeServerRuntimeServicesLayer() { gitManagerLayer, terminalLayer, KeybindingsLive, - ).pipe(Layer.provideMerge(NodeServices.layer)); + ); } diff --git a/apps/server/src/serverRpc.ts b/apps/server/src/serverRpc.ts new file mode 100644 index 0000000000..354f29ea59 --- /dev/null +++ b/apps/server/src/serverRpc.ts @@ -0,0 +1,322 @@ +import { + ClientOrchestrationCommand, + GitPreparePullRequestThreadInput, + type GitPreparePullRequestThreadResult, + GitPullRequestRefInput, + type GitResolvePullRequestResult, + type OrchestrationCommand, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + type ServerRpcError, + ServerRpcGroup, + TerminalEvent, +} from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect"; +import { clamp } from "effect/Number"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"; +import * as RpcServer from "effect/unstable/rpc/RpcServer"; + +import { createAttachmentId, resolveAttachmentPath } from "./attachmentStore.ts"; +import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; +import { ServerConfig as RuntimeServerConfig } from "./config"; +import { GitCore } from "./git/Services/GitCore.ts"; +import { GitManager } from "./git/Services/GitManager.ts"; +import { parseBase64DataUrl } from "./imageMime.ts"; +import { Keybindings } from "./keybindings"; +import { Open, resolveAvailableEditors } from "./open"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { ProviderHealth } from "./provider/Services/ProviderHealth"; +import { ProviderService } from "./provider/Services/ProviderService"; +import { ServerRuntimeState } from "./serverRuntime"; +import { searchWorkspaceEntries } from "./workspaceEntries"; +import { TerminalManager } from "./terminal/Services/Manager.ts"; +import type { TerminalManagerShape } from "./terminal/Services/Manager.ts"; + +export type ServerRpcRouteRequirements = + | RuntimeServerConfig + | FileSystem.FileSystem + | Path.Path + | GitManager + | GitCore + | Keybindings + | Open + | OrchestrationEngineService + | CheckpointDiffQuery + | ProjectionSnapshotQuery + | ProviderHealth + | ProviderService + | ServerRuntimeState + | TerminalManager; + +function formatRpcError(error: unknown): string { + if (typeof error === "string") { + return error; + } + if (error instanceof Error && error.message.length > 0) { + return error.message; + } + if (typeof error === "object" && error !== null && "message" in error) { + const message = error.message; + if (typeof message === "string" && message.length > 0) { + return message; + } + } + try { + return JSON.stringify(error); + } catch { + return String(error); + } +} + +const serverRpcError = (message: string): ServerRpcError => ({ message }); + +const mapRpcError = (effect: Effect.Effect) => + effect.pipe(Effect.mapError((error) => serverRpcError(formatRpcError(error)))); + +const mapRpcStreamError = (stream: Stream.Stream) => + stream.pipe(Stream.mapError((error) => serverRpcError(formatRpcError(error)))); + +const textResponse = (status: number, body: string) => + HttpServerResponse.text(body, { status, contentType: "text/plain" }); + +const normalizeDispatchCommand = Effect.fn(function* (input: { + readonly command: ClientOrchestrationCommand; +}) { + if (input.command.type !== "thread.turn.start") { + return input.command as OrchestrationCommand; + } + const turnStartCommand = input.command; + + const serverConfig = yield* RuntimeServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const normalizedAttachments = yield* Effect.forEach( + turnStartCommand.message.attachments, + (attachment) => + Effect.gen(function* () { + const parsed = parseBase64DataUrl(attachment.dataUrl); + if (!parsed || !parsed.mimeType.startsWith("image/")) { + return yield* Effect.fail( + serverRpcError(`Invalid image attachment payload for '${attachment.name}'.`), + ); + } + + const bytes = Buffer.from(parsed.base64, "base64"); + if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + return yield* Effect.fail( + serverRpcError(`Image attachment '${attachment.name}' is empty or too large.`), + ); + } + + const attachmentId = createAttachmentId(turnStartCommand.threadId); + if (!attachmentId) { + return yield* Effect.fail(serverRpcError("Failed to create a safe attachment id.")); + } + + const persistedAttachment = { + type: "image" as const, + id: attachmentId, + name: attachment.name, + mimeType: parsed.mimeType.toLowerCase(), + sizeBytes: bytes.byteLength, + }; + + const attachmentPath = resolveAttachmentPath({ + stateDir: serverConfig.stateDir, + attachment: persistedAttachment, + }); + if (!attachmentPath) { + return yield* Effect.fail( + serverRpcError(`Failed to resolve persisted path for '${attachment.name}'.`), + ); + } + + yield* fileSystem + .makeDirectory(path.dirname(attachmentPath), { recursive: true }) + .pipe( + Effect.mapError(() => + serverRpcError(`Failed to create attachment directory for '${attachment.name}'.`), + ), + ); + yield* fileSystem + .writeFile(attachmentPath, bytes) + .pipe( + Effect.mapError(() => + serverRpcError(`Failed to persist attachment '${attachment.name}'.`), + ), + ); + + return persistedAttachment; + }), + { concurrency: 1 }, + ); + + return { + ...turnStartCommand, + message: { + ...turnStartCommand.message, + attachments: normalizedAttachments, + }, + } satisfies OrchestrationCommand; +}); + +const makeTerminalEventStream = (terminalManager: TerminalManagerShape) => + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event: TerminalEvent) => { + Queue.offerUnsafe(queue, event); + }), + (unsubscribe) => Effect.sync(() => unsubscribe()), + ).pipe(Effect.asVoid), + ); + +export const makeServerRpcHandlersLayer = Layer.unwrap( + Effect.gen(function* () { + const serverConfig = yield* RuntimeServerConfig; + const gitManager = yield* GitManager; + const git = yield* GitCore; + const keybindingsManager = yield* Keybindings; + const open = yield* Open; + const orchestrationEngine = yield* OrchestrationEngineService; + const checkpointDiffQuery = yield* CheckpointDiffQuery; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const providerHealth = yield* ProviderHealth; + const serverRuntime = yield* ServerRuntimeState; + const terminalManager = yield* TerminalManager; + + const availableEditors = resolveAvailableEditors(); + + const loadServerConfig = Effect.gen(function* () { + const keybindingsConfig = yield* keybindingsManager.loadConfigState; + const providerStatuses = yield* providerHealth.getStatuses; + return { + cwd: serverConfig.cwd, + keybindingsConfigPath: serverConfig.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers: providerStatuses, + availableEditors, + }; + }); + + return ServerRpcGroup.toLayer({ + getBootstrap: () => Effect.succeed(serverRuntime.bootstrapState), + getServerConfig: () => mapRpcError(loadServerConfig), + upsertKeybinding: (input) => + mapRpcError( + keybindingsManager + .upsertKeybindingRule(input) + .pipe(Effect.map((keybindings) => ({ keybindings, issues: [] }))), + ), + subscribeServerConfig: () => + mapRpcStreamError( + keybindingsManager.changes.pipe( + Stream.mapEffect((event) => + providerHealth.getStatuses.pipe( + Effect.map((providers) => ({ + issues: event.issues, + providers, + })), + ), + ), + ), + ), + getSnapshot: () => mapRpcError(projectionSnapshotQuery.getSnapshot()), + dispatchCommand: (command) => + mapRpcError( + normalizeDispatchCommand({ command }).pipe( + Effect.flatMap((normalizedCommand) => orchestrationEngine.dispatch(normalizedCommand)), + ), + ), + getTurnDiff: (input) => mapRpcError(checkpointDiffQuery.getTurnDiff(input)), + getFullThreadDiff: (input) => mapRpcError(checkpointDiffQuery.getFullThreadDiff(input)), + replayEvents: (input) => + mapRpcError( + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { + maximum: Number.MAX_SAFE_INTEGER, + minimum: 0, + }), + ), + ).pipe(Effect.map((events) => Array.from(events))), + ), + subscribeDomainEvents: () => mapRpcStreamError(orchestrationEngine.streamDomainEvents), + searchEntries: (input) => + mapRpcError( + Effect.tryPromise({ + try: () => searchWorkspaceEntries(input), + catch: (cause) => serverRpcError(`Failed to search workspace entries: ${String(cause)}`), + }), + ), + openInEditor: (input) => mapRpcError(open.openInEditor(input)), + gitStatus: (input) => mapRpcError(gitManager.status(input)), + gitPull: (input) => mapRpcError(git.pullCurrentBranch(input.cwd)), + gitRunStackedAction: (input) => mapRpcError(gitManager.runStackedAction(input)), + gitListBranches: (input) => mapRpcError(git.listBranches(input)), + gitCreateWorktree: (input) => mapRpcError(git.createWorktree(input)), + gitRemoveWorktree: (input) => mapRpcError(git.removeWorktree(input)), + gitCreateBranch: (input) => mapRpcError(git.createBranch(input)), + gitCheckout: (input) => mapRpcError(Effect.scoped(git.checkoutBranch(input))), + gitInit: (input) => mapRpcError(git.initRepo(input)), + gitResolvePullRequest: (input: GitPullRequestRefInput) => + mapRpcError( + gitManager.resolvePullRequest(input) as Effect.Effect< + GitResolvePullRequestResult, + never, + never + >, + ), + gitPreparePullRequestThread: (input: GitPreparePullRequestThreadInput) => + mapRpcError( + gitManager.preparePullRequestThread(input) as Effect.Effect< + GitPreparePullRequestThreadResult, + never, + never + >, + ), + terminalOpen: (input) => mapRpcError(terminalManager.open(input)), + terminalWrite: (input) => mapRpcError(terminalManager.write(input)), + terminalResize: (input) => mapRpcError(terminalManager.resize(input)), + terminalClear: (input) => mapRpcError(terminalManager.clear(input)), + terminalRestart: (input) => mapRpcError(terminalManager.restart(input)), + terminalClose: (input) => mapRpcError(terminalManager.close(input)), + subscribeTerminalEvents: () => mapRpcStreamError(makeTerminalEventStream(terminalManager)), + }); + }), +); + +export const makeServerRpcRouteLayer = Layer.unwrap( + Effect.gen(function* () { + const serverConfig = yield* RuntimeServerConfig; + const { httpEffect, protocol } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; + + const websocketRpcRoute = HttpRouter.add( + "GET", + "/ws", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (!url) { + return textResponse(400, "Invalid WebSocket URL"); + } + if (request.headers.upgrade?.toLowerCase() !== "websocket") { + return textResponse(400, "Expected WebSocket upgrade request"); + } + if (serverConfig.authToken && url.searchParams.get("token") !== serverConfig.authToken) { + return textResponse(401, "Unauthorized WebSocket connection"); + } + return yield* httpEffect; + }), + ); + + return RpcServer.layer(ServerRpcGroup).pipe( + Layer.provide(Layer.succeed(RpcServer.Protocol, protocol)), + Layer.provide(makeServerRpcHandlersLayer), + Layer.provide(RpcSerialization.layerJson), + Layer.provideMerge(websocketRpcRoute), + ); + }).pipe(Effect.provide(RpcSerialization.layerJson)), +); diff --git a/apps/server/src/serverRuntime.ts b/apps/server/src/serverRuntime.ts new file mode 100644 index 0000000000..e416bb05e5 --- /dev/null +++ b/apps/server/src/serverRuntime.ts @@ -0,0 +1,137 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Effect, Exit, Layer, Path, Scope, ServiceMap } from "effect"; + +import { ServerConfig } from "./config"; +import { Keybindings } from "./keybindings"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; +import { ProviderService } from "./provider/Services/ProviderService"; + +export interface ServerBootstrapStateShape { + readonly cwd: string; + readonly projectName: string; + readonly bootstrapProjectId?: ProjectId; + readonly bootstrapThreadId?: ThreadId; +} + +export interface ServerRuntimeStateShape { + readonly bootstrapState: ServerBootstrapStateShape; +} + +export class ServerRuntimeState extends ServiceMap.Service< + ServerRuntimeState, + ServerRuntimeStateShape +>()("t3/serverRuntime/ServerRuntimeState") {} + +const resolveBootstrapState = Effect.fn(function* () { + const serverConfig = yield* ServerConfig; + const path = yield* Path.Path; + const orchestrationEngine = yield* OrchestrationEngineService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + const projectName = path.basename(serverConfig.cwd) || "project"; + let bootstrapProjectId: ProjectId | undefined; + let bootstrapThreadId: ThreadId | undefined; + + if (serverConfig.autoBootstrapProjectFromCwd) { + const snapshot = yield* projectionSnapshotQuery.getSnapshot(); + const existingProject = snapshot.projects.find( + (project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null, + ); + let projectId: ProjectId; + let defaultModel: string; + + if (!existingProject) { + const createdAt = new Date().toISOString(); + projectId = ProjectId.makeUnsafe(crypto.randomUUID()); + defaultModel = "gpt-5-codex"; + yield* orchestrationEngine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + projectId, + title: projectName, + workspaceRoot: serverConfig.cwd, + defaultModel, + createdAt, + }); + } else { + projectId = existingProject.id; + defaultModel = existingProject.defaultModel ?? "gpt-5-codex"; + } + + const refreshedSnapshot = existingProject + ? snapshot + : yield* projectionSnapshotQuery.getSnapshot(); + const existingThread = refreshedSnapshot.threads.find( + (thread) => thread.projectId === projectId && thread.deletedAt === null, + ); + + if (!existingThread) { + const createdAt = new Date().toISOString(); + const threadId = ThreadId.makeUnsafe(crypto.randomUUID()); + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + threadId, + projectId, + title: "New thread", + model: defaultModel, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }); + bootstrapProjectId = projectId; + bootstrapThreadId = threadId; + } else { + bootstrapProjectId = projectId; + bootstrapThreadId = existingThread.id; + } + } + + return { + cwd: serverConfig.cwd, + projectName, + ...(bootstrapProjectId ? { bootstrapProjectId } : {}), + ...(bootstrapThreadId ? { bootstrapThreadId } : {}), + } satisfies ServerBootstrapStateShape; +}); + +export const ServerRuntimeStateLive = Layer.effect( + ServerRuntimeState, + Effect.gen(function* () { + const keybindingsManager = yield* Keybindings; + const orchestrationReactor = yield* OrchestrationReactor; + const providerService = yield* ProviderService; + + yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe( + Effect.catch((error) => + Effect.logWarning("failed to sync keybindings defaults on startup", { + path: error.configPath, + detail: error.detail, + cause: error.cause, + }), + ), + ); + + const startupScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(startupScope, Exit.void)); + yield* Scope.provide(orchestrationReactor.start, startupScope); + yield* Effect.addFinalizer(() => + providerService + .stopAll() + .pipe(Effect.catch((cause) => Effect.logWarning("failed to stop provider service", { cause }))), + ); + + return { + bootstrapState: yield* resolveBootstrapState(), + } satisfies ServerRuntimeStateShape; + }), +); diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index f12792a318..b601325b50 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -1,68 +1,38 @@ -import * as Http from "node:http"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect"; -import { describe, expect, it, afterEach, vi } from "vitest"; -import { createServer } from "./wsServer"; -import WebSocket from "ws"; -import { ServerConfig, type ServerConfigShape } from "./config"; -import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers"; - import { DEFAULT_TERMINAL_ID, - EDITORS, - EventId, - ORCHESTRATION_WS_CHANNELS, - ORCHESTRATION_WS_METHODS, - ProviderItemId, - ThreadId, - TurnId, - WS_CHANNELS, - WS_METHODS, - type WebSocketResponse, type ProviderRuntimeEvent, + ServerRpcGroup, + type ServerConfig as ServerConfigPayload, type ServerProviderStatus, - type KeybindingsConfig, - type ResolvedKeybindingsConfig, - type WsPushChannel, - type WsPushMessage, - type WsPush, + type ServerUpsertKeybindingResult, + type TerminalEvent, + type TerminalOpenInput, + type TerminalSessionSnapshot, + type TerminalWriteInput, } from "@t3tools/contracts"; -import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings"; -import type { - TerminalClearInput, - TerminalCloseInput, - TerminalEvent, - TerminalOpenInput, - TerminalResizeInput, - TerminalSessionSnapshot, - TerminalWriteInput, -} from "@t3tools/contracts"; -import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager"; -import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite"; -import { SqlClient, SqlError } from "effect/unstable/sql"; -import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService"; -import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth"; +import { describe, expect } from "@effect/vitest"; +import { Effect, Fiber, Layer, Stream } from "effect"; +import { HttpClient, HttpServer } from "effect/unstable/http"; +import * as RpcClient from "effect/unstable/rpc/RpcClient"; +import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"; +import { afterEach, it, vi } from "vitest"; + +import { ServerConfig, type ServerConfigShape } from "./config"; import { Open, type OpenShape } from "./open"; -import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; -import type { GitCoreShape } from "./git/Services/GitCore.ts"; -import { GitCore } from "./git/Services/GitCore.ts"; -import { GitCommandError, GitManagerError } from "./git/Errors.ts"; -import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; - -const asEventId = (value: string): EventId => EventId.makeUnsafe(value); -const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); -const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value); -const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); - -const defaultOpenService: OpenShape = { - openBrowser: () => Effect.void, - openInEditor: () => Effect.void, -}; +import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite"; +import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth"; +import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService"; +import { ServerRuntimeStateLive } from "./serverRuntime"; +import { makeServerAppLayer } from "./server"; +import { makeServerRuntimeServicesLayer } from "./serverLayers"; +import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager"; const defaultProviderStatuses: ReadonlyArray = [ { @@ -78,6 +48,23 @@ const defaultProviderHealthService: ProviderHealthShape = { getStatuses: Effect.succeed(defaultProviderStatuses), }; +const defaultOpenService: OpenShape = { + openBrowser: () => Effect.void, + openInEditor: () => Effect.void, +}; + +const defaultProviderService: ProviderServiceShape = { + startSession: () => Effect.die(new Error("startSession not implemented in test")), + sendTurn: () => Effect.die(new Error("sendTurn not implemented in test")), + interruptTurn: () => Effect.die(new Error("interruptTurn not implemented in test")), + respondToRequest: () => Effect.die(new Error("respondToRequest not implemented in test")), + stopSession: () => Effect.die(new Error("stopSession not implemented in test")), + listSessions: () => Effect.succeed([]), + rollbackConversation: () => Effect.die(new Error("rollbackConversation not implemented in test")), + stopAll: () => Effect.void, + streamEvents: Stream.empty as Stream.Stream, +}; + class MockTerminalManager implements TerminalManagerShape { private readonly sessions = new Map(); private readonly listeners = new Set<(event: TerminalEvent) => void>(); @@ -86,16 +73,12 @@ class MockTerminalManager implements TerminalManagerShape { return `${threadId}\u0000${terminalId}`; } - emitEvent(event: TerminalEvent): void { + private emit(event: TerminalEvent): void { for (const listener of this.listeners) { listener(event); } } - subscriptionCount(): number { - return this.listeners.size; - } - readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) => Effect.sync(() => { const now = new Date().toISOString(); @@ -113,7 +96,7 @@ class MockTerminalManager implements TerminalManagerShape { }; this.sessions.set(this.key(input.threadId, terminalId), snapshot); queueMicrotask(() => { - this.emitEvent({ + this.emit({ type: "started", threadId: input.threadId, terminalId, @@ -127,12 +110,11 @@ class MockTerminalManager implements TerminalManagerShape { readonly write: TerminalManagerShape["write"] = (input: TerminalWriteInput) => Effect.sync(() => { const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const existing = this.sessions.get(this.key(input.threadId, terminalId)); - if (!existing) { - throw new Error(`Unknown terminal thread: ${input.threadId}`); + if (!this.sessions.has(this.key(input.threadId, terminalId))) { + throw new Error(`Unknown terminal ${input.threadId}/${terminalId}`); } queueMicrotask(() => { - this.emitEvent({ + this.emit({ type: "output", threadId: input.threadId, terminalId, @@ -142,61 +124,10 @@ class MockTerminalManager implements TerminalManagerShape { }); }); - readonly resize: TerminalManagerShape["resize"] = (_input: TerminalResizeInput) => Effect.void; - - readonly clear: TerminalManagerShape["clear"] = (input: TerminalClearInput) => - Effect.sync(() => { - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - queueMicrotask(() => { - this.emitEvent({ - type: "cleared", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - }); - }); - }); - - readonly restart: TerminalManagerShape["restart"] = (input: TerminalOpenInput) => - Effect.sync(() => { - const now = new Date().toISOString(); - const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; - const snapshot: TerminalSessionSnapshot = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - status: "running", - pid: 5252, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emitEvent({ - type: "restarted", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - }); - - readonly close: TerminalManagerShape["close"] = (input: TerminalCloseInput) => - Effect.sync(() => { - if (input.terminalId) { - this.sessions.delete(this.key(input.threadId, input.terminalId)); - return; - } - for (const key of this.sessions.keys()) { - if (key.startsWith(`${input.threadId}\u0000`)) { - this.sessions.delete(key); - } - } - }); + readonly resize: TerminalManagerShape["resize"] = () => Effect.void; + readonly clear: TerminalManagerShape["clear"] = () => Effect.void; + readonly restart: TerminalManagerShape["restart"] = (input) => this.open(input); + readonly close: TerminalManagerShape["close"] = () => Effect.void; readonly subscribe: TerminalManagerShape["subscribe"] = (listener) => Effect.sync(() => { @@ -209,1607 +140,258 @@ class MockTerminalManager implements TerminalManagerShape { readonly dispose: TerminalManagerShape["dispose"] = Effect.void; } -// --------------------------------------------------------------------------- -// WebSocket test harness -// -// Incoming messages are split into two channels: -// - pushChannel: server push envelopes (type === "push") -// - responseChannel: request/response envelopes (have an "id" field) -// -// This means sendRequest never has to skip push messages and waitForPush -// never has to skip response messages, eliminating a class of ordering bugs. -// --------------------------------------------------------------------------- +const makeRpcProtocolLayer = (wsUrl: string) => + RpcClient.layerProtocolSocket().pipe( + Layer.provide(NodeSocket.layerWebSocket(wsUrl)), + Layer.provide(RpcSerialization.layerJson), + ); -interface MessageChannel { - queue: T[]; - waiters: Array<{ - resolve: (value: T) => void; - reject: (error: Error) => void; - timeoutId: ReturnType | null; - }>; -} +const makeServerRpcClient = RpcClient.make(ServerRpcGroup); +type ServerRpcClient = Effect.Success; -interface SocketChannels { - push: MessageChannel; - response: MessageChannel; -} +const withRpcClient = ( + wsUrl: string, + f: (client: ServerRpcClient) => Effect.Effect, +): Effect.Effect => + Effect.scoped( + makeServerRpcClient.pipe( + Effect.flatMap(f), + Effect.provide(makeRpcProtocolLayer(wsUrl)), + ), + ).pipe(Effect.orDie) as Effect.Effect; -const channelsBySocket = new WeakMap(); +const getServerConfigEffect = (client: ServerRpcClient) => { + const typedClient = client as ServerRpcClient & { + readonly getServerConfig: (_: undefined) => Effect.Effect; + }; + return typedClient.getServerConfig(undefined); +}; -function enqueue(channel: MessageChannel, item: T) { - const waiter = channel.waiters.shift(); - if (waiter) { - if (waiter.timeoutId !== null) clearTimeout(waiter.timeoutId); - waiter.resolve(item); - return; - } - channel.queue.push(item); -} - -function dequeue(channel: MessageChannel, timeoutMs: number): Promise { - const queued = channel.queue.shift(); - if (queued !== undefined) { - return Promise.resolve(queued); - } - - return new Promise((resolve, reject) => { - const waiter = { - resolve, - reject, - timeoutId: setTimeout(() => { - const index = channel.waiters.indexOf(waiter); - if (index >= 0) channel.waiters.splice(index, 1); - reject(new Error(`Timed out waiting for WebSocket message after ${timeoutMs}ms`)); - }, timeoutMs) as ReturnType, - }; - channel.waiters.push(waiter); - }); -} - -function isWsPushEnvelope(message: unknown): message is WsPush { - if (typeof message !== "object" || message === null) return false; - if (!("type" in message) || !("channel" in message)) return false; - return (message as { type?: unknown }).type === "push"; -} - -function asWebSocketResponse(message: unknown): WebSocketResponse | null { - if (typeof message !== "object" || message === null) return null; - if (!("id" in message)) return null; - const id = (message as { id?: unknown }).id; - if (typeof id !== "string") return null; - return message as WebSocketResponse; -} - -function connectWsOnce(port: number, token?: string): Promise { - return new Promise((resolve, reject) => { - const query = token ? `?token=${encodeURIComponent(token)}` : ""; - const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`); - const channels: SocketChannels = { - push: { queue: [], waiters: [] }, - response: { queue: [], waiters: [] }, - }; - channelsBySocket.set(ws, channels); - - ws.on("message", (raw) => { - const parsed = JSON.parse(String(raw)); - if (isWsPushEnvelope(parsed)) { - enqueue(channels.push, parsed); - } else { - const response = asWebSocketResponse(parsed); - if (response) { - enqueue(channels.response, response); - } - } +const upsertKeybindingEffect = (client: ServerRpcClient) => { + const typedClient = client as ServerRpcClient & { + readonly upsertKeybinding: ( + input: { + readonly key: "mod+shift+y"; + readonly command: "chat.new"; + }, + ) => Effect.Effect; + }; + return typedClient.upsertKeybinding({ + key: "mod+shift+y", + command: "chat.new", }); +}; - ws.once("open", () => resolve(ws)); - ws.once("error", () => reject(new Error("WebSocket connection failed"))); +interface TestServerContext { + readonly client: HttpClient.HttpClient; + readonly wsUrl: string; +} + +const tempDirs: string[] = []; + +function makeTempDir(prefix: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +const makeTestServicesLayer = (options: { + readonly providerHealth: ProviderHealthShape; + readonly providerService: ProviderServiceShape; + readonly open: OpenShape; + readonly terminalManager?: TerminalManagerShape; +}) => { + const providerLayer = Layer.succeed(ProviderService, options.providerService); + const providerHealthLayer = Layer.succeed(ProviderHealth, options.providerHealth); + const openLayer = Layer.succeed(Open, options.open); + const runtimeOverrides = options.terminalManager + ? Layer.succeed(TerminalManager, options.terminalManager) + : Layer.empty; + const nodeServicesLayer = NodeServices.layer; + const providerBackedRuntimeLayer = makeServerRuntimeServicesLayer().pipe( + Layer.provideMerge(providerLayer), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provideMerge(nodeServicesLayer), + ); + const baseServicesLayer = Layer.mergeAll( + nodeServicesLayer, + providerBackedRuntimeLayer, + providerLayer, + providerHealthLayer, + SqlitePersistenceMemory, + openLayer, + runtimeOverrides, + ); + + return Layer.mergeAll( + baseServicesLayer, + ServerRuntimeStateLive.pipe(Layer.provide(baseServicesLayer)), + ); +}; + +function withTestServer( + options: { + readonly cwd?: string; + readonly autoBootstrapProjectFromCwd?: boolean; + readonly authToken?: string; + readonly stateDir?: string; + readonly staticDir?: string; + readonly providerHealth?: ProviderHealthShape; + readonly providerService?: ProviderServiceShape; + readonly open?: OpenShape; + readonly terminalManager?: TerminalManagerShape; + } = {}, + run: (context: TestServerContext) => Effect.Effect, +): Effect.Effect { + const stateDir = options.stateDir ?? makeTempDir("t3code-rpc-state-"); + const serverConfig = { + mode: "web", + port: 0, + host: undefined, + cwd: options.cwd ?? "/test/project", + keybindingsConfigPath: path.join(stateDir, "keybindings.json"), + stateDir, + staticDir: options.staticDir, + devUrl: undefined, + noBrowser: true, + authToken: options.authToken, + autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false, + logWebSocketEvents: false, + } satisfies ServerConfigShape; + const servicesLayer = makeTestServicesLayer({ + providerHealth: options.providerHealth ?? defaultProviderHealthService, + providerService: options.providerService ?? defaultProviderService, + open: options.open ?? defaultOpenService, + ...(options.terminalManager ? { terminalManager: options.terminalManager } : {}), }); -} + const appLayer = makeServerAppLayer(servicesLayer); -async function connectWs(port: number, token?: string, attempts = 5): Promise { - let lastError: unknown = new Error("WebSocket connection failed"); - - for (let attempt = 0; attempt < attempts; attempt += 1) { - try { - return await connectWsOnce(port, token); - } catch (error) { - lastError = error; - if (attempt < attempts - 1) { - await new Promise((resolve) => setTimeout(resolve, 25)); - } - } - } - - throw lastError; -} - -/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */ -async function connectAndAwaitWelcome( - port: number, - token?: string, -): Promise<[WebSocket, WsPushMessage]> { - const ws = await connectWs(port, token); - const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome); - return [ws, welcome]; -} - -async function sendRequest( - ws: WebSocket, - method: string, - params?: unknown, -): Promise { - const channels = channelsBySocket.get(ws); - if (!channels) throw new Error("WebSocket not initialized"); - - const id = crypto.randomUUID(); - const body = - method === ORCHESTRATION_WS_METHODS.dispatchCommand - ? { _tag: method, command: params } - : params && typeof params === "object" && !Array.isArray(params) - ? { _tag: method, ...(params as Record) } - : { _tag: method }; - ws.send(JSON.stringify({ id, body })); - - // Response channel only contains responses — no push filtering needed - while (true) { - const response = await dequeue(channels.response, 60_000); - if (response.id === id || response.id === "unknown") { - return response; - } - } -} - -async function waitForPush( - ws: WebSocket, - channel: C, - predicate?: (push: WsPushMessage) => boolean, - maxMessages = 120, - idleTimeoutMs = 5_000, -): Promise> { - const channels = channelsBySocket.get(ws); - if (!channels) throw new Error("WebSocket not initialized"); - - for (let remaining = maxMessages; remaining > 0; remaining--) { - const push = await dequeue(channels.push, idleTimeoutMs); - if (push.channel !== channel) continue; - const typed = push as WsPushMessage; - if (!predicate || predicate(typed)) return typed; - } - throw new Error(`Timed out waiting for push on ${channel}`); -} - -async function rewriteKeybindingsAndWaitForPush( - ws: WebSocket, - keybindingsPath: string, - contents: string, - predicate: (push: WsPushMessage) => boolean, - attempts = 3, -): Promise> { - let lastError: unknown; - for (let attempt = 0; attempt < attempts; attempt++) { - fs.writeFileSync(keybindingsPath, contents, "utf8"); - try { - return await waitForPush(ws, WS_CHANNELS.serverConfigUpdated, predicate, 20, 3_000); - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -async function requestPath( - port: number, - requestPath: string, -): Promise<{ statusCode: number; body: string }> { - return new Promise((resolve, reject) => { - const req = Http.request( - { - hostname: "127.0.0.1", - port, - path: requestPath, - method: "GET", - }, - (res) => { - const chunks: Buffer[] = []; - res.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - res.on("end", () => { - resolve({ - statusCode: res.statusCode ?? 0, - body: Buffer.concat(chunks).toString("utf8"), - }); - }); - }, - ); - req.once("error", reject); - req.end(); - }); -} - -function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig { - const resolved: Array = []; - for (const binding of bindings) { - const compiled = compileResolvedKeybindingRule(binding); - if (!compiled) { - throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`); - } - resolved.push(compiled); - } - return resolved; -} - -const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]); -const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id)); - -function expectAvailableEditors(value: unknown): void { - expect(Array.isArray(value)).toBe(true); - for (const editorId of value as unknown[]) { - expect(typeof editorId).toBe("string"); - expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true); - } -} - -describe("WebSocket Server", () => { - let server: Http.Server | null = null; - let serverScope: Scope.Closeable | null = null; - const connections: WebSocket[] = []; - const tempDirs: string[] = []; - - function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; - } - - async function createTestServer( - options: { - persistenceLayer?: Layer.Layer< - SqlClient.SqlClient, - SqlError.SqlError | MigrationError | PlatformError.PlatformError - >; - cwd?: string; - autoBootstrapProjectFromCwd?: boolean; - logWebSocketEvents?: boolean; - devUrl?: string; - authToken?: string; - stateDir?: string; - staticDir?: string; - providerLayer?: Layer.Layer; - providerHealth?: ProviderHealthShape; - open?: OpenShape; - gitManager?: GitManagerShape; - gitCore?: Pick; - terminalManager?: TerminalManagerShape; - } = {}, - ): Promise { - if (serverScope) { - throw new Error("Test server is already running"); - } - - const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-"); - const scope = await Effect.runPromise(Scope.make("sequential")); - const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory; - const providerLayer = options.providerLayer ?? makeServerProviderLayer(); - const providerHealthLayer = Layer.succeed( - ProviderHealth, - options.providerHealth ?? defaultProviderHealthService, - ); - const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService); - const serverConfigLayer = Layer.succeed(ServerConfig, { - mode: "web", - port: 0, - host: undefined, - cwd: options.cwd ?? "/test/project", - keybindingsConfigPath: path.join(stateDir, "keybindings.json"), - stateDir, - staticDir: options.staticDir, - devUrl: options.devUrl ? new URL(options.devUrl) : undefined, - noBrowser: true, - authToken: options.authToken, - autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false, - logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl), - } satisfies ServerConfigShape); - const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer)); - const runtimeOverrides = Layer.mergeAll( - options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty, - options.gitCore - ? Layer.succeed(GitCore, options.gitCore as unknown as GitCoreShape) - : Layer.empty, - options.terminalManager - ? Layer.succeed(TerminalManager, options.terminalManager) - : Layer.empty, + return Effect.gen(function* () { + const testServer = yield* Layer.build(NodeHttpServer.layerTest).pipe(Effect.orDie); + yield* Layer.build(appLayer).pipe( + Effect.provide(testServer), + Effect.provideService(ServerConfig, serverConfig), + Effect.orDie, ); - const runtimeLayer = Layer.merge( - Layer.merge( - makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)), - infrastructureLayer, - ), - runtimeOverrides, - ); - const dependenciesLayer = Layer.empty.pipe( - Layer.provideMerge(runtimeLayer), - Layer.provideMerge(providerHealthLayer), - Layer.provideMerge(openLayer), - Layer.provideMerge(serverConfigLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provideMerge(NodeServices.layer), - ); - const runtimeServices = await Effect.runPromise( - Layer.build(dependenciesLayer).pipe(Scope.provide(scope)), - ); - - try { - const runtime = await Effect.runPromise( - createServer().pipe(Effect.provide(runtimeServices), Scope.provide(scope)), - ); - serverScope = scope; - return runtime; - } catch (error) { - await Effect.runPromise(Scope.close(scope, Exit.void)); - throw error; + const server = yield* HttpServer.HttpServer.asEffect().pipe(Effect.provide(testServer)); + const client = yield* HttpClient.HttpClient.asEffect().pipe(Effect.provide(testServer)); + if (server.address._tag !== "TcpAddress") { + return yield* Effect.die(new Error("Expected TCP test server address")); } - } - async function closeTestServer() { - if (!serverScope) return; - const scope = serverScope; - serverScope = null; - await Effect.runPromise(Scope.close(scope, Exit.void)); - } + const tokenSuffix = options.authToken ? `?token=${options.authToken}` : ""; + return yield* run({ + client, + wsUrl: `ws://127.0.0.1:${server.address.port}/ws${tokenSuffix}`, + }); + }).pipe(Effect.scoped, Effect.orDie) as Effect.Effect; +} - afterEach(async () => { - for (const ws of connections) { - ws.close(); - } - connections.length = 0; - await closeTestServer(); - server = null; +describe("wsServer", () => { + afterEach(() => { for (const dir of tempDirs.splice(0, tempDirs.length)) { fs.rmSync(dir, { recursive: true, force: true }); } vi.restoreAllMocks(); }); - it("sends welcome message on connect", async () => { - server = await createTestServer({ cwd: "/test/project" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const [ws, welcome] = await connectAndAwaitWelcome(port); - connections.push(ws); - - expect(welcome.type).toBe("push"); - expect(welcome.data).toEqual({ - cwd: "/test/project", - projectName: "project", - }); - }); - - it("serves persisted attachments from stateDir", async () => { - const stateDir = makeTempDir("t3code-state-attachments-"); - const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png"); - fs.mkdirSync(path.dirname(attachmentPath), { recursive: true }); - fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment")); - - server = await createTestServer({ cwd: "/test/project", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const response = await fetch(`http://127.0.0.1:${port}/attachments/thread-a/message-a/0.png`); - expect(response.status).toBe(200); - expect(response.headers.get("content-type")).toContain("image/png"); - const bytes = Buffer.from(await response.arrayBuffer()); - expect(bytes).toEqual(Buffer.from("hello-attachment")); - }); - - it("serves persisted attachments for URL-encoded paths", async () => { - const stateDir = makeTempDir("t3code-state-attachments-encoded-"); - const attachmentPath = path.join( - stateDir, - "attachments", - "thread%20folder", - "message%20folder", - "file%20name.png", - ); - fs.mkdirSync(path.dirname(attachmentPath), { recursive: true }); - fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment")); - - server = await createTestServer({ cwd: "/test/project", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const response = await fetch( - `http://127.0.0.1:${port}/attachments/thread%20folder/message%20folder/file%20name.png`, - ); - expect(response.status).toBe(200); - expect(response.headers.get("content-type")).toContain("image/png"); - const bytes = Buffer.from(await response.arrayBuffer()); - expect(bytes).toEqual(Buffer.from("hello-encoded-attachment")); - }); - - it("serves static index for root path", async () => { - const stateDir = makeTempDir("t3code-state-static-root-"); - const staticDir = makeTempDir("t3code-static-root-"); - fs.writeFileSync(path.join(staticDir, "index.html"), "

static-root

", "utf8"); - - server = await createTestServer({ cwd: "/test/project", stateDir, staticDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const response = await fetch(`http://127.0.0.1:${port}/`); - expect(response.status).toBe(200); - expect(await response.text()).toContain("static-root"); - }); - - it("rejects static path traversal attempts", async () => { - const stateDir = makeTempDir("t3code-state-static-traversal-"); - const staticDir = makeTempDir("t3code-static-traversal-"); - fs.writeFileSync(path.join(staticDir, "index.html"), "

safe

", "utf8"); - - server = await createTestServer({ cwd: "/test/project", stateDir, staticDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const response = await requestPath(port, "/..%2f..%2fetc/passwd"); - expect(response.statusCode).toBe(400); - expect(response.body).toBe("Invalid static file path"); - }); - - it("bootstraps the cwd project on startup when enabled", async () => { - server = await createTestServer({ - cwd: "/test/bootstrap-workspace", - autoBootstrapProjectFromCwd: true, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const [ws, welcome] = await connectAndAwaitWelcome(port); - connections.push(ws); - expect(welcome.data).toEqual( - expect.objectContaining({ - cwd: "/test/bootstrap-workspace", - projectName: "bootstrap-workspace", - bootstrapProjectId: expect.any(String), - bootstrapThreadId: expect.any(String), - }), - ); - - const snapshotResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getSnapshot); - expect(snapshotResponse.error).toBeUndefined(); - const snapshot = snapshotResponse.result as { - projects: Array<{ - id: string; - workspaceRoot: string; - title: string; - defaultModel: string | null; - }>; - threads: Array<{ - id: string; - projectId: string; - title: string; - model: string; - branch: string | null; - worktreePath: string | null; - }>; - }; - const bootstrapProjectId = (welcome.data as { bootstrapProjectId?: string }).bootstrapProjectId; - const bootstrapThreadId = (welcome.data as { bootstrapThreadId?: string }).bootstrapThreadId; - expect(bootstrapProjectId).toBeDefined(); - expect(bootstrapThreadId).toBeDefined(); - - expect(snapshot.projects).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - id: bootstrapProjectId, - workspaceRoot: "/test/bootstrap-workspace", - title: "bootstrap-workspace", - defaultModel: "gpt-5-codex", + it("serves the health route through the exported app layer", async () => { + await Effect.runPromise( + withTestServer({}, ({ client }) => + Effect.gen(function* () { + const response = yield* client.get("/health").pipe(Effect.orDie); + const body = yield* response.text; + expect(response.status).toBe(200); + expect(JSON.parse(body)).toEqual({ ok: true }); }), - ]), - ); - expect(snapshot.threads).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - id: bootstrapThreadId, - projectId: bootstrapProjectId, - title: "New thread", - model: "gpt-5-codex", - branch: null, - worktreePath: null, - }), - ]), + ), ); }); - it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => { - const stateDir = makeTempDir("t3code-state-bootstrap-existing-"); - const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe( - Layer.provide(NodeServices.layer), - ); - const cwd = "/test/bootstrap-existing"; - - server = await createTestServer({ - cwd, - stateDir, - persistenceLayer, - autoBootstrapProjectFromCwd: true, - }); - let addr = server.address(); - let port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const [firstWs, firstWelcome] = await connectAndAwaitWelcome(port); - connections.push(firstWs); - const firstBootstrapProjectId = (firstWelcome.data as { bootstrapProjectId?: string }) - .bootstrapProjectId; - const firstBootstrapThreadId = (firstWelcome.data as { bootstrapThreadId?: string }) - .bootstrapThreadId; - expect(firstBootstrapProjectId).toBeDefined(); - expect(firstBootstrapThreadId).toBeDefined(); - - firstWs.close(); - await closeTestServer(); - server = null; - - server = await createTestServer({ - cwd, - stateDir, - persistenceLayer, - autoBootstrapProjectFromCwd: true, - }); - addr = server.address(); - port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const [secondWs, secondWelcome] = await connectAndAwaitWelcome(port); - connections.push(secondWs); - expect(secondWelcome.data).toEqual( - expect.objectContaining({ - cwd, - projectName: "bootstrap-existing", - bootstrapProjectId: firstBootstrapProjectId, - bootstrapThreadId: firstBootstrapThreadId, - }), - ); - }); - - it("logs outbound websocket push events in dev mode", async () => { - const logSpy = vi.spyOn(console, "log").mockImplementation(() => { - // Keep test output clean while verifying websocket logs. - }); - - server = await createTestServer({ - cwd: "/test/project", - devUrl: "http://localhost:5173", - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - expect(port).toBeGreaterThan(0); - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - expect( - logSpy.mock.calls.some(([message]) => { - if (typeof message !== "string") return false; - return ( - message.includes("[ws]") && - message.includes("outgoing push") && - message.includes(`channel="${WS_CHANNELS.serverWelcome}"`) - ); - }), - ).toBe(true); - }); - - it("responds to server.getConfig", async () => { - const stateDir = makeTempDir("t3code-state-get-config-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync(keybindingsPath, "[]", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindingsConfigPath: keybindingsPath, - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - issues: [], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - }); - - it("bootstraps default keybindings file when missing", async () => { - const stateDir = makeTempDir("t3code-state-bootstrap-keybindings-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - expect(fs.existsSync(keybindingsPath)).toBe(false); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindingsConfigPath: keybindingsPath, - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - issues: [], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - - const persistedConfig = JSON.parse( - fs.readFileSync(keybindingsPath, "utf8"), - ) as KeybindingsConfig; - expect(persistedConfig).toEqual(DEFAULT_KEYBINDINGS); - }); - - it("falls back to defaults and reports malformed keybindings config issues", async () => { - const stateDir = makeTempDir("t3code-state-malformed-keybindings-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync(keybindingsPath, "{ not-json", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindingsConfigPath: keybindingsPath, - keybindings: DEFAULT_RESOLVED_KEYBINDINGS, - issues: [ + it("exposes bootstrap state and orchestration snapshot over websocket rpc", async () => { + await Effect.runPromise( + withTestServer( { - kind: "keybindings.malformed-config", - message: expect.stringContaining("expected JSON array"), + cwd: "/workspace/example-project", + autoBootstrapProjectFromCwd: true, }, - ], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json"); - }); - - it("ignores invalid keybinding entries but keeps valid entries and reports issues", async () => { - const stateDir = makeTempDir("t3code-state-partial-invalid-keybindings-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync( - keybindingsPath, - JSON.stringify([ - { key: "mod+j", command: "terminal.toggle" }, - { key: "mod+shift+d+o", command: "terminal.new" }, - { key: "mod+x", command: "not-a-real-command" }, - ]), - "utf8", - ); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - const result = response.result as { - cwd: string; - keybindingsConfigPath: string; - keybindings: ResolvedKeybindingsConfig; - issues: Array<{ kind: string; index?: number; message: string }>; - providers: ReadonlyArray; - availableEditors: unknown; - }; - expect(result.cwd).toBe("/my/workspace"); - expect(result.keybindingsConfigPath).toBe(keybindingsPath); - expect(result.issues).toEqual([ - { - kind: "keybindings.invalid-entry", - index: 1, - message: expect.any(String), - }, - { - kind: "keybindings.invalid-entry", - index: 2, - message: expect.any(String), - }, - ]); - expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length); - expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true); - expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true); - expect(result.providers).toEqual(defaultProviderStatuses); - expectAvailableEditors(result.availableEditors); - }); - - it("pushes server.configUpdated issues when keybindings file changes", async () => { - const stateDir = makeTempDir("t3code-state-keybindings-watch-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync(keybindingsPath, "[]", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const malformedPush = await rewriteKeybindingsAndWaitForPush( - ws, - keybindingsPath, - "{ not-json", - (push) => - Array.isArray(push.data.issues) && - Boolean(push.data.issues[0]) && - push.data.issues[0]!.kind === "keybindings.malformed-config", - ); - expect(malformedPush.data).toEqual({ - issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }], - providers: defaultProviderStatuses, - }); - - const successPush = await rewriteKeybindingsAndWaitForPush( - ws, - keybindingsPath, - "[]", - (push) => Array.isArray(push.data.issues) && push.data.issues.length === 0, - ); - expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses }); - }); - - it("routes shell.openInEditor through the injected open service", async () => { - const openCalls: Array<{ cwd: string; editor: string }> = []; - const openService: OpenShape = { - openBrowser: () => Effect.void, - openInEditor: (input) => { - openCalls.push({ cwd: input.cwd, editor: input.editor }); - return Effect.void; - }, - }; - - server = await createTestServer({ cwd: "/my/workspace", open: openService }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.shellOpenInEditor, { - cwd: "/my/workspace", - editor: "cursor", - }); - expect(response.error).toBeUndefined(); - expect(openCalls).toEqual([{ cwd: "/my/workspace", editor: "cursor" }]); - }); - - it("reads keybindings from the configured state directory", async () => { - const stateDir = makeTempDir("t3code-state-keybindings-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync( - keybindingsPath, - JSON.stringify([ - { key: "cmd+j", command: "terminal.toggle" }, - { key: "mod+d", command: "terminal.split", when: "terminalFocus" }, - { key: "mod+n", command: "terminal.new", when: "terminalFocus" }, - ]), - "utf8", - ); - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(response.error).toBeUndefined(); - const persistedConfig = JSON.parse( - fs.readFileSync(keybindingsPath, "utf8"), - ) as KeybindingsConfig; - expect(response.result).toEqual({ - cwd: "/my/workspace", - keybindingsConfigPath: keybindingsPath, - keybindings: compileKeybindings(persistedConfig), - issues: [], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - }); - - it("upserts keybinding rules and updates cached server config", async () => { - const stateDir = makeTempDir("t3code-state-upsert-keybinding-"); - const keybindingsPath = path.join(stateDir, "keybindings.json"); - fs.writeFileSync( - keybindingsPath, - JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), - "utf8", - ); - - server = await createTestServer({ cwd: "/my/workspace", stateDir }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, { - key: "mod+shift+r", - command: "script.run-tests.run", - }); - expect(upsertResponse.error).toBeUndefined(); - const persistedConfig = JSON.parse( - fs.readFileSync(keybindingsPath, "utf8"), - ) as KeybindingsConfig; - const persistedCommands = new Set(persistedConfig.map((entry) => entry.command)); - for (const defaultRule of DEFAULT_KEYBINDINGS) { - expect(persistedCommands.has(defaultRule.command)).toBe(true); - } - expect(persistedCommands.has("script.run-tests.run")).toBe(true); - expect(upsertResponse.result).toEqual({ - keybindings: compileKeybindings(persistedConfig), - issues: [], - }); - - const configResponse = await sendRequest(ws, WS_METHODS.serverGetConfig); - expect(configResponse.error).toBeUndefined(); - expect(configResponse.result).toEqual({ - cwd: "/my/workspace", - keybindingsConfigPath: keybindingsPath, - keybindings: compileKeybindings(persistedConfig), - issues: [], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - }); - expectAvailableEditors( - (configResponse.result as { availableEditors: unknown }).availableEditors, - ); - }); - - it("returns error for unknown methods", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, "nonexistent.method"); - expect(response.error).toBeDefined(); - expect(response.error!.message).toContain("Invalid request format"); - }); - - it("returns error when requesting turn diff for unknown thread", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, { - threadId: "thread-missing", - fromTurnCount: 1, - toTurnCount: 2, - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("Thread 'thread-missing' not found."); - }); - - it("returns error when requesting turn diff with an inverted range", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, { - threadId: "thread-any", - fromTurnCount: 2, - toTurnCount: 1, - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain( - "fromTurnCount must be less than or equal to toTurnCount", - ); - }); - - it("returns error when requesting full thread diff for unknown thread", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getFullThreadDiff, { - threadId: "thread-missing", - toTurnCount: 2, - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("Thread 'thread-missing' not found."); - }); - - it("returns retryable error when requested turn exceeds current checkpoint turn count", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const workspaceRoot = makeTempDir("t3code-ws-diff-project-"); - const createdAt = new Date().toISOString(); - const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "project.create", - commandId: "cmd-diff-project-create", - projectId: "project-diff", - title: "Diff Project", - workspaceRoot, - defaultModel: "gpt-5-codex", - createdAt, - }); - expect(createProjectResponse.error).toBeUndefined(); - const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "thread.create", - commandId: "cmd-diff-thread-create", - threadId: "thread-diff", - projectId: "project-diff", - title: "Diff Thread", - model: "gpt-5-codex", - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt, - }); - expect(createThreadResponse.error).toBeUndefined(); - - const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.getTurnDiff, { - threadId: "thread-diff", - fromTurnCount: 0, - toTurnCount: 1, - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("exceeds current turn count"); - }); - - it("keeps orchestration domain push behavior for provider runtime events", async () => { - const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); - const emitRuntimeEvent = (event: ProviderRuntimeEvent) => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event)); - }; - const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - const providerService: ProviderServiceShape = { - startSession: (threadId) => - Effect.succeed({ - provider: "codex", - status: "ready", - runtimeMode: "full-access", - threadId, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }), - sendTurn: ({ threadId }) => - Effect.succeed({ - threadId, - turnId: asTurnId("provider-turn-1"), - }), - interruptTurn: () => unsupported(), - respondToRequest: () => unsupported(), - respondToUserInput: () => unsupported(), - stopSession: () => unsupported(), - listSessions: () => Effect.succeed([]), - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), - rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), - }; - const providerLayer = Layer.succeed(ProviderService, providerService); - - server = await createTestServer({ - cwd: "/test", - providerLayer, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const workspaceRoot = makeTempDir("t3code-ws-project-"); - const createdAt = new Date().toISOString(); - const createProjectResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "project.create", - commandId: "cmd-ws-project-create", - projectId: "project-1", - title: "WS Project", - workspaceRoot, - defaultModel: "gpt-5-codex", - createdAt, - }); - expect(createProjectResponse.error).toBeUndefined(); - const createThreadResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "thread.create", - commandId: "cmd-ws-runtime-thread-create", - threadId: "thread-1", - projectId: "project-1", - title: "Thread 1", - model: "gpt-5-codex", - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt, - }); - expect(createThreadResponse.error).toBeUndefined(); - - const startTurnResponse = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { - type: "thread.turn.start", - commandId: "cmd-ws-runtime-turn-start", - threadId: "thread-1", - message: { - messageId: "msg-ws-runtime-1", - role: "user", - text: "hello", - attachments: [], - }, - assistantDeliveryMode: "streaming", - runtimeMode: "approval-required", - interactionMode: "default", - createdAt, - }); - expect(startTurnResponse.error).toBeUndefined(); - - await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => { - const event = push.data as { type?: string }; - return event.type === "thread.session-set"; - }); - - emitRuntimeEvent({ - type: "content.delta", - eventId: asEventId("evt-ws-runtime-message-delta"), - provider: "codex", - threadId: asThreadId("thread-1"), - createdAt: new Date().toISOString(), - turnId: asTurnId("turn-1"), - itemId: asProviderItemId("item-1"), - payload: { - streamKind: "assistant_text", - delta: "hello from runtime", - }, - } as unknown as ProviderRuntimeEvent); - - const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => { - const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } }; - return ( - event.type === "thread.message-sent" && event.payload?.messageId === "assistant:item-1" - ); - }); - - const domainEvent = domainPush.data as { - type: string; - payload: { messageId: string; text: string }; - }; - expect(domainEvent.type).toBe("thread.message-sent"); - expect(domainEvent.payload.messageId).toBe("assistant:item-1"); - expect(domainEvent.payload.text).toBe("hello from runtime"); - }); - - it("routes terminal RPC methods and broadcasts terminal events", async () => { - const cwd = makeTempDir("t3code-ws-terminal-cwd-"); - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const open = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "thread-1", - cwd, - cols: 100, - rows: 24, - }); - expect(open.error).toBeUndefined(); - expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1"); - expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID); - - const write = await sendRequest(ws, WS_METHODS.terminalWrite, { - threadId: "thread-1", - data: "echo hello\n", - }); - expect(write.error).toBeUndefined(); - - const resize = await sendRequest(ws, WS_METHODS.terminalResize, { - threadId: "thread-1", - cols: 120, - rows: 30, - }); - expect(resize.error).toBeUndefined(); - - const clear = await sendRequest(ws, WS_METHODS.terminalClear, { - threadId: "thread-1", - }); - expect(clear.error).toBeUndefined(); - - const restart = await sendRequest(ws, WS_METHODS.terminalRestart, { - threadId: "thread-1", - cwd, - cols: 120, - rows: 30, - }); - expect(restart.error).toBeUndefined(); - - const close = await sendRequest(ws, WS_METHODS.terminalClose, { - threadId: "thread-1", - deleteHistory: true, - }); - expect(close.error).toBeUndefined(); - - const manualEvent: TerminalEvent = { - type: "output", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - createdAt: new Date().toISOString(), - data: "manual test output\n", - }; - terminalManager.emitEvent(manualEvent); - - const push = await waitForPush( - ws, - WS_CHANNELS.terminalEvent, - (candidate) => (candidate.data as TerminalEvent).type === "output", - ); - expect(push.type).toBe("push"); - expect(push.channel).toBe(WS_CHANNELS.terminalEvent); - }); - - it("detaches terminal event listener on stop for injected manager", async () => { - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - - expect(terminalManager.subscriptionCount()).toBe(1); - - await closeTestServer(); - server = null; - - expect(terminalManager.subscriptionCount()).toBe(0); - }); - - it("returns validation errors for invalid terminal open params", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "", - cwd: "", - cols: 1, - rows: 1, - }); - expect(response.error).toBeDefined(); - }); - - it("handles invalid JSON gracefully", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - // Send garbage - ws.send("not json at all"); - - // Error response goes to the response channel - const channels = channelsBySocket.get(ws)!; - let response: WebSocketResponse | null = null; - for (let attempt = 0; attempt < 5; attempt += 1) { - const message = await dequeue(channels.response, 5_000); - if (message.id === "unknown") { - response = message; - break; - } - if (message.error) { - response = message; - break; - } - } - expect(response).toBeDefined(); - expect(response!.error).toBeDefined(); - expect(response!.error!.message).toContain("Invalid request format"); - }); - - it("catches websocket message handler rejections and keeps the socket usable", async () => { - const unhandledRejections: unknown[] = []; - const onUnhandledRejection = (reason: unknown) => { - unhandledRejections.push(reason); - }; - process.on("unhandledRejection", onUnhandledRejection); - - const brokenOpenService: OpenShape = { - openBrowser: () => Effect.void, - openInEditor: () => - Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)), - }; - - try { - server = await createTestServer({ cwd: "/test", open: brokenOpenService }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - ws.send( - JSON.stringify({ - id: "req-broken-open", - body: { - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/tmp", - editor: "cursor", - }, - }), - ); - - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(unhandledRejections).toHaveLength(0); - - const workspace = makeTempDir("t3code-ws-handler-still-usable-"); - fs.writeFileSync(path.join(workspace, "file.txt"), "ok\n", "utf8"); - const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { - cwd: workspace, - query: "file", - limit: 5, - }); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual( - expect.objectContaining({ - entries: expect.arrayContaining([ - expect.objectContaining({ - path: "file.txt", - kind: "file", + ({ wsUrl }) => + withRpcClient(wsUrl, (client) => + Effect.gen(function* () { + const bootstrap = yield* client.getBootstrap(undefined); + expect(bootstrap.cwd).toBe("/workspace/example-project"); + expect(bootstrap.projectName).toBe("example-project"); + expect(bootstrap.bootstrapProjectId).toBeDefined(); + expect(bootstrap.bootstrapThreadId).toBeDefined(); + + const snapshot = yield* client.getSnapshot(undefined); + expect(snapshot.projects).toHaveLength(1); + expect(snapshot.threads).toHaveLength(1); + expect(snapshot.projects[0]?.workspaceRoot).toBe("/workspace/example-project"); + expect(snapshot.threads[0]?.projectId).toBe(bootstrap.bootstrapProjectId); + expect(snapshot.threads[0]?.interactionMode).toBe("chat"); + expect(snapshot.threads[0]?.runtimeMode).toBe("full-access"); }), - ]), - }), - ); - } finally { - process.off("unhandledRejection", onUnhandledRejection); - } - }); - - it("returns errors for removed projects CRUD methods", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const listResponse = await sendRequest(ws, WS_METHODS.projectsList); - expect(listResponse.result).toBeUndefined(); - expect(listResponse.error?.message).toContain("Invalid request format"); - - const addResponse = await sendRequest(ws, WS_METHODS.projectsAdd, { - cwd: "/tmp/project-a", - }); - expect(addResponse.result).toBeUndefined(); - expect(addResponse.error?.message).toContain("Invalid request format"); - - const removeResponse = await sendRequest(ws, WS_METHODS.projectsRemove, { - id: "project-a", - }); - expect(removeResponse.result).toBeUndefined(); - expect(removeResponse.error?.message).toContain("Invalid request format"); - }); - - it("supports projects.searchEntries", async () => { - const workspace = makeTempDir("t3code-ws-workspace-entries-"); - fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true }); - fs.writeFileSync( - path.join(workspace, "src", "components", "Composer.tsx"), - "export {};", - "utf8", - ); - fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8"); - fs.mkdirSync(path.join(workspace, ".git"), { recursive: true }); - fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8"); - - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { - cwd: workspace, - query: "comp", - limit: 10, - }); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - entries: expect.arrayContaining([ - expect.objectContaining({ path: "src/components", kind: "directory" }), - expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }), - ]), - truncated: false, - }); - }); - - it("supports projects.writeFile within the workspace root", async () => { - const workspace = makeTempDir("t3code-ws-write-file-"); - - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, { - cwd: workspace, - relativePath: "plans/effect-rpc.md", - contents: "# Plan\n\n- step 1\n", - }); - - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - relativePath: "plans/effect-rpc.md", - }); - expect(fs.readFileSync(path.join(workspace, "plans", "effect-rpc.md"), "utf8")).toBe( - "# Plan\n\n- step 1\n", - ); - }); - - it("rejects projects.writeFile paths outside the workspace root", async () => { - const workspace = makeTempDir("t3code-ws-write-file-reject-"); - - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, { - cwd: workspace, - relativePath: "../escape.md", - contents: "# no\n", - }); - - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain( - "Workspace file path must stay within the project root.", - ); - expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false); - }); - - it("routes git core methods over websocket", async () => { - const listBranches = vi.fn(() => - Effect.succeed({ - branches: [], - isRepo: false, - hasOriginRemote: false, - }), - ); - const initRepo = vi.fn(() => Effect.void); - const pullCurrentBranch = vi.fn(() => - Effect.fail( - new GitCommandError({ - operation: "GitCore.test.pullCurrentBranch", - detail: "No upstream configured", - command: "git pull", - cwd: "/repo/path", - }), + ), ), ); - - server = await createTestServer({ - cwd: "/test", - gitCore: { - listBranches, - initRepo, - pullCurrentBranch, - }, - }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const listResponse = await sendRequest(ws, WS_METHODS.gitListBranches, { cwd: "/repo/path" }); - expect(listResponse.error).toBeUndefined(); - expect(listResponse.result).toEqual({ branches: [], isRepo: false, hasOriginRemote: false }); - expect(listBranches).toHaveBeenCalledWith({ cwd: "/repo/path" }); - - const initResponse = await sendRequest(ws, WS_METHODS.gitInit, { cwd: "/repo/path" }); - expect(initResponse.error).toBeUndefined(); - expect(initRepo).toHaveBeenCalledWith({ cwd: "/repo/path" }); - - const pullResponse = await sendRequest(ws, WS_METHODS.gitPull, { cwd: "/repo/path" }); - expect(pullResponse.result).toBeUndefined(); - expect(pullResponse.error?.message).toContain("No upstream configured"); - expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path"); }); - it("supports git.status over websocket", async () => { - const statusResult = { - branch: "feature/test", - hasWorkingTreeChanges: true, - workingTree: { - files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }], - insertions: 7, - deletions: 2, - }, - hasUpstream: false, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - - const status = vi.fn(() => Effect.succeed(statusResult)); - const runStackedAction = vi.fn(() => Effect.void as any); - const resolvePullRequest = vi.fn(() => Effect.void as any); - const preparePullRequestThread = vi.fn(() => Effect.void as any); - const gitManager: GitManagerShape = { - status, - resolvePullRequest, - preparePullRequestThread, - runStackedAction, - }; - - server = await createTestServer({ cwd: "/test", gitManager }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.gitStatus, { - cwd: "/test", - }); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual(statusResult); - expect(status).toHaveBeenCalledWith({ cwd: "/test" }); - }); - - it("supports git pull request routing over websocket", async () => { - const resolvePullRequestResult = { - pullRequest: { - number: 42, - title: "PR thread flow", - url: "https://github.com/pingdotgg/codething-mvp/pull/42", - baseBranch: "main", - headBranch: "feature/pr-threads", - state: "open" as const, - }, - }; - const preparePullRequestThreadResult = { - ...resolvePullRequestResult, - branch: "feature/pr-threads", - worktreePath: "/tmp/pr-threads", - }; - - const gitManager: GitManagerShape = { - status: vi.fn(() => Effect.void as any), - resolvePullRequest: vi.fn(() => Effect.succeed(resolvePullRequestResult)), - preparePullRequestThread: vi.fn(() => Effect.succeed(preparePullRequestThreadResult)), - runStackedAction: vi.fn(() => Effect.void as any), - }; - - server = await createTestServer({ cwd: "/test", gitManager }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const resolveResponse = await sendRequest(ws, WS_METHODS.gitResolvePullRequest, { - cwd: "/test", - reference: "#42", - }); - expect(resolveResponse.error).toBeUndefined(); - expect(resolveResponse.result).toEqual(resolvePullRequestResult); - - const prepareResponse = await sendRequest(ws, WS_METHODS.gitPreparePullRequestThread, { - cwd: "/test", - reference: "42", - mode: "worktree", - }); - expect(prepareResponse.error).toBeUndefined(); - expect(prepareResponse.result).toEqual(preparePullRequestThreadResult); - expect(gitManager.resolvePullRequest).toHaveBeenCalledWith({ - cwd: "/test", - reference: "#42", - }); - expect(gitManager.preparePullRequestThread).toHaveBeenCalledWith({ - cwd: "/test", - reference: "42", - mode: "worktree", - }); - }); - - it("returns errors from git.runStackedAction", async () => { - const runStackedAction = vi.fn(() => - Effect.fail( - new GitManagerError({ - operation: "GitManager.test.runStackedAction", - detail: "Cannot push from detached HEAD.", - }), + it("opens a terminal over rpc", async () => { + await Effect.runPromise( + withTestServer( + { + terminalManager: new MockTerminalManager(), + }, + ({ wsUrl }) => + withRpcClient(wsUrl, (client) => + Effect.gen(function* () { + const snapshot = yield* client.terminalOpen({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cwd: "/tmp/test-terminal", + }); + expect(snapshot.terminalId).toBe(DEFAULT_TERMINAL_ID); + expect(snapshot.threadId).toBe("thread-1"); + expect(snapshot.cwd).toBe("/tmp/test-terminal"); + expect(snapshot.status).toBe("running"); + }), + ), ), ); - const gitManager: GitManagerShape = { - status: vi.fn(() => Effect.void as any), - resolvePullRequest: vi.fn(() => Effect.void as any), - preparePullRequestThread: vi.fn(() => Effect.void as any), - runStackedAction, - }; - - server = await createTestServer({ cwd: "/test", gitManager }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, { - cwd: "/test", - action: "commit_push", - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("detached HEAD"); - expect(runStackedAction).toHaveBeenCalledWith({ - cwd: "/test", - action: "commit_push", - }); }); - it("rejects websocket connections without a valid auth token", async () => { - server = await createTestServer({ cwd: "/test", authToken: "secret-token" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; + it("updates keybindings and emits config updates over rpc", async () => { + await Effect.runPromise( + withTestServer({}, ({ wsUrl }) => + withRpcClient(wsUrl, (client) => + Effect.gen(function* () { + const initial = yield* getServerConfigEffect(client); + expect(initial.keybindings.length).toBeGreaterThan(0); - await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed"); + const updatesFiber = yield* client.subscribeServerConfig(undefined).pipe( + Stream.take(1), + Stream.runCollect, + Effect.forkChild, + ); - const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token"); - connections.push(authorizedWs); + const updated = yield* upsertKeybindingEffect(client); + expect(updated.issues).toEqual([]); + + const updates = yield* Fiber.join(updatesFiber); + expect(updates[0]?.issues).toEqual([]); + expect(updates[0]?.providers).toEqual(defaultProviderStatuses); + + const refreshed = yield* getServerConfigEffect(client); + expect( + refreshed.keybindings.some( + (binding) => binding.command === "chat.new" && binding.shortcut.key === "y", + ), + ).toBe(true); + }), + ), + ), + ); }); }); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 2e6ac51b7f..86b74aa50b 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -1,507 +1,153 @@ -/** - * Server - HTTP/WebSocket server service interface. - * - * Owns startup and shutdown lifecycle of the HTTP server, static asset serving, - * and WebSocket request routing. - * - * @module Server - */ -import http from "node:http"; -import type { Duplex } from "node:stream"; +import fs from "node:fs"; import Mime from "@effect/platform-node/Mime"; -import { - CommandId, - DEFAULT_PROVIDER_INTERACTION_MODE, - type ClientOrchestrationCommand, - type OrchestrationCommand, - ORCHESTRATION_WS_CHANNELS, - ORCHESTRATION_WS_METHODS, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - ProjectId, - ThreadId, - WS_CHANNELS, - WS_METHODS, - WebSocketRequest, - type WsResponse as WsResponseMessage, - WsResponse, - type WsPushEnvelopeBase, -} from "@t3tools/contracts"; -import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import { - Cause, - Effect, - Exit, - FileSystem, - Layer, - Path, - Ref, - Result, - Schema, - Scope, - ServiceMap, - Stream, - Struct, -} from "effect"; -import { WebSocketServer, type WebSocket } from "ws"; +import { Effect, FileSystem, Layer, Path } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; -import { createLogger } from "./logger"; -import { GitManager } from "./git/Services/GitManager.ts"; -import { TerminalManager } from "./terminal/Services/Manager.ts"; -import { Keybindings } from "./keybindings"; -import { searchWorkspaceEntries } from "./workspaceEntries"; -import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; -import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; -import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; -import { ProviderService } from "./provider/Services/ProviderService"; -import { ProviderHealth } from "./provider/Services/ProviderHealth"; -import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; -import { clamp } from "effect/Number"; -import { Open, resolveAvailableEditors } from "./open"; -import { ServerConfig } from "./config"; -import { GitCore } from "./git/Services/GitCore.ts"; -import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; import { ATTACHMENTS_ROUTE_PREFIX, normalizeAttachmentRelativePath, resolveAttachmentRelativePath, } from "./attachmentPaths"; +import { resolveAttachmentPathById } from "./attachmentStore.ts"; +import { ServerConfig } from "./config"; +import { resolveProjectFaviconRoute, type ProjectFaviconRouteResult } from "./projectFaviconRoute"; +import { makeServerRpcRouteLayer, type ServerRpcRouteRequirements } from "./serverRpc"; -import { - createAttachmentId, - resolveAttachmentPath, - resolveAttachmentPathById, -} from "./attachmentStore.ts"; -import { parseBase64DataUrl } from "./imageMime.ts"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; -import { expandHomePath } from "./os-jank.ts"; -import { makeServerPushBus } from "./wsServer/pushBus.ts"; -import { makeServerReadiness } from "./wsServer/readiness.ts"; -import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson"; +const textResponse = (status: number, body: string) => + HttpServerResponse.text(body, { status, contentType: "text/plain" }); -/** - * ServerShape - Service API for server lifecycle control. - */ -export interface ServerShape { - /** - * Start HTTP and WebSocket listeners. - */ - readonly start: Effect.Effect< - http.Server, - ServerLifecycleError, - Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path - >; +const toHttpResponseFromProjectFavicon = ( + result: ProjectFaviconRouteResult, +): HttpServerResponse.HttpServerResponse => { + if (result.kind === "file") { + return HttpServerResponse.raw(fs.createReadStream(result.filePath), { + status: 200, + headers: { + "Content-Type": result.contentType, + "Cache-Control": result.cacheControl, + }, + }); + } - /** - * Wait for process shutdown signals. - */ - readonly stopSignal: Effect.Effect; -} - -/** - * Server - Service tag for HTTP/WebSocket lifecycle management. - */ -export class Server extends ServiceMap.Service()("t3/wsServer/Server") {} - -const isServerNotRunningError = (error: Error): boolean => { - const maybeCode = (error as NodeJS.ErrnoException).code; - return ( - maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running") - ); + return HttpServerResponse.text(result.body, { + status: result.statusCode, + contentType: result.contentType, + headers: result.cacheControl ? { "Cache-Control": result.cacheControl } : undefined, + }); }; -function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void { - socket.end( - `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` + - "Connection: close\r\n" + - "Content-Type: text/plain\r\n" + - `Content-Length: ${Buffer.byteLength(message)}\r\n` + - "\r\n" + - message, - ); -} +export type ServerRouteRequirements = ServerRpcRouteRequirements; -function websocketRawToString(raw: unknown): string | null { - if (typeof raw === "string") { - return raw; - } - if (raw instanceof Uint8Array) { - return Buffer.from(raw).toString("utf8"); - } - if (raw instanceof ArrayBuffer) { - return Buffer.from(new Uint8Array(raw)).toString("utf8"); - } - if (Array.isArray(raw)) { - const chunks: string[] = []; - for (const chunk of raw) { - if (typeof chunk === "string") { - chunks.push(chunk); - continue; - } - if (chunk instanceof Uint8Array) { - chunks.push(Buffer.from(chunk).toString("utf8")); - continue; - } - if (chunk instanceof ArrayBuffer) { - chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8")); - continue; - } - return null; - } - return chunks.join(""); - } - return null; -} +export const makeRoutesLayer = Layer.unwrap( + Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const { staticDir, devUrl } = serverConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; -function toPosixRelativePath(input: string): string { - return input.replaceAll("\\", "/"); -} - -function resolveWorkspaceWritePath(params: { - workspaceRoot: string; - relativePath: string; - path: Path.Path; -}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> { - const normalizedInputPath = params.relativePath.trim(); - if (params.path.isAbsolute(normalizedInputPath)) { - return Effect.fail( - new RouteRequestError({ - message: "Workspace file path must be relative to the project root.", - }), - ); - } - - const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath); - const relativeToRoot = toPosixRelativePath( - params.path.relative(params.workspaceRoot, absolutePath), - ); - if ( - relativeToRoot.length === 0 || - relativeToRoot === "." || - relativeToRoot.startsWith("../") || - relativeToRoot === ".." || - params.path.isAbsolute(relativeToRoot) - ) { - return Effect.fail( - new RouteRequestError({ - message: "Workspace file path must stay within the project root.", - }), - ); - } - - return Effect.succeed({ - absolutePath, - relativePath: relativeToRoot, - }); -} - -function stripRequestTag(body: T) { - return Struct.omit(body, ["_tag"]); -} - -const encodeWsResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse)); -const decodeWebSocketRequest = decodeJsonResult(WebSocketRequest); - -export type ServerCoreRuntimeServices = - | OrchestrationEngineService - | ProjectionSnapshotQuery - | CheckpointDiffQuery - | OrchestrationReactor - | ProviderService - | ProviderHealth; - -export type ServerRuntimeServices = - | ServerCoreRuntimeServices - | GitManager - | GitCore - | TerminalManager - | Keybindings - | Open - | AnalyticsService; - -export class ServerLifecycleError extends Schema.TaggedErrorClass()( - "ServerLifecycleError", - { - operation: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) {} - -class RouteRequestError extends Schema.TaggedErrorClass()("RouteRequestError", { - message: Schema.String, -}) {} - -export const createServer = Effect.fn(function* (): Effect.fn.Return< - http.Server, - ServerLifecycleError, - Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path -> { - const serverConfig = yield* ServerConfig; - const { - port, - cwd, - keybindingsConfigPath, - staticDir, - devUrl, - authToken, - host, - logWebSocketEvents, - autoBootstrapProjectFromCwd, - } = serverConfig; - const availableEditors = resolveAvailableEditors(); - - const gitManager = yield* GitManager; - const terminalManager = yield* TerminalManager; - const keybindingsManager = yield* Keybindings; - const providerHealth = yield* ProviderHealth; - const git = yield* GitCore; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - - yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe( - Effect.catch((error) => - Effect.logWarning("failed to sync keybindings defaults on startup", { - path: error.configPath, - detail: error.detail, - cause: error.cause, - }), - ), - ); - - const providerStatuses = yield* providerHealth.getStatuses; - - const clients = yield* Ref.make(new Set()); - const logger = createLogger("ws"); - const readiness = yield* makeServerReadiness; - - function logOutgoingPush(push: WsPushEnvelopeBase, recipients: number) { - if (!logWebSocketEvents) return; - logger.event("outgoing push", { - channel: push.channel, - sequence: push.sequence, - recipients, - payload: push.data, - }); - } - - const pushBus = yield* makeServerPushBus({ - clients, - logOutgoingPush, - }); - yield* readiness.markPushBusReady; - yield* keybindingsManager.start.pipe( - Effect.mapError( - (cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }), - ), - ); - yield* readiness.markKeybindingsReady; - - const normalizeDispatchCommand = Effect.fnUntraced(function* (input: { - readonly command: ClientOrchestrationCommand; - }) { - const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) { - const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim())); - const workspaceStat = yield* fileSystem - .stat(normalizedWorkspaceRoot) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!workspaceStat) { - return yield* new RouteRequestError({ - message: `Project directory does not exist: ${normalizedWorkspaceRoot}`, - }); - } - if (workspaceStat.type !== "Directory") { - return yield* new RouteRequestError({ - message: `Project path is not a directory: ${normalizedWorkspaceRoot}`, - }); - } - return normalizedWorkspaceRoot; - }); - - if (input.command.type === "project.create") { - return { - ...input.command, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot), - } satisfies OrchestrationCommand; + if (!devUrl && !staticDir) { + yield* Effect.logWarning( + "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", + { + hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.", + }, + ); } - if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) { - return { - ...input.command, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot), - } satisfies OrchestrationCommand; - } + const healthRoute = HttpRouter.add("GET", "/health", HttpServerResponse.json({ ok: true })); - if (input.command.type !== "thread.turn.start") { - return input.command as OrchestrationCommand; - } - const turnStartCommand = input.command; - - const normalizedAttachments = yield* Effect.forEach( - turnStartCommand.message.attachments, - (attachment) => - Effect.gen(function* () { - const parsed = parseBase64DataUrl(attachment.dataUrl); - if (!parsed || !parsed.mimeType.startsWith("image/")) { - return yield* new RouteRequestError({ - message: `Invalid image attachment payload for '${attachment.name}'.`, - }); - } - - const bytes = Buffer.from(parsed.base64, "base64"); - if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - return yield* new RouteRequestError({ - message: `Image attachment '${attachment.name}' is empty or too large.`, - }); - } - - const attachmentId = createAttachmentId(turnStartCommand.threadId); - if (!attachmentId) { - return yield* new RouteRequestError({ - message: "Failed to create a safe attachment id.", - }); - } - - const persistedAttachment = { - type: "image" as const, - id: attachmentId, - name: attachment.name, - mimeType: parsed.mimeType.toLowerCase(), - sizeBytes: bytes.byteLength, - }; - - const attachmentPath = resolveAttachmentPath({ - stateDir: serverConfig.stateDir, - attachment: persistedAttachment, - }); - if (!attachmentPath) { - return yield* new RouteRequestError({ - message: `Failed to resolve persisted path for '${attachment.name}'.`, - }); - } - - yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe( - Effect.mapError( - () => - new RouteRequestError({ - message: `Failed to create attachment directory for '${attachment.name}'.`, - }), - ), - ); - yield* fileSystem.writeFile(attachmentPath, bytes).pipe( - Effect.mapError( - () => - new RouteRequestError({ - message: `Failed to persist attachment '${attachment.name}'.`, - }), - ), - ); - - return persistedAttachment; - }), - { concurrency: 1 }, - ); - - return { - ...turnStartCommand, - message: { - ...turnStartCommand.message, - attachments: normalizedAttachments, - }, - } satisfies OrchestrationCommand; - }); - - // HTTP server — serves static files or redirects to Vite dev server - const httpServer = http.createServer((req, res) => { - const respond = ( - statusCode: number, - headers: Record, - body?: string | Uint8Array, - ) => { - res.writeHead(statusCode, headers); - res.end(body); - }; - - void Effect.runPromise( + const attachmentsRoute = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, Effect.gen(function* () { - const url = new URL(req.url ?? "/", `http://localhost:${port}`); - if (tryHandleProjectFaviconRequest(url, res)) { - return; + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (!url) { + return textResponse(400, "Bad Request"); } - if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) { - const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length); - const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath); - if (!normalizedRelativePath) { - respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path"); - return; - } + const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length); + const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath); + if (!normalizedRelativePath) { + return textResponse(400, "Invalid attachment path"); + } - const isIdLookup = - !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes("."); - const filePath = isIdLookup - ? resolveAttachmentPathById({ - stateDir: serverConfig.stateDir, - attachmentId: normalizedRelativePath, - }) - : resolveAttachmentRelativePath({ - stateDir: serverConfig.stateDir, - relativePath: normalizedRelativePath, - }); - if (!filePath) { - respond( - isIdLookup ? 404 : 400, - { "Content-Type": "text/plain" }, - isIdLookup ? "Not Found" : "Invalid attachment path", - ); - return; - } + const isIdLookup = + !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes("."); + const filePath = isIdLookup + ? resolveAttachmentPathById({ + stateDir: serverConfig.stateDir, + attachmentId: normalizedRelativePath, + }) + : resolveAttachmentRelativePath({ + stateDir: serverConfig.stateDir, + relativePath: normalizedRelativePath, + }); - const fileInfo = yield* fileSystem - .stat(filePath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - respond(404, { "Content-Type": "text/plain" }, "Not Found"); - return; - } + if (!filePath) { + return textResponse( + isIdLookup ? 404 : 400, + isIdLookup ? "Not Found" : "Invalid attachment path", + ); + } - const contentType = Mime.getType(filePath) ?? "application/octet-stream"; - res.writeHead(200, { + const fileInfo = yield* fileSystem + .stat(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return textResponse(404, "Not Found"); + } + + const contentType = Mime.getType(filePath) ?? "application/octet-stream"; + return HttpServerResponse.stream(fileSystem.stream(filePath), { + headers: { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable", - }); - const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) => - Effect.sync(() => { - if (!res.destroyed) { - res.write(chunk); - } - }), - ).pipe(Effect.exit); - if (Exit.isFailure(streamExit)) { - if (!res.destroyed) { - res.destroy(); - } - return; - } - if (!res.writableEnded) { - res.end(); - } - return; + }, + }); + }), + ); + + const projectFaviconRoute = HttpRouter.add( + "GET", + "/api/project-favicon", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (!url) { + return textResponse(400, "Bad Request"); + } + + const result = yield* resolveProjectFaviconRoute(url); + + if (!result) { + return textResponse(404, "Not Found"); + } + + return toHttpResponseFromProjectFavicon(result); + }), + ); + + const staticRoute = HttpRouter.add( + "GET", + "*", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (!url) { + return textResponse(400, "Bad Request"); } - // In dev mode, redirect to Vite dev server if (devUrl) { - respond(302, { Location: devUrl.href }); - return; + return HttpServerResponse.redirect(new URL(`${url.pathname}${url.search}`, devUrl), { + status: 307, + headers: { "cache-control": "no-store" }, + }); } - // Serve static files from the web app build if (!staticDir) { - respond( - 503, - { "Content-Type": "text/plain" }, - "No static directory configured and no dev URL set.", - ); - return; + return textResponse(503, "No static directory configured and no dev URL set."); } const staticRoot = path.resolve(staticDir); @@ -510,14 +156,14 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(".."); const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, ""); const hasPathTraversalSegment = staticRelativePath.startsWith(".."); + if ( staticRelativePath.length === 0 || hasRawLeadingParentSegment || hasPathTraversalSegment || staticRelativePath.includes("\0") ) { - respond(400, { "Content-Type": "text/plain" }, "Invalid static file path"); - return; + return textResponse(400, "Invalid static file path"); } const isWithinStaticRoot = (candidate: string) => @@ -528,16 +174,14 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< let filePath = path.resolve(staticRoot, staticRelativePath); if (!isWithinStaticRoot(filePath)) { - respond(400, { "Content-Type": "text/plain" }, "Invalid static file path"); - return; + return textResponse(400, "Invalid static file path"); } const ext = path.extname(filePath); if (!ext) { filePath = path.resolve(filePath, "index.html"); if (!isWithinStaticRoot(filePath)) { - respond(400, { "Content-Type": "text/plain" }, "Invalid static file path"); - return; + return textResponse(400, "Invalid static file path"); } } @@ -550,11 +194,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< .readFile(indexPath) .pipe(Effect.catch(() => Effect.succeed(null))); if (!indexData) { - respond(404, { "Content-Type": "text/plain" }, "Not Found"); - return; + return textResponse(404, "Not Found"); } - respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData); - return; + return HttpServerResponse.uint8Array(indexData, { + contentType: "text/html; charset=utf-8", + }); } const contentType = Mime.getType(filePath) ?? "application/octet-stream"; @@ -562,445 +206,22 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< .readFile(filePath) .pipe(Effect.catch(() => Effect.succeed(null))); if (!data) { - respond(500, { "Content-Type": "text/plain" }, "Internal Server Error"); - return; + return textResponse(500, "Internal Server Error"); } - respond(200, { "Content-Type": contentType }, data); + + return HttpServerResponse.uint8Array(data, { + contentType, + }); }), - ).catch(() => { - if (!res.headersSent) { - respond(500, { "Content-Type": "text/plain" }, "Internal Server Error"); - } - }); - }); - - // WebSocket server — upgrades from the HTTP server - const wss = new WebSocketServer({ noServer: true }); - - const closeWebSocketServer = Effect.callback((resume) => { - wss.close((error) => { - if (error && !isServerNotRunningError(error)) { - resume( - Effect.fail( - new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }), - ), - ); - } else { - resume(Effect.void); - } - }); - }); - - const closeAllClients = Ref.get(clients).pipe( - Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))), - Effect.flatMap(() => Ref.set(clients, new Set())), - ); - - const listenOptions = host ? { host, port } : { port }; - - const orchestrationEngine = yield* OrchestrationEngineService; - const projectionReadModelQuery = yield* ProjectionSnapshotQuery; - const checkpointDiffQuery = yield* CheckpointDiffQuery; - const orchestrationReactor = yield* OrchestrationReactor; - const { openInEditor } = yield* Open; - - const subscriptionsScope = yield* Scope.make("sequential"); - yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void)); - - yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => - pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(keybindingsManager.streamChanges, (event) => - pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: event.issues, - providers: providerStatuses, - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Scope.provide(orchestrationReactor.start, subscriptionsScope); - yield* readiness.markOrchestrationSubscriptionsReady; - - let welcomeBootstrapProjectId: ProjectId | undefined; - let welcomeBootstrapThreadId: ThreadId | undefined; - - if (autoBootstrapProjectFromCwd) { - yield* Effect.gen(function* () { - const snapshot = yield* projectionReadModelQuery.getSnapshot(); - const existingProject = snapshot.projects.find( - (project) => project.workspaceRoot === cwd && project.deletedAt === null, - ); - let bootstrapProjectId: ProjectId; - let bootstrapProjectDefaultModel: string; - - if (!existingProject) { - const createdAt = new Date().toISOString(); - bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); - const bootstrapProjectTitle = path.basename(cwd) || "project"; - bootstrapProjectDefaultModel = "gpt-5-codex"; - yield* orchestrationEngine.dispatch({ - type: "project.create", - commandId: CommandId.makeUnsafe(crypto.randomUUID()), - projectId: bootstrapProjectId, - title: bootstrapProjectTitle, - workspaceRoot: cwd, - defaultModel: bootstrapProjectDefaultModel, - createdAt, - }); - } else { - bootstrapProjectId = existingProject.id; - bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex"; - } - - const existingThread = snapshot.threads.find( - (thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null, - ); - if (!existingThread) { - const createdAt = new Date().toISOString(); - const threadId = ThreadId.makeUnsafe(crypto.randomUUID()); - yield* orchestrationEngine.dispatch({ - type: "thread.create", - commandId: CommandId.makeUnsafe(crypto.randomUUID()), - threadId, - projectId: bootstrapProjectId, - title: "New thread", - model: bootstrapProjectDefaultModel, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt, - }); - welcomeBootstrapProjectId = bootstrapProjectId; - welcomeBootstrapThreadId = threadId; - } else { - welcomeBootstrapProjectId = bootstrapProjectId; - welcomeBootstrapThreadId = existingThread.id; - } - }).pipe( - Effect.mapError( - (cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }), - ), - ); - } - - const runtimeServices = yield* Effect.services< - ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path - >(); - const runPromise = Effect.runPromiseWith(runtimeServices); - - const unsubscribeTerminalEvents = yield* terminalManager.subscribe( - (event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)), - ); - yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents())); - yield* readiness.markTerminalSubscriptionsReady; - - yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe( - Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })), - ); - yield* readiness.markHttpListening; - - yield* Effect.addFinalizer(() => - Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]), - ); - - const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) { - switch (request.body._tag) { - case ORCHESTRATION_WS_METHODS.getSnapshot: - return yield* projectionReadModelQuery.getSnapshot(); - - case ORCHESTRATION_WS_METHODS.dispatchCommand: { - const { command } = request.body; - const normalizedCommand = yield* normalizeDispatchCommand({ command }); - return yield* orchestrationEngine.dispatch(normalizedCommand); - } - - case ORCHESTRATION_WS_METHODS.getTurnDiff: { - const body = stripRequestTag(request.body); - return yield* checkpointDiffQuery.getTurnDiff(body); - } - - case ORCHESTRATION_WS_METHODS.getFullThreadDiff: { - const body = stripRequestTag(request.body); - return yield* checkpointDiffQuery.getFullThreadDiff(body); - } - - case ORCHESTRATION_WS_METHODS.replayEvents: { - const { fromSequenceExclusive } = request.body; - return yield* Stream.runCollect( - orchestrationEngine.readEvents( - clamp(fromSequenceExclusive, { - maximum: Number.MAX_SAFE_INTEGER, - minimum: 0, - }), - ), - ).pipe(Effect.map((events) => Array.from(events))); - } - - case WS_METHODS.projectsSearchEntries: { - const body = stripRequestTag(request.body); - return yield* Effect.tryPromise({ - try: () => searchWorkspaceEntries(body), - catch: (cause) => - new RouteRequestError({ - message: `Failed to search workspace entries: ${String(cause)}`, - }), - }); - } - - case WS_METHODS.projectsWriteFile: { - const body = stripRequestTag(request.body); - const target = yield* resolveWorkspaceWritePath({ - workspaceRoot: body.cwd, - relativePath: body.relativePath, - path, - }); - yield* fileSystem - .makeDirectory(path.dirname(target.absolutePath), { recursive: true }) - .pipe( - Effect.mapError( - (cause) => - new RouteRequestError({ - message: `Failed to prepare workspace path: ${String(cause)}`, - }), - ), - ); - yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe( - Effect.mapError( - (cause) => - new RouteRequestError({ - message: `Failed to write workspace file: ${String(cause)}`, - }), - ), - ); - return { relativePath: target.relativePath }; - } - - case WS_METHODS.shellOpenInEditor: { - const body = stripRequestTag(request.body); - return yield* openInEditor(body); - } - - case WS_METHODS.gitStatus: { - const body = stripRequestTag(request.body); - return yield* gitManager.status(body); - } - - case WS_METHODS.gitPull: { - const body = stripRequestTag(request.body); - return yield* git.pullCurrentBranch(body.cwd); - } - - case WS_METHODS.gitRunStackedAction: { - const body = stripRequestTag(request.body); - return yield* gitManager.runStackedAction(body); - } - - case WS_METHODS.gitResolvePullRequest: { - const body = stripRequestTag(request.body); - return yield* gitManager.resolvePullRequest(body); - } - - case WS_METHODS.gitPreparePullRequestThread: { - const body = stripRequestTag(request.body); - return yield* gitManager.preparePullRequestThread(body); - } - - case WS_METHODS.gitListBranches: { - const body = stripRequestTag(request.body); - return yield* git.listBranches(body); - } - - case WS_METHODS.gitCreateWorktree: { - const body = stripRequestTag(request.body); - return yield* git.createWorktree(body); - } - - case WS_METHODS.gitRemoveWorktree: { - const body = stripRequestTag(request.body); - return yield* git.removeWorktree(body); - } - - case WS_METHODS.gitCreateBranch: { - const body = stripRequestTag(request.body); - return yield* git.createBranch(body); - } - - case WS_METHODS.gitCheckout: { - const body = stripRequestTag(request.body); - return yield* Effect.scoped(git.checkoutBranch(body)); - } - - case WS_METHODS.gitInit: { - const body = stripRequestTag(request.body); - return yield* git.initRepo(body); - } - - case WS_METHODS.terminalOpen: { - const body = stripRequestTag(request.body); - return yield* terminalManager.open(body); - } - - case WS_METHODS.terminalWrite: { - const body = stripRequestTag(request.body); - return yield* terminalManager.write(body); - } - - case WS_METHODS.terminalResize: { - const body = stripRequestTag(request.body); - return yield* terminalManager.resize(body); - } - - case WS_METHODS.terminalClear: { - const body = stripRequestTag(request.body); - return yield* terminalManager.clear(body); - } - - case WS_METHODS.terminalRestart: { - const body = stripRequestTag(request.body); - return yield* terminalManager.restart(body); - } - - case WS_METHODS.terminalClose: { - const body = stripRequestTag(request.body); - return yield* terminalManager.close(body); - } - - case WS_METHODS.serverGetConfig: - const keybindingsConfig = yield* keybindingsManager.loadConfigState; - return { - cwd, - keybindingsConfigPath, - keybindings: keybindingsConfig.keybindings, - issues: keybindingsConfig.issues, - providers: providerStatuses, - availableEditors, - }; - - case WS_METHODS.serverUpsertKeybinding: { - const body = stripRequestTag(request.body); - const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body); - return { keybindings: keybindingsConfig, issues: [] }; - } - - default: { - const _exhaustiveCheck: never = request.body; - return yield* new RouteRequestError({ - message: `Unknown method: ${String(_exhaustiveCheck)}`, - }); - } - } - }); - - const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) { - const sendWsResponse = (response: WsResponseMessage) => - encodeWsResponse(response).pipe( - Effect.tap((encodedResponse) => Effect.sync(() => ws.send(encodedResponse))), - Effect.asVoid, - ); - - const messageText = websocketRawToString(raw); - if (messageText === null) { - return yield* sendWsResponse({ - id: "unknown", - error: { message: "Invalid request format: Failed to read message" }, - }); - } - - const request = decodeWebSocketRequest(messageText); - if (Result.isFailure(request)) { - return yield* sendWsResponse({ - id: "unknown", - error: { message: `Invalid request format: ${formatSchemaError(request.failure)}` }, - }); - } - - const result = yield* Effect.exit(routeRequest(request.success)); - if (Exit.isFailure(result)) { - return yield* sendWsResponse({ - id: request.success.id, - error: { message: Cause.pretty(result.cause) }, - }); - } - - return yield* sendWsResponse({ - id: request.success.id, - result: result.value, - }); - }); - - httpServer.on("upgrade", (request, socket, head) => { - socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake - - if (authToken) { - let providedToken: string | null = null; - try { - const url = new URL(request.url ?? "/", `http://localhost:${port}`); - providedToken = url.searchParams.get("token"); - } catch { - rejectUpgrade(socket, 400, "Invalid WebSocket URL"); - return; - } - - if (providedToken !== authToken) { - rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); - return; - } - } - - wss.handleUpgrade(request, socket, head, (ws) => { - wss.emit("connection", ws, request); - }); - }); - - wss.on("connection", (ws) => { - const segments = cwd.split(/[/\\]/).filter(Boolean); - const projectName = segments[segments.length - 1] ?? "project"; - - const welcomeData = { - cwd, - projectName, - ...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}), - ...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}), - }; - // Send welcome before adding to broadcast set so publishAll calls - // cannot reach this client before the welcome arrives. - void runPromise( - readiness.awaitServerReady.pipe( - Effect.flatMap(() => pushBus.publishClient(ws, WS_CHANNELS.serverWelcome, welcomeData)), - Effect.flatMap((delivered) => - delivered ? Ref.update(clients, (clients) => clients.add(ws)) : Effect.void, - ), - ), ); - ws.on("message", (raw) => { - void runPromise(handleMessage(ws, raw).pipe(Effect.ignoreCause({ log: true }))); - }); + const baseRoutesLayer = Layer.mergeAll( + healthRoute, + attachmentsRoute, + projectFaviconRoute, + staticRoute, + ); - ws.on("close", () => { - void runPromise( - Ref.update(clients, (clients) => { - clients.delete(ws); - return clients; - }), - ); - }); - - ws.on("error", () => { - void runPromise( - Ref.update(clients, (clients) => { - clients.delete(ws); - return clients; - }), - ); - }); - }); - - return httpServer; -}); - -export const ServerLive = Layer.succeed(Server, { - start: createServer(), - stopSignal: Effect.never, -} satisfies ServerShape); + return makeServerRpcRouteLayer.pipe(Layer.provideMerge(baseRoutesLayer)); + }), +); diff --git a/apps/server/tsdown.config.ts b/apps/server/tsdown.config.ts index f89bc7d3d7..111d41f04c 100644 --- a/apps/server/tsdown.config.ts +++ b/apps/server/tsdown.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from "tsdown"; export default defineConfig({ - entry: ["src/index.ts"], + entry: ["src/bin.ts"], format: ["esm", "cjs"], checks: { legacyCjs: false, @@ -11,7 +11,4 @@ export default defineConfig({ clean: true, noExternal: (id) => id.startsWith("@t3tools/"), inlineOnly: false, - banner: { - js: "#!/usr/bin/env node\n", - }, }); diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/wsTransport.ts index 2882098c47..a402981a8a 100644 --- a/apps/web/src/wsTransport.ts +++ b/apps/web/src/wsTransport.ts @@ -46,6 +46,18 @@ function asError(value: unknown, fallback: string): Error { return new Error(fallback); } +function normalizeWsUrl(rawUrl: string): string { + try { + const url = new URL(rawUrl); + if (url.pathname === "" || url.pathname === "/") { + url.pathname = "/ws"; + } + return url.toString(); + } catch { + return rawUrl; + } +} + export class WsTransport { private ws: WebSocket | null = null; private nextId = 1; @@ -62,13 +74,16 @@ export class WsTransport { constructor(url?: string) { const bridgeUrl = window.desktopBridge?.getWsUrl(); const envUrl = import.meta.env.VITE_WS_URL as string | undefined; - this.url = + const resolvedUrl = url ?? (bridgeUrl && bridgeUrl.length > 0 ? bridgeUrl : envUrl && envUrl.length > 0 ? envUrl : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`); + this.url = normalizeWsUrl(resolvedUrl); + : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`); + this.url = normalizeWsUrl(resolvedUrl); this.connect(); } diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 0f37a93515..e12568919e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -7,6 +7,7 @@ export * from "./model"; export * from "./ws"; export * from "./keybindings"; export * from "./server"; +export * from "./rpc"; export * from "./git"; export * from "./orchestration"; export * from "./editor"; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts new file mode 100644 index 0000000000..bec404fc22 --- /dev/null +++ b/packages/contracts/src/rpc.ts @@ -0,0 +1,265 @@ +import { Schema } from "effect"; +import * as Rpc from "effect/unstable/rpc/Rpc"; +import * as RpcGroup from "effect/unstable/rpc/RpcGroup"; + +import { + DispatchResult, + OrchestrationEvent, + OrchestrationGetFullThreadDiffInput, + OrchestrationGetFullThreadDiffResult, + OrchestrationGetSnapshotResult, + OrchestrationGetTurnDiffInput, + OrchestrationGetTurnDiffResult, + OrchestrationReplayEventsInput, + OrchestrationReplayEventsResult, + ClientOrchestrationCommand, +} from "./orchestration"; +import { + GitCheckoutInput, + GitCreateBranchInput, + GitCreateWorktreeInput, + GitCreateWorktreeResult, + GitInitInput, + GitListBranchesInput, + GitListBranchesResult, + GitPreparePullRequestThreadInput, + GitPreparePullRequestThreadResult, + GitPullInput, + GitPullRequestRefInput, + GitPullResult, + GitRemoveWorktreeInput, + GitResolvePullRequestResult, + GitRunStackedActionInput, + GitRunStackedActionResult, + GitStatusInput, + GitStatusResult, +} from "./git"; +import { + TerminalClearInput, + TerminalCloseInput, + TerminalEvent, + TerminalOpenInput, + TerminalResizeInput, + TerminalRestartInput, + TerminalSessionSnapshot, + TerminalWriteInput, +} from "./terminal"; +import { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "./project"; +import { OpenInEditorInput } from "./editor"; +import { + ServerBootstrapState, + ServerConfig, + ServerConfigUpdatedPayload, + ServerUpsertKeybindingInput, + ServerUpsertKeybindingResult, +} from "./server"; + +export const ServerRpcError = Schema.Struct({ + message: Schema.String, +}); +export type ServerRpcError = typeof ServerRpcError.Type; + +const rpcOptions = { + error: ServerRpcError, +} as const; + +export const GetBootstrapRpc = Rpc.make("getBootstrap", { + success: ServerBootstrapState, + ...rpcOptions, +}); + +export const GetServerConfigRpc = Rpc.make("getServerConfig", { + success: ServerConfig, + ...rpcOptions, +}); + +export const UpsertKeybindingRpc = Rpc.make("upsertKeybinding", { + payload: ServerUpsertKeybindingInput, + success: ServerUpsertKeybindingResult, + ...rpcOptions, +}); + +export const SubscribeServerConfigRpc = Rpc.make("subscribeServerConfig", { + success: ServerConfigUpdatedPayload, + stream: true, + ...rpcOptions, +}); + +export const GetSnapshotRpc = Rpc.make("getSnapshot", { + success: OrchestrationGetSnapshotResult, + ...rpcOptions, +}); + +export const DispatchCommandRpc = Rpc.make("dispatchCommand", { + payload: ClientOrchestrationCommand, + success: DispatchResult, + ...rpcOptions, +}); + +export const GetTurnDiffRpc = Rpc.make("getTurnDiff", { + payload: OrchestrationGetTurnDiffInput, + success: OrchestrationGetTurnDiffResult, + ...rpcOptions, +}); + +export const GetFullThreadDiffRpc = Rpc.make("getFullThreadDiff", { + payload: OrchestrationGetFullThreadDiffInput, + success: OrchestrationGetFullThreadDiffResult, + ...rpcOptions, +}); + +export const ReplayEventsRpc = Rpc.make("replayEvents", { + payload: OrchestrationReplayEventsInput, + success: OrchestrationReplayEventsResult, + ...rpcOptions, +}); + +export const SubscribeDomainEventsRpc = Rpc.make("subscribeDomainEvents", { + success: OrchestrationEvent, + stream: true, + ...rpcOptions, +}); + +export const SearchEntriesRpc = Rpc.make("searchEntries", { + payload: ProjectSearchEntriesInput, + success: ProjectSearchEntriesResult, + ...rpcOptions, +}); + +export const OpenInEditorRpc = Rpc.make("openInEditor", { + payload: OpenInEditorInput, + ...rpcOptions, +}); + +export const GitStatusRpc = Rpc.make("gitStatus", { + payload: GitStatusInput, + success: GitStatusResult, + ...rpcOptions, +}); + +export const GitPullRpc = Rpc.make("gitPull", { + payload: GitPullInput, + success: GitPullResult, + ...rpcOptions, +}); + +export const GitRunStackedActionRpc = Rpc.make("gitRunStackedAction", { + payload: GitRunStackedActionInput, + success: GitRunStackedActionResult, + ...rpcOptions, +}); + +export const GitListBranchesRpc = Rpc.make("gitListBranches", { + payload: GitListBranchesInput, + success: GitListBranchesResult, + ...rpcOptions, +}); + +export const GitCreateWorktreeRpc = Rpc.make("gitCreateWorktree", { + payload: GitCreateWorktreeInput, + success: GitCreateWorktreeResult, + ...rpcOptions, +}); + +export const GitRemoveWorktreeRpc = Rpc.make("gitRemoveWorktree", { + payload: GitRemoveWorktreeInput, + ...rpcOptions, +}); + +export const GitCreateBranchRpc = Rpc.make("gitCreateBranch", { + payload: GitCreateBranchInput, + ...rpcOptions, +}); + +export const GitCheckoutRpc = Rpc.make("gitCheckout", { + payload: GitCheckoutInput, + ...rpcOptions, +}); + +export const GitInitRpc = Rpc.make("gitInit", { + payload: GitInitInput, + ...rpcOptions, +}); + +export const GitResolvePullRequestRpc = Rpc.make("gitResolvePullRequest", { + payload: GitPullRequestRefInput, + success: GitResolvePullRequestResult, + ...rpcOptions, +}); + +export const GitPreparePullRequestThreadRpc = Rpc.make("gitPreparePullRequestThread", { + payload: GitPreparePullRequestThreadInput, + success: GitPreparePullRequestThreadResult, + ...rpcOptions, +}); + +export const TerminalOpenRpc = Rpc.make("terminalOpen", { + payload: TerminalOpenInput, + success: TerminalSessionSnapshot, + ...rpcOptions, +}); + +export const TerminalWriteRpc = Rpc.make("terminalWrite", { + payload: TerminalWriteInput, + ...rpcOptions, +}); + +export const TerminalResizeRpc = Rpc.make("terminalResize", { + payload: TerminalResizeInput, + ...rpcOptions, +}); + +export const TerminalClearRpc = Rpc.make("terminalClear", { + payload: TerminalClearInput, + ...rpcOptions, +}); + +export const TerminalRestartRpc = Rpc.make("terminalRestart", { + payload: TerminalRestartInput, + success: TerminalSessionSnapshot, + ...rpcOptions, +}); + +export const TerminalCloseRpc = Rpc.make("terminalClose", { + payload: TerminalCloseInput, + ...rpcOptions, +}); + +export const SubscribeTerminalEventsRpc = Rpc.make("subscribeTerminalEvents", { + success: TerminalEvent, + stream: true, + ...rpcOptions, +}); + +export const ServerRpcGroup = RpcGroup.make( + GetBootstrapRpc, + GetServerConfigRpc, + UpsertKeybindingRpc, + SubscribeServerConfigRpc, + GetSnapshotRpc, + DispatchCommandRpc, + GetTurnDiffRpc, + GetFullThreadDiffRpc, + ReplayEventsRpc, + SubscribeDomainEventsRpc, + SearchEntriesRpc, + OpenInEditorRpc, + GitStatusRpc, + GitPullRpc, + GitRunStackedActionRpc, + GitListBranchesRpc, + GitCreateWorktreeRpc, + GitRemoveWorktreeRpc, + GitCreateBranchRpc, + GitCheckoutRpc, + GitInitRpc, + GitResolvePullRequestRpc, + GitPreparePullRequestThreadRpc, + TerminalOpenRpc, + TerminalWriteRpc, + TerminalResizeRpc, + TerminalClearRpc, + TerminalRestartRpc, + TerminalCloseRpc, + SubscribeTerminalEventsRpc, +); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 96ea90c1f5..622bf5771e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -3,6 +3,7 @@ import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas"; import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings"; import { EditorId } from "./editor"; import { ProviderKind } from "./orchestration"; +import { ProjectId, ThreadId } from "./baseSchemas"; const KeybindingsMalformedConfigIssue = Schema.Struct({ kind: Schema.Literal("keybindings.malformed-config"), @@ -55,6 +56,14 @@ export const ServerConfig = Schema.Struct({ }); export type ServerConfig = typeof ServerConfig.Type; +export const ServerBootstrapState = Schema.Struct({ + cwd: TrimmedNonEmptyString, + projectName: TrimmedNonEmptyString, + bootstrapProjectId: Schema.optional(ProjectId), + bootstrapThreadId: Schema.optional(ThreadId), +}); +export type ServerBootstrapState = typeof ServerBootstrapState.Type; + export const ServerUpsertKeybindingInput = KeybindingRule; export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type; diff --git a/packages/contracts/src/ws.ts b/packages/contracts/src/ws.ts index ebb76138b8..659161edf1 100644 --- a/packages/contracts/src/ws.ts +++ b/packages/contracts/src/ws.ts @@ -1,5 +1,5 @@ import { Schema, Struct } from "effect"; -import { NonNegativeInt, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas"; +import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas"; import { ClientOrchestrationCommand, @@ -36,7 +36,7 @@ import { import { KeybindingRule } from "./keybindings"; import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project"; import { OpenInEditorInput } from "./editor"; -import { ServerConfigUpdatedPayload } from "./server"; +import { ServerBootstrapState, ServerConfigUpdatedPayload } from "./server"; // ── WebSocket RPC Method Names ─────────────────────────────────────── @@ -161,12 +161,7 @@ export type WebSocketResponse = typeof WebSocketResponse.Type; export const WsPushSequence = NonNegativeInt; export type WsPushSequence = typeof WsPushSequence.Type; -export const WsWelcomePayload = Schema.Struct({ - cwd: TrimmedNonEmptyString, - projectName: TrimmedNonEmptyString, - bootstrapProjectId: Schema.optional(ProjectId), - bootstrapThreadId: Schema.optional(ThreadId), -}); +export const WsWelcomePayload = ServerBootstrapState; export type WsWelcomePayload = typeof WsWelcomePayload.Type; export interface WsPushPayloadByChannel {