diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 482eebc459..0156738783 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -1,6 +1,7 @@ { "$schema": "./node_modules/oxfmt/configuration_schema.json", "ignorePatterns": [ + ".reference", ".plans", "dist", "dist-electron", diff --git a/.plans/effect-atom.md b/.plans/effect-atom.md new file mode 100644 index 0000000000..ff6894f563 --- /dev/null +++ b/.plans/effect-atom.md @@ -0,0 +1,89 @@ +# Replace React Query With AtomRpc + Atom State + +## Summary +- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts). +- Keep Zustand for orchestration read model and UI state. +- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs. +- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low. + +## Target Architecture +- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`. +- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`. +- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`. +- Add `platform/desktopBridge.ts` as the only browser/desktop facade. +- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules. + +## Phase 1: Infrastructure First +1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior. +2. Build the AtomRpc client on top of that layer. +3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object. +4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`. +5. Land this as a no-behavior-change PR. + +## Phase 2: Replace `wsNativeApi`-Owned Push State +1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities. +2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`. +3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`. +4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx). +5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms. + +## Phase 3: Replace React Query Domain By Domain +1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first. +2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`. +3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`. +4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior. +5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`. +6. Defer the desktop updater until the last phase. + +## Phase 4: Move Root Invalidation Off `queryClient` +1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers. +2. Keep Zustand orchestration/event application unchanged. +3. Map current effects exactly: +- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}` +- file creation/deletion/restoration touches `project:${cwd}` +- config-affecting server events touch `server-config` + +## Phase 5: Remove Imperative `NativeApi` Usage +1. Create narrow modules instead of a replacement mega-facade: +- `rpc/orchestrationActions.ts` +- `rpc/terminalActions.ts` +- `rpc/gitActions.ts` +- `rpc/projectActions.ts` +- `platform/desktopBridge.ts` +2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers. +3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely. +4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it. + +## Phase 6: Remove React Query Completely +1. Delete `@tanstack/react-query` from `apps/web/package.json`. +2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx). +3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`. +4. Delete the old query-option tests. + +## Public Interfaces And Types +- Preserve the current server-state hook names during the transition. +- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`. +- Do not expose raw AtomRpc clients to components. +- Do not add Suspense as part of this migration. +- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features. + +## Test Plan +- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates. +- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior. +- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`. +- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage. +- Acceptance scenarios: +- welcome still bootstraps snapshot and navigation +- keybindings toast still responds to config stream updates +- git status/branches refresh after checkout/pull/worktree actions +- PR resolve dialog keeps cached result while typing +- `@` path search refreshes after file mutations and orchestration events +- diff panel refreshes when checkpoints arrive +- desktop updater still reflects push events and button actions + +## Assumptions And Defaults +- Zustand stays in scope; only `react-query` is being removed. +- `desktopBridge` remains the only non-RPC boundary. +- The migration lands as 5-6 small PRs, each green independently. +- Invalidations are explicit and scoped; do not recreate a global cache client abstraction. +- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 7ecb81c791..dfa3bde2f8 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -24,8 +24,7 @@ "@types/node": "catalog:", "tsdown": "catalog:", "typescript": "catalog:", - "vitest": "catalog:", - "wait-on": "^8.0.2" + "vitest": "catalog:" }, "productName": "T3 Code (Alpha)" } diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 12d4753509..5244d51dbf 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -1,27 +1,29 @@ import { spawn, spawnSync } from "node:child_process"; import { watch } from "node:fs"; import { join } from "node:path"; -import waitOn from "wait-on"; import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; +import { waitForResources } from "./wait-for-resources.mjs"; const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733); const devServerUrl = `http://localhost:${port}`; const requiredFiles = [ "dist-electron/main.js", "dist-electron/preload.js", - "../server/dist/index.mjs", + "../server/dist/bin.mjs", ]; const watchedDirectories = [ { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) }, - { directory: "../server/dist", files: new Set(["index.mjs"]) }, + { directory: "../server/dist", files: new Set(["bin.mjs"]) }, ]; const forcedShutdownTimeoutMs = 1_500; const restartDebounceMs = 120; const childTreeGracePeriodMs = 1_200; -await waitOn({ - resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)], +await waitForResources({ + baseDir: desktopDir, + files: requiredFiles, + tcpPort: port, }); const childEnv = { ...process.env }; diff --git a/apps/desktop/scripts/wait-for-resources.mjs b/apps/desktop/scripts/wait-for-resources.mjs new file mode 100644 index 0000000000..2b0a60c5d9 --- /dev/null +++ b/apps/desktop/scripts/wait-for-resources.mjs @@ -0,0 +1,119 @@ +import * as FileSystem from "node:fs/promises"; +import * as Net from "node:net"; +import * as Path from "node:path"; +import * as Timers from "node:timers/promises"; + +const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"]; + +async function fileExists(filePath) { + try { + await FileSystem.access(filePath); + return true; + } catch { + return false; + } +} + +function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) { + return new Promise((resolveReady) => { + const socket = Net.createConnection({ host, port }); + let settled = false; + + const finish = (ready) => { + if (settled) { + return; + } + + settled = true; + socket.removeAllListeners(); + socket.destroy(); + resolveReady(ready); + }; + + socket.once("connect", () => { + finish(true); + }); + socket.once("timeout", () => { + finish(false); + }); + socket.once("error", () => { + finish(false); + }); + socket.setTimeout(connectTimeoutMs); + }); +} + +async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) { + const pendingFiles = []; + + for (const relativeFilePath of files) { + const ready = await fileExists(Path.resolve(baseDir, relativeFilePath)); + if (!ready) { + pendingFiles.push(relativeFilePath); + } + } + + let tcpReady = false; + for (const host of tcpHosts) { + tcpReady = await tcpPortIsReady({ + host, + port: tcpPort, + connectTimeoutMs, + }); + if (tcpReady) { + break; + } + } + + return { + pendingFiles, + tcpReady, + }; +} + +export async function waitForResources({ + baseDir, + files = [], + intervalMs = 100, + timeoutMs = 120_000, + tcpHost, + tcpPort, + connectTimeoutMs = 500, +}) { + if (!Number.isInteger(tcpPort) || tcpPort <= 0) { + throw new TypeError("waitForResources requires a positive integer tcpPort"); + } + + const startedAt = Date.now(); + const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts; + + while (true) { + const { pendingFiles, tcpReady } = await resolvePendingResources({ + baseDir, + files, + tcpPort, + tcpHosts, + connectTimeoutMs, + }); + + if (pendingFiles.length === 0 && tcpReady) { + return; + } + + if (Date.now() - startedAt >= timeoutMs) { + const pendingResources = []; + if (!tcpReady) { + pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`); + } + for (const filePath of pendingFiles) { + pendingResources.push(`file:${filePath}`); + } + + throw new Error( + `Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`, + ); + } + + await Timers.setTimeout(intervalMs); + } +} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f1086e9c29..34391a5995 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -66,6 +66,8 @@ const ROOT_DIR = Path.resolve(__dirname, "../../.."); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; const APP_USER_MODEL_ID = "com.t3tools.t3code"; +const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop"; +const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code"; const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code"; const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i; @@ -80,6 +82,9 @@ const DESKTOP_UPDATE_CHANNEL = "latest"; const DESKTOP_UPDATE_ALLOW_PRERELEASE = false; type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"]; +type LinuxDesktopNamedApp = Electron.App & { + setDesktopName?: (desktopName: string) => void; +}; let mainWindow: BrowserWindow | null = null; let backendProcess: ChildProcess.ChildProcess | null = null; @@ -263,6 +268,10 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void { initializePackagedLogging(); +if (process.platform === "linux") { + app.commandLine.appendSwitch("class", LINUX_WM_CLASS); +} + function getDestructiveMenuIcon(): Electron.NativeImage | undefined { if (process.platform !== "darwin") return undefined; if (destructiveMenuIconCache !== undefined) { @@ -390,7 +399,7 @@ function resolveAboutCommitHash(): string | null { } function resolveBackendEntry(): string { - return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs"); + return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs"); } function resolveBackendCwd(): string { @@ -715,6 +724,10 @@ function configureAppIdentity(): void { app.setAppUserModelId(APP_USER_MODEL_ID); } + if (process.platform === "linux") { + (app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME); + } + if (process.platform === "darwin" && app.dock) { const iconPath = resolveIconPath("png"); if (iconPath) { diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index e66a214fb7..408ea827c2 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -68,6 +68,8 @@ import { type TestProviderAdapterHarness, } from "./TestProviderAdapter.integration.ts"; import { deriveServerPaths, ServerConfig } from "../src/config.ts"; +import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts"; function runGit(cwd: string, args: ReadonlyArray) { return execFileSync("git", args, { @@ -124,7 +126,7 @@ function waitFor( read: Effect.Effect, predicate: (value: A) => boolean, description: string, - timeoutMs = 10_000, + timeoutMs = 40_000, ): Effect.Effect { const RETRY_SIGNAL = "wait_for_retry"; const retryIntervalMs = 10; @@ -317,6 +319,14 @@ export const makeOrchestrationIntegrationHarness = ( ); const checkpointReactorLayer = CheckpointReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge( + WorkspaceEntriesLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provideMerge(gitCoreLayer), + Layer.provide(NodeServices.layer), + ), + ), + Layer.provideMerge(WorkspacePathsLive), ); const orchestrationReactorLayer = OrchestrationReactorLive.pipe( Layer.provideMerge(runtimeIngestionLayer), diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index d6b1004749..a5cc8f8cc6 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -57,7 +57,7 @@ function waitForSync( read: () => A, predicate: (value: A) => boolean, description: string, - timeoutMs = 3000, + timeoutMs = 10_000, ): Effect.Effect { return Effect.gen(function* () { const deadline = Date.now() + timeoutMs; diff --git a/apps/server/package.json b/apps/server/package.json index e473e21fd1..e59c7c208c 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -8,29 +8,29 @@ "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" }, "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.2.77", + "@effect/platform-bun": "catalog:", "@effect/platform-node": "catalog:", "@effect/sql-sqlite-bun": "catalog:", "@pierre/diffs": "^1.1.0-beta.16", "effect": "catalog:", "node-pty": "^1.1.0", - "open": "^10.1.0", - "ws": "^8.18.0" + "open": "^10.1.0" }, "devDependencies": { "@effect/language-service": "catalog:", @@ -40,7 +40,6 @@ "@t3tools/web": "workspace:*", "@types/bun": "catalog:", "@types/node": "catalog:", - "@types/ws": "^8.5.13", "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:" diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts new file mode 100644 index 0000000000..063d43326c --- /dev/null +++ b/apps/server/src/bin.ts @@ -0,0 +1,17 @@ +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 { Command } from "effect/unstable/cli"; + +import { NetService } from "@t3tools/shared/Net"; +import { cli } from "./cli"; +import { version } from "../package.json" with { type: "json" }; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +Command.run(cli, { version }).pipe( + Effect.scoped, + Effect.provide(CliRuntimeLayer), + NodeRuntime.runMain, +); diff --git a/apps/server/src/checkpointing/Errors.ts b/apps/server/src/checkpointing/Errors.ts index 782d0918e6..cb873559c1 100644 --- a/apps/server/src/checkpointing/Errors.ts +++ b/apps/server/src/checkpointing/Errors.ts @@ -1,6 +1,6 @@ import { Schema } from "effect"; import type { ProjectionRepositoryError } from "../persistence/Errors.ts"; -import { GitCommandError } from "../git/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; /** * CheckpointUnavailableError - Expected checkpoint does not exist. diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts index c430dbbde0..7df1c71c23 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -10,7 +10,7 @@ import { CheckpointStoreLive } from "./CheckpointStore.ts"; import { CheckpointStore } from "../Services/CheckpointStore.ts"; import { GitCoreLive } from "../../git/Layers/GitCore.ts"; import { GitCore } from "../../git/Services/GitCore.ts"; -import { GitCommandError } from "../../git/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; import { ServerConfig } from "../../config.ts"; import { ThreadId } from "@t3tools/contracts"; diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.ts index b20204780c..0a1d7abb9d 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointStore.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.ts @@ -14,7 +14,7 @@ import { randomUUID } from "node:crypto"; import { Effect, Layer, FileSystem, Path } from "effect"; import { CheckpointInvariantError } from "../Errors.ts"; -import { GitCommandError } from "../../git/Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; import { GitCore } from "../../git/Services/GitCore.ts"; import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts"; import { CheckpointRef } from "@t3tools/contracts"; diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts new file mode 100644 index 0000000000..27bc60b1be --- /dev/null +++ b/apps/server/src/cli-config.test.ts @@ -0,0 +1,318 @@ +import os from "node:os"; + +import { assert, expect, it } from "@effect/vitest"; +import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"; + +import { NetService } from "@t3tools/shared/Net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { deriveServerPaths } from "./config"; +import { resolveServerConfig } from "./cli"; + +it.layer(NodeServices.layer)("cli config resolution", (it) => { + const openBootstrapFd = Effect.fn(function* (payload: Record) { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`); + const { fd } = yield* fs.open(filePath, { flag: "r" }); + return fd; + }); + + it.effect("falls back to effect/config values when flags are omitted", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-env-base"); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_LOG_LEVEL: "Warn", + T3CODE_MODE: "desktop", + T3CODE_PORT: "4001", + T3CODE_HOST: "0.0.0.0", + T3CODE_HOME: baseDir, + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "true", + T3CODE_AUTH_TOKEN: "env-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Warn", + mode: "desktop", + port: 4001, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "0.0.0.0", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:5173"), + noBrowser: true, + authToken: "env-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("uses CLI flags when provided", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base"); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + const resolved = yield* resolveServerConfig( + { + mode: Option.some("web"), + port: Option.some(8788), + host: Option.some("127.0.0.1"), + baseDir: Option.some(baseDir), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.some(true), + authToken: Option.some("flag-token"), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.some(true), + logWebSocketEvents: Option.some(true), + }, + Option.some("Debug"), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_LOG_LEVEL: "Warn", + T3CODE_MODE: "desktop", + T3CODE_PORT: "4001", + T3CODE_HOST: "0.0.0.0", + T3CODE_HOME: join(os.tmpdir(), "ignored-base"), + VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", + T3CODE_NO_BROWSER: "false", + T3CODE_AUTH_TOKEN: "ignored-token", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", + T3CODE_LOG_WS_EVENTS: "false", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Debug", + mode: "web", + port: 8788, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:4173"), + noBrowser: true, + authToken: "flag-token", + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); + + it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = "/tmp/t3-bootstrap-home"; + const fd = yield* openBootstrapFd({ + mode: "desktop", + port: 4888, + host: "127.0.0.2", + t3Home: baseDir, + devUrl: "http://127.0.0.1:5173", + noBrowser: true, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); + + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_BOOTSTRAP_FD: String(fd), + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Info", + mode: "desktop", + port: 4888, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.2", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:5173"), + noBrowser: true, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: true, + }); + assert.equal(join(baseDir, "dev"), resolved.stateDir); + }), + ); + + it.effect("creates derived runtime directories during config resolution", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" }); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + devUrl: Option.some(new URL("http://127.0.0.1:5173")), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + NetService.layer, + ), + ), + ); + + for (const directory of [ + resolved.stateDir, + resolved.logsDir, + resolved.providerLogsDir, + resolved.terminalLogsDir, + resolved.attachmentsDir, + resolved.worktreesDir, + path.dirname(resolved.serverLogPath), + ]) { + expect(yield* fs.exists(directory)).toBe(true); + } + }), + ); + + it.effect("applies flag then env precedence over bootstrap envelope values", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins"); + const fd = yield* openBootstrapFd({ + mode: "desktop", + port: 4888, + host: "127.0.0.2", + t3Home: "/tmp/t3-bootstrap-home", + devUrl: "http://127.0.0.1:5173", + noBrowser: false, + authToken: "bootstrap-token", + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173")); + + const resolved = yield* resolveServerConfig( + { + mode: Option.none(), + port: Option.some(8788), + host: Option.some("127.0.0.1"), + baseDir: Option.none(), + devUrl: Option.some(new URL("http://127.0.0.1:4173")), + noBrowser: Option.none(), + authToken: Option.some("flag-token"), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.some("Debug"), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + T3CODE_MODE: "web", + T3CODE_BOOTSTRAP_FD: String(fd), + T3CODE_HOME: baseDir, + T3CODE_NO_BROWSER: "true", + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", + T3CODE_LOG_WS_EVENTS: "true", + }, + }), + ), + NetService.layer, + ), + ), + ); + + expect(resolved).toEqual({ + logLevel: "Debug", + mode: "web", + port: 8788, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: undefined, + devUrl: new URL("http://127.0.0.1:4173"), + noBrowser: true, + authToken: "flag-token", + autoBootstrapProjectFromCwd: true, + logWebSocketEvents: true, + }); + }), + ); +}); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts new file mode 100644 index 0000000000..fbbe26e6cf --- /dev/null +++ b/apps/server/src/cli.test.ts @@ -0,0 +1,37 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { NetService } from "@t3tools/shared/Net"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as CliError from "effect/unstable/cli/CliError"; +import { Command } from "effect/unstable/cli"; + +import { cli } from "./cli.ts"; + +const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); + +it.layer(NodeServices.layer)("cli log-level parsing", (it) => { + it.effect("accepts the built-in lowercase log-level flag values", () => + Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe( + Effect.provide(CliRuntimeLayer), + ), + ); + + it.effect("rejects invalid log-level casing before launching the server", () => + Effect.gen(function* () { + const error = yield* Command.runWith(cli, { version: "0.0.0" })([ + "--log-level", + "Debug", + ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip); + + if (!CliError.isCliError(error)) { + assert.fail(`Expected CliError, got ${String(error)}`); + } + if (error._tag !== "InvalidValue") { + assert.fail(`Expected InvalidValue, got ${error._tag}`); + } + assert.equal(error.option, "log-level"); + assert.equal(error.value, "Debug"); + }), + ); +}); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts new file mode 100644 index 0000000000..2f76d25b7b --- /dev/null +++ b/apps/server/src/cli.ts @@ -0,0 +1,292 @@ +import { NetService } from "@t3tools/shared/Net"; +import { Config, Effect, LogLevel, Option, Schema } from "effect"; +import { Command, Flag, GlobalFlag } from "effect/unstable/cli"; + +import { + DEFAULT_PORT, + deriveServerPaths, + ensureServerDirectories, + resolveStaticDir, + ServerConfig, + RuntimeMode, + type ServerConfigShape, +} from "./config"; +import { readBootstrapEnvelope } from "./bootstrap"; +import { resolveBaseDir } from "./os-jank"; +import { runServer } from "./server"; + +const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); + +const BootstrapEnvelopeSchema = Schema.Struct({ + mode: Schema.optional(RuntimeMode), + port: Schema.optional(PortSchema), + host: Schema.optional(Schema.String), + t3Home: Schema.optional(Schema.String), + devUrl: Schema.optional(Schema.URLFromString), + noBrowser: Schema.optional(Schema.Boolean), + authToken: Schema.optional(Schema.String), + autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), + logWebSocketEvents: Schema.optional(Schema.Boolean), +}); + +const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe( + Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."), + Flag.optional, +); +const portFlag = Flag.integer("port").pipe( + Flag.withSchema(PortSchema), + 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 baseDirFlag = Flag.string("base-dir").pipe( + Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."), + 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 bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe( + Flag.withSchema(Schema.Int), + Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."), + 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, +); + +const EnvServerConfig = Config.all({ + logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")), + mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), + port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), + host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), + t3Home: Config.string("T3CODE_HOME").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), + ), + bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").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), + ), +}); + +interface CliServerFlags { + readonly mode: Option.Option; + readonly port: Option.Option; + readonly host: Option.Option; + readonly baseDir: Option.Option; + readonly devUrl: Option.Option; + readonly noBrowser: Option.Option; + readonly authToken: Option.Option; + readonly bootstrapFd: Option.Option; + readonly autoBootstrapProjectFromCwd: Option.Option; + readonly logWebSocketEvents: Option.Option; +} + +const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => + Option.getOrElse(Option.filter(flag, Boolean), () => envValue); + +const resolveOptionPrecedence = ( + ...values: ReadonlyArray> +): Option.Option => Option.firstSomeOf(values); + +export const resolveServerConfig = ( + flags: CliServerFlags, + cliLogLevel: Option.Option, +) => + Effect.gen(function* () { + const { findAvailablePort } = yield* NetService; + const env = yield* EnvServerConfig; + const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd; + const bootstrapEnvelope = + bootstrapFd !== undefined + ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd) + : Option.none(); + + const mode: RuntimeMode = Option.getOrElse( + resolveOptionPrecedence( + flags.mode, + Option.fromUndefinedOr(env.mode), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)), + ), + () => "web", + ); + + const port = yield* Option.match( + resolveOptionPrecedence( + flags.port, + Option.fromUndefinedOr(env.port), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(DEFAULT_PORT); + } + return findAvailablePort(DEFAULT_PORT); + }, + }, + ); + const devUrl = Option.getOrElse( + resolveOptionPrecedence( + flags.devUrl, + Option.fromUndefinedOr(env.devUrl), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)), + ), + () => undefined, + ); + const baseDir = yield* resolveBaseDir( + Option.getOrUndefined( + resolveOptionPrecedence( + flags.baseDir, + Option.fromUndefinedOr(env.t3Home), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.t3Home), + ), + ), + ), + ); + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + yield* ensureServerDirectories(derivedPaths); + const noBrowser = resolveBooleanFlag( + flags.noBrowser, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.noBrowser), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.noBrowser), + ), + ), + () => mode === "desktop", + ), + ); + const authToken = Option.getOrUndefined( + resolveOptionPrecedence( + flags.authToken, + Option.fromUndefinedOr(env.authToken), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.authToken), + ), + ), + ); + const autoBootstrapProjectFromCwd = resolveBooleanFlag( + flags.autoBootstrapProjectFromCwd, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd), + ), + ), + () => mode === "web", + ), + ); + const logWebSocketEvents = resolveBooleanFlag( + flags.logWebSocketEvents, + Option.getOrElse( + resolveOptionPrecedence( + Option.fromUndefinedOr(env.logWebSocketEvents), + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.logWebSocketEvents), + ), + ), + () => Boolean(devUrl), + ), + ); + const staticDir = devUrl ? undefined : yield* resolveStaticDir(); + const host = Option.getOrElse( + resolveOptionPrecedence( + flags.host, + Option.fromUndefinedOr(env.host), + Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)), + ), + () => (mode === "desktop" ? "127.0.0.1" : undefined), + ); + const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); + + const config: ServerConfigShape = { + logLevel, + mode, + port, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host, + staticDir, + devUrl, + noBrowser, + authToken, + autoBootstrapProjectFromCwd, + logWebSocketEvents, + }; + + return config; + }); + +const commandFlags = { + mode: modeFlag, + port: portFlag, + host: hostFlag, + baseDir: baseDirFlag, + devUrl: devUrlFlag, + noBrowser: noBrowserFlag, + authToken: authTokenFlag, + bootstrapFd: bootstrapFdFlag, + autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, + logWebSocketEvents: logWebSocketEventsFlag, +} as const; + +const rootCommand = Command.make("t3", commandFlags).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((flags) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveServerConfig(flags, logLevel); + return yield* runServer.pipe(Effect.provideService(ServerConfig, config)); + }), + ), +); + +export const cli = rootCommand; diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 29f82bccf1..21cd6f3150 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -6,11 +6,12 @@ * * @module ServerConfig */ -import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect"; +import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect"; export const DEFAULT_PORT = 3773; -export type RuntimeMode = "web" | "desktop"; +export const RuntimeMode = Schema.Literals(["web", "desktop"]); +export type RuntimeMode = typeof RuntimeMode.Type; /** * ServerDerivedPaths - Derived paths from the base directory. @@ -34,6 +35,7 @@ export interface ServerDerivedPaths { * ServerConfigShape - Process/runtime configuration required by the server. */ export interface ServerConfigShape extends ServerDerivedPaths { + readonly logLevel: LogLevel.LogLevel; readonly mode: RuntimeMode; readonly port: number; readonly host: string | undefined; @@ -73,6 +75,26 @@ export const deriveServerPaths = Effect.fn(function* ( }; }); +export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* Effect.all( + [ + fs.makeDirectory(derivedPaths.stateDir, { recursive: true }), + fs.makeDirectory(derivedPaths.logsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }), + fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }), + fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }), + ], + { concurrency: "unbounded" }, + ); +}); + /** * ServerConfig - Service tag for server runtime configuration. */ @@ -91,12 +113,10 @@ export class ServerConfig extends ServiceMap.Service()("GitCommandError", { - operation: Schema.String, - command: Schema.String, - cwd: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), -}) { - override get message(): string { - return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`; - } -} - -/** - * GitHubCliError - GitHub CLI execution or authentication failed. - */ -export class GitHubCliError extends Schema.TaggedErrorClass()("GitHubCliError", { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), -}) { - override get message(): string { - return `GitHub CLI failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * TextGenerationError - Commit or PR text generation failed. - */ -export class TextGenerationError extends Schema.TaggedErrorClass()( - "TextGenerationError", - { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Text generation failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * GitManagerError - Stacked Git workflow orchestration failed. - */ -export class GitManagerError extends Schema.TaggedErrorClass()("GitManagerError", { - operation: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), -}) { - override get message(): string { - return `Git manager failed in ${this.operation}: ${this.detail}`; - } -} - -/** - * GitManagerServiceError - Errors emitted by stacked Git workflow orchestration. - */ -export type GitManagerServiceError = - | GitManagerError - | GitCommandError - | GitHubCliError - | TextGenerationError; diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 78baf26444..1ec2cf874d 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -15,7 +15,7 @@ import { resolveApiModelId } from "@t3tools/shared/model"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { toJsonSchemaObject } from "@t3tools/shared/schemaJson"; -import { TextGenerationError } from "../Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; import { buildBranchNamePrompt, diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 21a97eec9c..a07505f025 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -5,7 +5,7 @@ import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; import { CodexTextGenerationLive } from "./CodexTextGeneration.ts"; -import { TextGenerationError } from "../Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { TextGeneration } from "../Services/TextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 7d62015812..3e2bbdcabf 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -9,7 +9,7 @@ import { toJsonSchemaObject } from "@t3tools/shared/schemaJson"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { ServerConfig } from "../../config.ts"; -import { TextGenerationError } from "../Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { type BranchNameGenerationInput, type ThreadTitleGenerationResult, diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 547a69e7e1..07892ec447 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -8,7 +8,7 @@ import { describe, expect, vi } from "vitest"; import { GitCoreLive, makeGitCore } from "./GitCore.ts"; import { GitCore, type GitCoreShape } from "../Services/GitCore.ts"; -import { GitCommandError } from "../Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; import { type ProcessRunResult, runProcess } from "../../processRunner.ts"; import { ServerConfig } from "../../config.ts"; @@ -138,6 +138,13 @@ function buildLargeText(lineCount = 20_000): string { .concat("\n"); } +function splitNullSeparatedPaths(input: string): string[] { + return input + .split("\0") + .map((value) => value.trim()) + .filter((value) => value.length > 0); +} + // ── Tests ── it.layer(TestLayer)("git integration", (it) => { @@ -181,6 +188,55 @@ it.layer(TestLayer)("git integration", (it) => { ); }); + describe("workspace helpers", () => { + it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => + Effect.gen(function* () { + const cwd = "/virtual/repo"; + const relativePaths = Array.from({ length: 340 }, (_, index) => { + const prefix = index % 3 === 0 ? "ignored" : "kept"; + return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; + }); + const expectedPaths = relativePaths.filter( + (relativePath) => !relativePath.startsWith("ignored/"), + ); + + const seenChunks: string[][] = []; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") { + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "unexpected git command in chunking test", + }), + ); + } + + const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); + seenChunks.push(chunkPaths); + const ignoredPaths = chunkPaths.filter((relativePath) => + relativePath.startsWith("ignored/"), + ); + + return Effect.succeed({ + code: ignoredPaths.length > 0 ? 0 : 1, + stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }); + + const result = yield* core.filterIgnoredPaths(cwd, relativePaths); + + expect(seenChunks.length).toBeGreaterThan(1); + expect(seenChunks.flat()).toEqual(relativePaths); + expect(result).toEqual(expectedPaths); + }), + ); + }); + // ── listGitBranches ── describe("listGitBranches", () => { @@ -313,6 +369,64 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("parses separate branch names when column.ui is always enabled", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const createdBranchNames = [ + "go-bin", + "copilot/rewrite-cli-in-go", + "copilot/rewrite-cli-in-rust", + ] as const; + for (const branchName of createdBranchNames) { + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName }); + } + yield* git(tmp, ["config", "column.ui", "always"]); + + const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], { + ...process.env, + COLUMNS: "120", + }); + expect( + rawBranchOutput + .split("\n") + .some( + (line) => + createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2, + ), + ).toBe(true); + + const realGitCore = yield* GitCore; + const core = yield* makeIsolatedGitCore((input) => + realGitCore.execute( + input.args[0] === "branch" + ? { + ...input, + env: { ...input.env, COLUMNS: "120" }, + } + : input, + ), + ); + + const result = yield* core.listBranches({ cwd: tmp }); + const localBranchNames = result.branches + .filter((branch) => !branch.isRemote) + .map((branch) => branch.name); + + expect(localBranchNames).toHaveLength(4); + expect(localBranchNames).toEqual( + expect.arrayContaining([initialBranch, ...createdBranchNames]), + ); + expect( + localBranchNames.some( + (branchName) => + createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch)) + .length >= 2, + ), + ).toBe(false); + }), + ); + it.effect("isDefault is false when no remote exists", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -457,12 +571,18 @@ it.layer(TestLayer)("git integration", (it) => { yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); const core = yield* GitCore; yield* Effect.promise(() => - vi.waitFor(async () => { - const details = await runPromise(core.statusDetails(source)); - expect(details.branch).toBe(featureBranch); - expect(details.aheadCount).toBe(0); - expect(details.behindCount).toBe(1); - }), + vi.waitFor( + async () => { + const details = await runPromise(core.statusDetails(source)); + expect(details.branch).toBe(featureBranch); + expect(details.aheadCount).toBe(0); + expect(details.behindCount).toBe(1); + }, + { + timeout: 10_000, + interval: 100, + }, + ), ); }), ); @@ -541,7 +661,13 @@ it.layer(TestLayer)("git integration", (it) => { const core = yield* makeIsolatedGitCore((input) => { if (input.args[0] === "fetch") { fetchArgs = [...input.args]; - return Effect.succeed({ code: 0, stdout: "", stderr: "" }); + return Effect.succeed({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); } return realGitCore.execute(input); }); @@ -594,7 +720,13 @@ it.layer(TestLayer)("git integration", (it) => { if (input.args[0] === "fetch") { fetchStarted = true; return Effect.promise(() => - waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })), + waitForReleasePromise.then(() => ({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + })), ); } return realGitCore.execute(input); @@ -1824,7 +1956,7 @@ it.layer(TestLayer)("git integration", (it) => { let didFailRemoteBranches = false; let didFailRemoteNames = false; const core = yield* makeIsolatedGitCore((input) => { - if (input.args.join(" ") === "branch --no-color --remotes") { + if (input.args.join(" ") === "branch --no-color --no-column --remotes") { didFailRemoteBranches = true; return Effect.fail( new GitCommandError({ diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 64ed409508..cbb2c67449 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -18,7 +18,7 @@ import { } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { GitCommandError } from "../Errors.ts"; +import { GitCommandError } from "@t3tools/contracts"; import { GitCore, type ExecuteGitProgress, @@ -37,6 +37,8 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; +const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; +const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; @@ -55,6 +57,7 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{ }> {} interface ExecuteGitOptions { + stdin?: string | undefined; timeoutMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorMessage?: string | undefined; @@ -96,6 +99,47 @@ function parseNumstatEntries( return entries; } +function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { + const parts = input.split("\0"); + if (parts.length === 0) return []; + + if (truncated && parts[parts.length - 1]?.length) { + parts.pop(); + } + + return parts.filter((value) => value.length > 0); +} + +function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] { + const chunks: string[][] = []; + let chunk: string[] = []; + let chunkBytes = 0; + + for (const relativePath of relativePaths) { + const relativePathBytes = Buffer.byteLength(relativePath) + 1; + if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + + chunk.push(relativePath); + chunkBytes += relativePathBytes; + + if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + } + + if (chunk.length > 0) { + chunks.push(chunk); + } + + return chunks; +} + function parsePorcelainPath(line: string): string | null { if (line.startsWith("? ") || line.startsWith("! ")) { const simple = line.slice(2).trim(); @@ -445,7 +489,7 @@ const collectOutput = Effect.fn("collectOutput")(function* ( maxOutputBytes: number, truncateOutputAtMaxBytes: boolean, onLine: ((line: string) => Effect.Effect) | undefined, -): Effect.fn.Return { +): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { const decoder = new TextDecoder(); let bytes = 0; let text = ""; @@ -507,7 +551,10 @@ const collectOutput = Effect.fn("collectOutput")(function* ( text += remainder; lineBuffer += remainder; yield* emitCompleteLines(true); - return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text; + return { + text, + truncated, + }; }); export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { @@ -571,13 +618,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { Effect.map((value) => Number(value)), Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), ), + input.stdin === undefined + ? Effect.void + : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe( + Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")), + ), ], { concurrency: "unbounded" }, - ); + ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const)); yield* trace2Monitor.flush; if (!input.allowNonZeroExit && exitCode !== 0) { - const trimmedStderr = stderr.trim(); + const trimmedStderr = stderr.text.trim(); return yield* new GitCommandError({ operation: commandInput.operation, command: quoteGitCommand(commandInput.args), @@ -589,7 +641,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }); } - return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; + return { + code: exitCode, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + } satisfies ExecuteGitResult; }); return yield* runGitCommand().pipe( @@ -618,11 +676,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { cwd: string, args: readonly string[], options: ExecuteGitOptions = {}, - ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => + ): Effect.Effect => execute({ operation, cwd, args, + ...(options.stdin !== undefined ? { stdin: options.stdin } : {}), allowNonZeroExit: true, ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), @@ -679,7 +738,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { args: readonly string[], options: ExecuteGitOptions = {}, ): Effect.Effect => - executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); + executeGit(operation, cwd, args, options).pipe( + Effect.map((result) => + result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout, + ), + ); const branchExists = (cwd: string, branch: string): Effect.Effect => executeGit( @@ -1416,6 +1479,86 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); + const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) => + executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], { + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 4_096, + }).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true")); + + const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) => + executeGit( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + { + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe( + Effect.flatMap((result) => + result.code === 0 + ? Effect.succeed({ + paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated), + truncated: result.stdoutTruncated, + }) + : Effect.fail( + createGitCommandError( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed", + ), + ), + ), + ); + + const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) => + Effect.gen(function* () { + if (relativePaths.length === 0) { + return relativePaths; + } + + const ignoredPaths = new Set(); + const chunks = chunkPathsForGitCheckIgnore(relativePaths); + + for (const chunk of chunks) { + const result = yield* executeGit( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + { + stdin: `${chunk.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + if (result.code !== 0 && result.code !== 1) { + return yield* createGitCommandError( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed", + ); + } + + for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) { + ignoredPaths.add(ignoredPath); + } + } + + if (ignoredPaths.size === 0) { + return relativePaths; + } + + return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); + }); + const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { const branchRecencyPromise = readBranchRecency(input.cwd).pipe( Effect.catch(() => Effect.succeed(new Map())), @@ -1423,7 +1566,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const localBranchResult = yield* executeGit( "GitCore.listBranches.branchNoColor", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], { timeoutMs: 10_000, allowNonZeroExit: true, @@ -1438,7 +1581,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { return yield* createGitCommandError( "GitCore.listBranches", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], stderr || "git branch failed", ); } @@ -1446,7 +1589,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const remoteBranchResultEffect = executeGit( "GitCore.listBranches.remoteBranches", input.cwd, - ["branch", "--no-color", "--remotes"], + ["branch", "--no-color", "--no-column", "--remotes"], { timeoutMs: 10_000, allowNonZeroExit: true, @@ -1798,8 +1941,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }); // Refresh upstream refs in the background so checkout remains responsive. - yield* Effect.forkScoped( - refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), + yield* refreshCheckedOutBranchUpstream(input.cwd).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkDetach({ startImmediately: true }), ); }, ); @@ -1814,6 +1958,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { runGitStdout("GitCore.listLocalBranchNames", cwd, [ "branch", "--list", + "--no-column", "--format=%(refname:short)", ]).pipe( Effect.map((stdout) => @@ -1834,6 +1979,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { pullCurrentBranch, readRangeContext, readConfigValue, + isInsideWorkTree, + listWorkspaceFiles, + filterIgnoredPaths, listBranches, createWorktree, fetchPullRequestBranch, diff --git a/apps/server/src/git/Layers/GitHubCli.ts b/apps/server/src/git/Layers/GitHubCli.ts index 80ce43659e..76d7d30a47 100644 --- a/apps/server/src/git/Layers/GitHubCli.ts +++ b/apps/server/src/git/Layers/GitHubCli.ts @@ -2,7 +2,7 @@ import { Effect, Layer, Schema } from "effect"; import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts"; import { runProcess } from "../../processRunner"; -import { GitHubCliError } from "../Errors.ts"; +import { GitHubCliError } from "@t3tools/contracts"; import { GitHubCli, type GitHubRepositoryCloneUrls, diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index db82ea4c72..e05fc30875 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -8,7 +8,7 @@ import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { expect } from "vitest"; import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts"; -import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts"; +import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts"; import { type GitManagerShape } from "../Services/GitManager.ts"; import { type GitHubCliShape, diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index dc082674b7..f8445cf09a 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -14,7 +14,7 @@ import { sanitizeFeatureBranchName, } from "@t3tools/shared/git"; -import { GitManagerError } from "../Errors.ts"; +import { GitManagerError } from "@t3tools/contracts"; import { GitManager, type GitActionProgressReporter, @@ -25,7 +25,7 @@ import { GitCore } from "../Services/GitCore.ts"; import { GitHubCli } from "../Services/GitHubCli.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import type { GitManagerServiceError } from "../Errors.ts"; +import type { GitManagerServiceError } from "@t3tools/contracts"; const COMMIT_TIMEOUT_MS = 10 * 60_000; const MAX_PROGRESS_TEXT_LENGTH = 500; diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/git/Prompts.test.ts index 7951e78b39..d8d079c0cf 100644 --- a/apps/server/src/git/Prompts.test.ts +++ b/apps/server/src/git/Prompts.test.ts @@ -7,7 +7,7 @@ import { buildThreadTitlePrompt, } from "./Prompts.ts"; import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts"; -import { TextGenerationError } from "./Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; describe("buildCommitMessagePrompt", () => { it("includes staged patch and summary in the prompt", () => { diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index f1a4e065cd..d7a28d1763 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -22,12 +22,13 @@ import type { GitStatusResult, } from "@t3tools/contracts"; -import type { GitCommandError } from "../Errors.ts"; +import type { GitCommandError } from "@t3tools/contracts"; export interface ExecuteGitInput { readonly operation: string; readonly cwd: string; readonly args: ReadonlyArray; + readonly stdin?: string; readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; @@ -40,6 +41,8 @@ export interface ExecuteGitResult { readonly code: number; readonly stdout: string; readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; } export interface GitStatusDetails extends Omit { @@ -93,6 +96,11 @@ export interface GitRangeContext { diffPatch: string; } +export interface GitListWorkspaceFilesResult { + readonly paths: ReadonlyArray; + readonly truncated: boolean; +} + export interface GitRenameBranchInput { cwd: string; oldBranch: string; @@ -190,6 +198,26 @@ export interface GitCoreShape { key: string, ) => Effect.Effect; + /** + * Determine whether the provided cwd is inside a git work tree. + */ + readonly isInsideWorkTree: (cwd: string) => Effect.Effect; + + /** + * List tracked and untracked workspace file paths relative to cwd. + */ + readonly listWorkspaceFiles: ( + cwd: string, + ) => Effect.Effect; + + /** + * Remove gitignored paths from a relative path list. + */ + readonly filterIgnoredPaths: ( + cwd: string, + relativePaths: ReadonlyArray, + ) => Effect.Effect, GitCommandError>; + /** * List local + remote branches and branch metadata. */ diff --git a/apps/server/src/git/Services/GitHubCli.ts b/apps/server/src/git/Services/GitHubCli.ts index f10339af47..38afdd5f92 100644 --- a/apps/server/src/git/Services/GitHubCli.ts +++ b/apps/server/src/git/Services/GitHubCli.ts @@ -9,7 +9,7 @@ import { ServiceMap } from "effect"; import type { Effect } from "effect"; import type { ProcessRunResult } from "../../processRunner"; -import type { GitHubCliError } from "../Errors.ts"; +import type { GitHubCliError } from "@t3tools/contracts"; export interface GitHubPullRequestSummary { readonly number: number; diff --git a/apps/server/src/git/Services/GitManager.ts b/apps/server/src/git/Services/GitManager.ts index 2e83b78c3b..a99e4d3bc4 100644 --- a/apps/server/src/git/Services/GitManager.ts +++ b/apps/server/src/git/Services/GitManager.ts @@ -19,7 +19,7 @@ import { } from "@t3tools/contracts"; import { ServiceMap } from "effect"; import type { Effect } from "effect"; -import type { GitManagerServiceError } from "../Errors.ts"; +import type { GitManagerServiceError } from "@t3tools/contracts"; export interface GitActionProgressReporter { readonly publish: (event: GitActionProgressEvent) => Effect.Effect; diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/git/Services/TextGeneration.ts index 0df2fff62c..f4354c7a99 100644 --- a/apps/server/src/git/Services/TextGeneration.ts +++ b/apps/server/src/git/Services/TextGeneration.ts @@ -10,7 +10,7 @@ import { ServiceMap } from "effect"; import type { Effect } from "effect"; import type { ChatAttachment, ModelSelection } from "@t3tools/contracts"; -import type { TextGenerationError } from "../Errors.ts"; +import type { TextGenerationError } from "@t3tools/contracts"; /** Providers that support git text generation (commit messages, PR content, branch names). */ export type TextGenerationProvider = "codex" | "claudeAgent"; diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index 1f026abf38..72caa7ff34 100644 --- a/apps/server/src/git/Utils.ts +++ b/apps/server/src/git/Utils.ts @@ -5,7 +5,7 @@ */ import { Schema } from "effect"; -import { TextGenerationError } from "./Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { existsSync } from "node:fs"; import { join } from "node:path"; diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts new file mode 100644 index 0000000000..cee08b4f98 --- /dev/null +++ b/apps/server/src/http.ts @@ -0,0 +1,197 @@ +import Mime from "@effect/platform-node/Mime"; +import { Effect, FileSystem, Option, Path } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import { + ATTACHMENTS_ROUTE_PREFIX, + normalizeAttachmentRelativePath, + resolveAttachmentRelativePath, +} from "./attachmentPaths"; +import { resolveAttachmentPathById } from "./attachmentStore"; +import { ServerConfig } from "./config"; +import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver"; + +const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600"; +const FALLBACK_PROJECT_FAVICON_SVG = ``; + +export const attachmentsRouteLayer = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const config = yield* ServerConfig; + const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length); + const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath); + if (!normalizedRelativePath) { + return HttpServerResponse.text("Invalid attachment path", { status: 400 }); + } + + const isIdLookup = + !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes("."); + const filePath = isIdLookup + ? resolveAttachmentPathById({ + attachmentsDir: config.attachmentsDir, + attachmentId: normalizedRelativePath, + }) + : resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: normalizedRelativePath, + }); + if (!filePath) { + return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", { + status: isIdLookup ? 404 : 400, + }); + } + + const fileSystem = yield* FileSystem.FileSystem; + const fileInfo = yield* fileSystem + .stat(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + + return yield* HttpServerResponse.file(filePath, { + status: 200, + headers: { + "Cache-Control": "public, max-age=31536000, immutable", + }, + }).pipe( + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), + ), + ); + }), +); + +export const projectFaviconRouteLayer = HttpRouter.add( + "GET", + "/api/project-favicon", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const projectCwd = url.value.searchParams.get("cwd"); + if (!projectCwd) { + return HttpServerResponse.text("Missing cwd parameter", { status: 400 }); + } + + const faviconResolver = yield* ProjectFaviconResolver; + const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd); + if (!faviconFilePath) { + return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, { + status: 200, + contentType: "image/svg+xml", + headers: { + "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL, + }, + }); + } + + return yield* HttpServerResponse.file(faviconFilePath, { + status: 200, + headers: { + "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL, + }, + }).pipe( + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), + ), + ); + }), +); + +export const staticAndDevRouteLayer = HttpRouter.add( + "GET", + "*", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Bad Request", { status: 400 }); + } + + const config = yield* ServerConfig; + if (config.devUrl) { + return HttpServerResponse.redirect(config.devUrl.href, { status: 302 }); + } + + if (!config.staticDir) { + return HttpServerResponse.text("No static directory configured and no dev URL set.", { + status: 503, + }); + } + + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticRoot = path.resolve(config.staticDir); + const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname; + const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, ""); + const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(".."); + const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, ""); + const hasPathTraversalSegment = staticRelativePath.startsWith(".."); + if ( + staticRelativePath.length === 0 || + hasRawLeadingParentSegment || + hasPathTraversalSegment || + staticRelativePath.includes("\0") + ) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + + const isWithinStaticRoot = (candidate: string) => + candidate === staticRoot || + candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`); + + let filePath = path.resolve(staticRoot, staticRelativePath); + if (!isWithinStaticRoot(filePath)) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + + const ext = path.extname(filePath); + if (!ext) { + filePath = path.resolve(filePath, "index.html"); + if (!isWithinStaticRoot(filePath)) { + return HttpServerResponse.text("Invalid static file path", { status: 400 }); + } + } + + const fileInfo = yield* fileSystem + .stat(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + const indexPath = path.resolve(staticRoot, "index.html"); + const indexData = yield* fileSystem + .readFile(indexPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!indexData) { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + return HttpServerResponse.uint8Array(indexData, { + status: 200, + contentType: "text/html; charset=utf-8", + }); + } + + const contentType = Mime.getType(filePath) ?? "application/octet-stream"; + const data = yield* fileSystem + .readFile(filePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!data) { + return HttpServerResponse.text("Internal Server Error", { status: 500 }); + } + + return HttpServerResponse.uint8Array(data, { + status: 200, + contentType, + }); + }), +); 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/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 9cf0394142..8eda0ca85d 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -8,13 +8,13 @@ import { ServerConfig } from "./config"; import { DEFAULT_KEYBINDINGS, Keybindings, - KeybindingsConfigError, KeybindingsLive, ResolvedKeybindingFromConfig, compileResolvedKeybindingRule, compileResolvedKeybindingsConfig, parseKeybindingShortcut, } from "./keybindings"; +import { KeybindingsConfigError } from "@t3tools/contracts"; const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); const makeKeybindingsLayer = () => { diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index a3d73b459b..655222387c 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -9,6 +9,7 @@ import { KeybindingRule, KeybindingsConfig, + KeybindingsConfigError, KeybindingShortcut, KeybindingWhenNode, MAX_KEYBINDINGS_COUNT, @@ -45,19 +46,6 @@ import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config"; import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson"; -export class KeybindingsConfigError extends Schema.TaggedErrorClass()( - "KeybindingsConfigParseError", - { - configPath: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`; - } -} - type WhenToken = | { type: "identifier"; value: string } | { type: "not" } diff --git a/apps/server/src/logger.ts b/apps/server/src/logger.ts deleted file mode 100644 index b9d18569cc..0000000000 --- a/apps/server/src/logger.ts +++ /dev/null @@ -1,103 +0,0 @@ -import util from "node:util"; - -type LogLevel = "info" | "warn" | "error" | "event"; - -type LogContext = Record; - -const ANSI = { - reset: "\u001b[0m", - dim: "\u001b[2m", - cyan: "\u001b[36m", - yellow: "\u001b[33m", - red: "\u001b[31m", - magenta: "\u001b[35m", -} as const; - -const LEVEL_LABEL: Record = { - info: "INFO", - warn: "WARN", - error: "ERROR", - event: "EVENT", -}; - -const LEVEL_COLOR: Record = { - info: ANSI.cyan, - warn: ANSI.yellow, - error: ANSI.red, - event: ANSI.magenta, -}; - -function useColors() { - return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined; -} - -function colorize(value: string, color: string, enabled: boolean) { - return enabled ? `${color}${value}${ANSI.reset}` : value; -} - -function timeStamp() { - return new Date().toISOString().slice(11, 23); -} - -function formatValue(value: unknown) { - if (typeof value === "string") { - return JSON.stringify(value); - } - if ( - typeof value === "number" || - typeof value === "boolean" || - value === null || - value === undefined - ) { - return String(value); - } - return util.inspect(value, { - depth: 4, - breakLength: Infinity, - compact: true, - maxArrayLength: 25, - maxStringLength: 320, - }); -} - -function formatContext(context: LogContext | undefined) { - if (!context) return ""; - const entries = Object.entries(context).filter(([, value]) => value !== undefined); - if (entries.length === 0) return ""; - return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" "); -} - -function write(level: LogLevel, scope: string, message: string, context?: LogContext) { - const colorEnabled = useColors(); - const ts = colorize(timeStamp(), ANSI.dim, colorEnabled); - const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled); - const contextText = formatContext(context); - const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`; - - if (level === "warn") { - console.warn(line); - return; - } - if (level === "error") { - console.error(line); - return; - } - console.log(line); -} - -export function createLogger(scope: string) { - return { - info(message: string, context?: LogContext) { - write("info", scope, message, context); - }, - warn(message: string, context?: LogContext) { - write("warn", scope, message, context); - }, - error(message: string, context?: LogContext) { - write("error", scope, message, context); - }, - event(message: string, context?: LogContext) { - write("event", scope, message, context); - }, - }; -} diff --git a/apps/server/src/main.test.ts b/apps/server/src/main.test.ts deleted file mode 100644 index 0d990a81c8..0000000000 --- a/apps/server/src/main.test.ts +++ /dev/null @@ -1,413 +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 FileSystem from "effect/FileSystem"; -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"; -import { ServerSettingsService } from "./serverSettings"; - -const start = vi.fn(() => undefined); -const stop = vi.fn(() => undefined); -const fixPath = 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.sync(fixPath), - 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), - ServerSettingsService.layerTest(), - AnalyticsService.layerTest, - FetchHttpClient.layer, - NodeServices.layer, -); - -const runCli = ( - args: ReadonlyArray, - env: Record = { T3CODE_NO_BROWSER: "true" }, -) => { - return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe( - Effect.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - ...env, - }, - }), - ), - ), - ); -}; - -beforeEach(() => { - vi.clearAllMocks(); - resolvedConfig = null; - start.mockImplementation(() => undefined); - stop.mockImplementation(() => undefined); - fixPath.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", - "--home-dir", - "/tmp/t3-cli-home", - "--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?.baseDir, "/tmp/t3-cli-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev"); - 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_HOME: "/tmp/t3-env-home", - 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?.baseDir, "/tmp/t3-env-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev"); - 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); - }), - ); - - const openBootstrapFd = Effect.fn(function* (payload: Record) { - const fs = yield* FileSystem.FileSystem; - const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); - yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`); - const { fd } = yield* fs.open(filePath, { flag: "r" }); - return fd; - }); - - it.effect("recognizes bootstrap fd from environment config", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" }); - - yield* runCli([], { - T3CODE_MODE: "web", - T3CODE_BOOTSTRAP_FD: String(fd), - T3CODE_AUTH_TOKEN: "env-token", - T3CODE_NO_BROWSER: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.authToken, "env-token"); - }), - ); - - it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ - mode: "desktop", - port: 4888, - host: "127.0.0.2", - t3Home: "/tmp/t3-bootstrap-home", - devUrl: "http://127.0.0.1:5173", - noBrowser: true, - authToken: "bootstrap-token", - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: true, - }); - - yield* runCli([], { - T3CODE_BOOTSTRAP_FD: String(fd), - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "desktop"); - assert.equal(resolvedConfig?.port, 4888); - assert.equal(resolvedConfig?.host, "127.0.0.2"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home"); - assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "bootstrap-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - }), - ); - - it.effect("applies CLI then env precedence over bootstrap envelope values", () => - Effect.gen(function* () { - const fd = yield* openBootstrapFd({ - mode: "desktop", - port: 4888, - host: "127.0.0.2", - t3Home: "/tmp/t3-bootstrap-home", - devUrl: "http://127.0.0.1:5173", - noBrowser: false, - authToken: "bootstrap-token", - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: false, - }); - - yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], { - T3CODE_MODE: "web", - T3CODE_BOOTSTRAP_FD: String(fd), - T3CODE_HOME: "/tmp/t3-env-home", - T3CODE_NO_BROWSER: "true", - T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true", - T3CODE_LOG_WS_EVENTS: "true", - }); - - assert.equal(start.mock.calls.length, 1); - assert.equal(resolvedConfig?.mode, "web"); - assert.equal(resolvedConfig?.port, 4999); - assert.equal(resolvedConfig?.host, "0.0.0.0"); - assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home"); - assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/"); - assert.equal(resolvedConfig?.noBrowser, true); - assert.equal(resolvedConfig?.authToken, "cli-token"); - assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true); - assert.equal(resolvedConfig?.logWebSocketEvents, true); - }), - ); - - 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("hydrates PATH before server startup", () => - Effect.gen(function* () { - yield* runCli([]); - - assert.equal(fixPath.mock.calls.length, 1); - assert.equal(start.mock.calls.length, 1); - const fixPathOrder = fixPath.mock.invocationCallOrder[0]; - const startOrder = start.mock.invocationCallOrder[0]; - if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") { - assert.fail("Expected fixPath and start to be called"); - } - assert.isTrue(fixPathOrder < startOrder); - }), - ); - - 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"]).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 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"]).pipe(Effect.catch(() => Effect.void)); - - // 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 019783c253..0000000000 --- a/apps/server/src/main.ts +++ /dev/null @@ -1,456 +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, - deriveServerPaths, - resolveStaticDir, - ServerConfig, - type RuntimeMode, - type ServerConfigShape, -} from "./config"; -import { fixPath, resolveBaseDir } 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 { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry"; -import { Server } from "./wsServer"; -import { ServerLoggerLive } from "./serverLogger"; -import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; -import { readBootstrapEnvelope } from "./bootstrap"; -import { ServerSettingsLive } from "./serverSettings"; - -export class StartupError extends Data.TaggedError("StartupError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} - -const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); - -const BootstrapEnvelopeSchema = Schema.Struct({ - mode: Schema.optional(Schema.String), - port: Schema.optional(PortSchema), - host: Schema.optional(Schema.String), - t3Home: Schema.optional(Schema.String), - devUrl: Schema.optional(Schema.URLFromString), - noBrowser: Schema.optional(Schema.Boolean), - authToken: Schema.optional(Schema.String), - autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), - logWebSocketEvents: Schema.optional(Schema.Boolean), -}); - -interface CliInput { - readonly mode: Option.Option; - readonly port: Option.Option; - readonly host: Option.Option; - readonly t3Home: Option.Option; - readonly devUrl: Option.Option; - readonly noBrowser: Option.Option; - readonly authToken: Option.Option; - readonly bootstrapFd: 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.map((value) => (value === "desktop" ? "desktop" : "web"))), - Config.map(Option.getOrUndefined), - ), - port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), - host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), - t3Home: Config.string("T3CODE_HOME").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), - ), - bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").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 resolveOptionPrecedence = ( - ...values: ReadonlyArray> -): Option.Option => Option.firstSomeOf(values); - -const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535; -const isRuntimeMode = (value: string): value is RuntimeMode => - value === "web" || value === "desktop"; - -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 bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd; - const bootstrapEnvelope = - bootstrapFd !== undefined - ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd) - : Option.none(); - - const mode: RuntimeMode = Option.getOrElse( - resolveOptionPrecedence( - input.mode, - Option.fromUndefinedOr(env.mode), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode), - ), - ), - () => "web", - ); - const port = yield* Option.match( - resolveOptionPrecedence( - input.port, - Option.fromUndefinedOr(env.port), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort), - ), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(DEFAULT_PORT); - } - return findAvailablePort(DEFAULT_PORT); - }, - }, - ); - - const devUrl = Option.getOrElse( - resolveOptionPrecedence( - input.devUrl, - Option.fromUndefinedOr(env.devUrl), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.devUrl), - ), - ), - () => undefined, - ); - const baseDir = yield* resolveBaseDir( - Option.getOrUndefined( - resolveOptionPrecedence( - input.t3Home, - Option.fromUndefinedOr(env.t3Home), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.t3Home), - ), - ), - ), - ); - const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); - const noBrowser = resolveBooleanFlag( - input.noBrowser, - Option.getOrElse( - resolveOptionPrecedence( - Option.fromUndefinedOr(env.noBrowser), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.noBrowser), - ), - ), - () => mode === "desktop", - ), - ); - const authToken = resolveOptionPrecedence( - input.authToken, - Option.fromUndefinedOr(env.authToken), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.authToken), - ), - ); - const autoBootstrapProjectFromCwd = resolveBooleanFlag( - input.autoBootstrapProjectFromCwd, - Option.getOrElse( - resolveOptionPrecedence( - Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd), - ), - ), - () => mode === "web", - ), - ); - const logWebSocketEvents = resolveBooleanFlag( - input.logWebSocketEvents, - Option.getOrElse( - resolveOptionPrecedence( - Option.fromUndefinedOr(env.logWebSocketEvents), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.logWebSocketEvents), - ), - ), - () => Boolean(devUrl), - ), - ); - const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir; - const host = Option.getOrElse( - resolveOptionPrecedence( - input.host, - Option.fromUndefinedOr(env.host), - Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)), - ), - () => (mode === "desktop" ? "127.0.0.1" : undefined), - ); - - const config: ServerConfigShape = { - mode, - port, - cwd: cliConfig.cwd, - host, - baseDir, - ...derivedPaths, - staticDir, - devUrl, - noBrowser, - authToken: Option.getOrUndefined(authToken), - autoBootstrapProjectFromCwd, - logWebSocketEvents, - } satisfies ServerConfigShape; - - return config; - }), - ); - -const LayerLive = (input: CliInput) => - Layer.empty.pipe( - Layer.provideMerge(makeServerRuntimeServicesLayer()), - Layer.provideMerge(makeServerProviderLayer()), - Layer.provideMerge(ProviderRegistryLive), - Layer.provideMerge(SqlitePersistence.layerConfig), - Layer.provideMerge(ServerLoggerLive), - Layer.provideMerge(AnalyticsServiceLayerLive), - Layer.provideMerge(ServerSettingsLive), - 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 makeServerRuntimeProgram = (input: CliInput) => - Effect.gen(function* () { - const { start, stopSignal } = yield* Server; - const openDeps = yield* Open; - - 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))); - -const makeServerProgram = (input: CliInput) => - Effect.gen(function* () { - const cliConfig = yield* CliConfig; - yield* cliConfig.fixPath; - return yield* makeServerRuntimeProgram(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(PortSchema), - 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 t3HomeFlag = Flag.string("home-dir").pipe( - Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."), - 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 bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe( - Flag.withSchema(Schema.Int), - Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."), - 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, - t3Home: t3HomeFlag, - devUrl: devUrlFlag, - noBrowser: noBrowserFlag, - authToken: authTokenFlag, - bootstrapFd: bootstrapFdFlag, - 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/open.ts b/apps/server/src/open.ts index 3fbfd1653d..212db36c01 100644 --- a/apps/server/src/open.ts +++ b/apps/server/src/open.ts @@ -10,17 +10,14 @@ import { spawn } from "node:child_process"; import { accessSync, constants, statSync } from "node:fs"; import { extname, join } from "node:path"; -import { EDITORS, type EditorId } from "@t3tools/contracts"; -import { ServiceMap, Schema, Effect, Layer } from "effect"; +import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts"; +import { ServiceMap, Effect, Layer } from "effect"; // ============================== // Definitions // ============================== -export class OpenError extends Schema.TaggedErrorClass()("OpenError", { - message: Schema.String, - cause: Schema.optional(Schema.Defect), -}) {} +export { OpenError }; export interface OpenInEditorInput { readonly cwd: string; diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 075f62f889..781a0025e2 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -38,6 +38,8 @@ import { } from "../../provider/Services/ProviderService.ts"; import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts"; import { ServerConfig } from "../../config.ts"; +import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts"; const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); @@ -114,7 +116,7 @@ async function waitForThread( checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>; activities: ReadonlyArray<{ kind: string }>; }) => boolean, - timeoutMs = 5000, + timeoutMs = 15_000, ) { const deadline = Date.now() + timeoutMs; const poll = async (): Promise<{ @@ -139,7 +141,7 @@ async function waitForThread( async function waitForEvent( engine: OrchestrationEngineShape, predicate: (event: { type: string }) => boolean, - timeoutMs = 5000, + timeoutMs = 15_000, ) { const deadline = Date.now() + timeoutMs; const poll = async () => { @@ -190,7 +192,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string { return runGit(cwd, ["show", `${ref}:${filePath}`]); } -async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) { +async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) { const deadline = Date.now() + timeoutMs; const poll = async (): Promise => { if (gitRefExists(cwd, ref)) { @@ -261,7 +263,10 @@ describe("CheckpointReactor", () => { Layer.provideMerge(orchestrationLayer), Layer.provideMerge(RuntimeReceiptBusLive), Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), - Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))), + Layer.provideMerge(CheckpointStoreLive), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), ); @@ -1004,18 +1009,7 @@ describe("CheckpointReactor", () => { }), ); - const deadline = Date.now() + 2000; - const waitForRollbackCalls = async (): Promise => { - if (harness.provider.rollbackConversation.mock.calls.length >= 2) { - return; - } - if (Date.now() >= deadline) { - throw new Error("Timed out waiting for rollbackConversation calls."); - } - await new Promise((resolve) => setTimeout(resolve, 10)); - return waitForRollbackCalls(); - }; - await waitForRollbackCalls(); + await harness.drain(); expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2); expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({ diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 561626b8de..28609cecb3 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -16,7 +16,6 @@ import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd, } from "../../checkpointing/Utils.ts"; -import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts"; import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts"; @@ -25,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; import { CheckpointStoreError } from "../../checkpointing/Errors.ts"; import { OrchestrationDispatchError } from "../Errors.ts"; import { isGitRepository } from "../../git/Utils.ts"; +import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts"; type ReactorInput = | { @@ -68,6 +68,7 @@ const make = Effect.gen(function* () { const providerService = yield* ProviderService; const checkpointStore = yield* CheckpointStore; const receiptBus = yield* RuntimeReceiptBus; + const workspaceEntries = yield* WorkspaceEntries; const appendRevertFailureActivity = (input: { readonly threadId: ThreadId; @@ -226,7 +227,7 @@ const make = Effect.gen(function* () { // Invalidate the workspace entry cache so the @-mention file picker // reflects files created or deleted during this turn. - clearWorkspaceIndexCache(input.cwd); + yield* workspaceEntries.invalidate(input.cwd); const files = yield* checkpointStore .diffCheckpoints({ @@ -642,7 +643,7 @@ const make = Effect.gen(function* () { // Invalidate the workspace entry cache so the @-mention file picker // reflects the reverted filesystem state. - clearWorkspaceIndexCache(sessionRuntime.value.cwd); + yield* workspaceEntries.invalidate(sessionRuntime.value.cwd); const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount); if (rolledBackTurns > 0) { diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index 69b28b9d3c..5c52379f47 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -205,7 +205,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope))); yield* Effect.forkScoped(worker); - yield* Effect.log("orchestration engine started").pipe( + yield* Effect.logDebug("orchestration engine started").pipe( Effect.annotateLogs({ sequence: readModel.snapshotSequence }), ); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index f0f2ccabee..61de04ad0e 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -3,7 +3,6 @@ import { type ChatAttachment, type OrchestrationEvent, } from "@t3tools/contracts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; @@ -1271,7 +1270,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti Effect.provideService(ServerConfig, serverConfig), Effect.asVoid, Effect.tap(() => - Effect.log("orchestration projection pipeline bootstrapped").pipe( + Effect.logDebug("orchestration projection pipeline bootstrapped").pipe( Effect.annotateLogs({ projectors: projectors.length }), ), ), @@ -1291,7 +1290,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect( OrchestrationProjectionPipeline, makeOrchestrationProjectionPipeline(), ).pipe( - Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ProjectionProjectRepositoryLive), Layer.provideMerge(ProjectionThreadRepositoryLive), Layer.provideMerge(ProjectionThreadMessageRepositoryLive), diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ed7037695f..506d6d2864 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -17,7 +17,7 @@ import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effe import { afterEach, describe, expect, it, vi } from "vitest"; import { deriveServerPaths, ServerConfig } from "../../config.ts"; -import { TextGenerationError } from "../../git/Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { ProviderAdapterRequestError } from "../../provider/Errors.ts"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts new file mode 100644 index 0000000000..69863b7f0a --- /dev/null +++ b/apps/server/src/orchestration/Normalizer.ts @@ -0,0 +1,121 @@ +import { Effect, FileSystem, Path } from "effect"; +import { + type ClientOrchestrationCommand, + type OrchestrationCommand, + OrchestrationDispatchCommandError, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; + +import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore"; +import { ServerConfig } from "../config"; +import { parseBase64DataUrl } from "../imageMime"; +import { WorkspacePaths } from "../workspace/Services/WorkspacePaths"; + +export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const workspacePaths = yield* WorkspacePaths; + + const normalizeProjectWorkspaceRoot = (workspaceRoot: string) => + workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe( + Effect.mapError( + (cause) => + new OrchestrationDispatchCommandError({ + message: cause.message, + }), + ), + ); + + if (command.type === "project.create") { + return { + ...command, + workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot), + } satisfies OrchestrationCommand; + } + + if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) { + return { + ...command, + workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot), + } satisfies OrchestrationCommand; + } + + if (command.type !== "thread.turn.start") { + return command as OrchestrationCommand; + } + + const normalizedAttachments = yield* Effect.forEach( + command.message.attachments, + (attachment) => + Effect.gen(function* () { + const parsed = parseBase64DataUrl(attachment.dataUrl); + if (!parsed || !parsed.mimeType.startsWith("image/")) { + return yield* new OrchestrationDispatchCommandError({ + 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 OrchestrationDispatchCommandError({ + message: `Image attachment '${attachment.name}' is empty or too large.`, + }); + } + + const attachmentId = createAttachmentId(command.threadId); + if (!attachmentId) { + return yield* new OrchestrationDispatchCommandError({ + 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({ + attachmentsDir: serverConfig.attachmentsDir, + attachment: persistedAttachment, + }); + if (!attachmentPath) { + return yield* new OrchestrationDispatchCommandError({ + message: `Failed to resolve persisted path for '${attachment.name}'.`, + }); + } + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe( + Effect.mapError( + () => + new OrchestrationDispatchCommandError({ + message: `Failed to create attachment directory for '${attachment.name}'.`, + }), + ), + ); + yield* fileSystem.writeFile(attachmentPath, bytes).pipe( + Effect.mapError( + () => + new OrchestrationDispatchCommandError({ + message: `Failed to persist attachment '${attachment.name}'.`, + }), + ), + ); + + return persistedAttachment; + }), + { concurrency: 1 }, + ); + + return { + ...command, + message: { + ...command.message, + attachments: normalizedAttachments, + }, + } satisfies OrchestrationCommand; + }); diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts new file mode 100644 index 0000000000..29b30739b9 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts @@ -0,0 +1,74 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts"; +import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectFaviconResolverLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-favicon-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => { + describe("resolvePath", () => { + it.effect("prefers well-known favicon files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "favicon.svg", "favicon"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("favicon.svg"); + }), + ); + + it.effect("resolves icon hrefs from project source files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("public/brand/logo.svg"); + }), + ); + + it.effect("returns null when no icon is present", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..3004a7a45c --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.ts @@ -0,0 +1,129 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + ProjectFaviconResolver, + type ProjectFaviconResolverShape, +} from "../Services/ProjectFaviconResolver.ts"; + +// Well-known favicon paths checked in order. +const FAVICON_CANDIDATES = [ + "favicon.svg", + "favicon.ico", + "favicon.png", + "public/favicon.svg", + "public/favicon.ico", + "public/favicon.png", + "app/favicon.ico", + "app/favicon.png", + "app/icon.svg", + "app/icon.png", + "app/icon.ico", + "src/favicon.ico", + "src/favicon.svg", + "src/app/favicon.ico", + "src/app/icon.svg", + "src/app/icon.png", + "assets/icon.svg", + "assets/icon.png", + "assets/logo.svg", + "assets/logo.png", +] as const; + +// Files that may contain a or icon metadata declaration. +const ICON_SOURCE_FILES = [ + "index.html", + "public/index.html", + "app/routes/__root.tsx", + "src/routes/__root.tsx", + "app/root.tsx", + "src/root.tsx", + "src/index.html", +] as const; + +// Matches tags or object-like icon metadata where rel/href can appear in any order. +const LINK_ICON_HTML_RE = + /]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; +const LINK_ICON_OBJ_RE = + /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i; + +function extractIconHref(source: string): string | null { + const htmlMatch = source.match(LINK_ICON_HTML_RE); + if (htmlMatch?.[1]) return htmlMatch[1]; + const objMatch = source.match(LINK_ICON_OBJ_RE); + if (objMatch?.[1]) return objMatch[1]; + return null; +} + +export const makeProjectFaviconResolver = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const resolveIconHref = (projectCwd: string, href: string): string[] => { + const clean = href.replace(/^\//, ""); + return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; + }; + + const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => { + const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath)); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); + }; + + const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* ( + projectCwd: string, + candidates: ReadonlyArray, + ): Effect.fn.Return { + for (const candidate of candidates) { + if (!isPathWithinProject(projectCwd, candidate)) { + continue; + } + const stats = yield* fileSystem + .stat(candidate) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (stats?.type === "File") { + return candidate; + } + } + return null; + }); + + const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn( + "ProjectFaviconResolver.resolvePath", + )(function* (cwd: string): Effect.fn.Return { + for (const candidate of FAVICON_CANDIDATES) { + const resolved = path.join(cwd, candidate); + const existing = yield* findExistingFile(cwd, [resolved]); + if (existing) { + return existing; + } + } + + for (const sourceFile of ICON_SOURCE_FILES) { + const sourcePath = path.join(cwd, sourceFile); + const source = yield* fileSystem + .readFileString(sourcePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!source) { + continue; + } + const href = extractIconHref(source); + if (!href) { + continue; + } + const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href)); + if (existing) { + return existing; + } + } + + return null; + }); + + return { + resolvePath, + } satisfies ProjectFaviconResolverShape; +}); + +export const ProjectFaviconResolverLive = Layer.effect( + ProjectFaviconResolver, + makeProjectFaviconResolver, +); diff --git a/apps/server/src/project/Services/ProjectFaviconResolver.ts b/apps/server/src/project/Services/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..f6a8e22c0d --- /dev/null +++ b/apps/server/src/project/Services/ProjectFaviconResolver.ts @@ -0,0 +1,30 @@ +/** + * ProjectFaviconResolver - Effect service contract for project icon discovery. + * + * Resolves a representative favicon or app icon file for a workspace by + * checking common file locations and project source metadata. + * + * @module ProjectFaviconResolver + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +/** + * ProjectFaviconResolverShape - Service API for project favicon lookup. + */ +export interface ProjectFaviconResolverShape { + /** + * Resolve a favicon or icon file path for the provided workspace root. + * + * Returns `null` when no candidate icon file can be found. + */ + readonly resolvePath: (cwd: string) => Effect.Effect; +} + +/** + * ProjectFaviconResolver - Service tag for project favicon resolution. + */ +export class ProjectFaviconResolver extends ServiceMap.Service< + ProjectFaviconResolver, + ProjectFaviconResolverShape +>()("t3/project/Services/ProjectFaviconResolver") {} diff --git a/apps/server/src/projectFaviconRoute.test.ts b/apps/server/src/projectFaviconRoute.test.ts deleted file mode 100644 index a346e513eb..0000000000 --- a/apps/server/src/projectFaviconRoute.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import fs from "node:fs"; -import http from "node:http"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, describe, expect, it } from "vitest"; -import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; - -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"); - }); - - await new Promise((resolve, reject) => { - server.listen(0, "127.0.0.1", (error?: Error) => { - if (error) { - reject(error); - return; - } - resolve(); - }); - }); - - 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(); - }); - }); - } -} - -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(), - }; -} - -describe("tryHandleProjectFaviconRequest", () => { - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); - - 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("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"); - - 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("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"); - - 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("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"); - - 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"'); - }); - }); -}); diff --git a/apps/server/src/projectFaviconRoute.ts b/apps/server/src/projectFaviconRoute.ts deleted file mode 100644 index cf234ad894..0000000000 --- a/apps/server/src/projectFaviconRoute.ts +++ /dev/null @@ -1,171 +0,0 @@ -import fs from "node:fs"; -import http from "node:http"; -import path from "node:path"; - -const FAVICON_MIME_TYPES: Record = { - ".png": "image/png", - ".jpg": "image/jpeg", - ".svg": "image/svg+xml", - ".ico": "image/x-icon", -}; - -const FALLBACK_FAVICON_SVG = ``; - -// Well-known favicon paths checked in order. -const FAVICON_CANDIDATES = [ - "favicon.svg", - "favicon.ico", - "favicon.png", - "public/favicon.svg", - "public/favicon.ico", - "public/favicon.png", - "app/favicon.ico", - "app/favicon.png", - "app/icon.svg", - "app/icon.png", - "app/icon.ico", - "src/favicon.ico", - "src/favicon.svg", - "src/app/favicon.ico", - "src/app/icon.svg", - "src/app/icon.png", - "assets/icon.svg", - "assets/icon.png", - "assets/logo.svg", - "assets/logo.png", -]; - -// Files that may contain a or icon metadata declaration. -const ICON_SOURCE_FILES = [ - "index.html", - "public/index.html", - "app/routes/__root.tsx", - "src/routes/__root.tsx", - "app/root.tsx", - "src/root.tsx", - "src/index.html", -]; - -// Matches tags or object-like icon metadata where rel/href can appear in any order. -const LINK_ICON_HTML_RE = - /]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; -const LINK_ICON_OBJ_RE = - /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i; - -function extractIconHref(source: string): string | null { - const htmlMatch = source.match(LINK_ICON_HTML_RE); - if (htmlMatch?.[1]) return htmlMatch[1]; - const objMatch = source.match(LINK_ICON_OBJ_RE); - if (objMatch?.[1]) return objMatch[1]; - return null; -} - -function resolveIconHref(projectCwd: string, href: string): string[] { - const clean = href.replace(/^\//, ""); - return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; -} - -function isPathWithinProject(projectCwd: string, candidatePath: string): boolean { - 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 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; - } - res.writeHead(200, { - "Content-Type": contentType, - "Cache-Control": "public, max-age=3600", - }); - res.end(data); - }); -} - -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 function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean { - if (url.pathname !== "/api/project-favicon") { - return false; - } - - const projectCwd = url.searchParams.get("cwd"); - if (!projectCwd) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end("Missing cwd parameter"); - return true; - } - - 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 trySourceFiles = (index: number): void => { - if (index >= ICON_SOURCE_FILES.length) { - serveFallbackFavicon(res); - return; - } - 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 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; -} diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index d064a8239f..5a09d8b6ba 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -208,6 +208,9 @@ async function readFirstPromptText( if (next.done) { return undefined; } + if (typeof next.value.message.content === "string") { + return next.value.message.content; + } const content = next.value.message.content[0]; if (!content || content.type !== "text") { return undefined; diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 6b50bd4fbb..d99e2ad203 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -533,7 +533,7 @@ function buildUserMessage(input: { parent_tool_use_id: null, message: { role: "user", - content: input.sdkContent, + content: input.sdkContent as unknown as SDKUserMessage["message"]["content"], }, } as SDKUserMessage; } diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index f2243ef1b0..158a9ef25a 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -24,7 +24,8 @@ import { } from "../providerSnapshot"; import { makeManagedServerProvider } from "../makeManagedServerProvider"; import { ClaudeProvider } from "../Services/ClaudeProvider"; -import { ServerSettingsError, ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; const PROVIDER = "claudeAgent" as const; const BUILT_IN_MODELS: ReadonlyArray = [ diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 7ddbdbfc98..b5eb873e85 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -508,6 +508,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); + it.effect("maps fatal websocket stderr notifications to runtime.error", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-process-stderr-websocket"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.error"); + if (firstEvent.value.type !== "runtime.error") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.class, "provider_error"); + assert.equal( + firstEvent.value.payload.message, + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + ); + }), + ); + it.effect("preserves request type when mapping serverRequest/resolved", () => Effect.gen(function* () { const adapter = yield* CodexAdapter; diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index b9ac4bfc4a..cee6bca6ed 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -112,6 +112,13 @@ function asNumber(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } +const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"]; + +function isFatalCodexProcessStderrMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet)); +} + function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined { const usage = asObject(value); const totalUsage = asObject(usage?.total_token_usage ?? usage?.total); @@ -1269,15 +1276,27 @@ function mapToRuntimeEvents( } if (event.method === "process/stderr") { + const message = event.message ?? "Codex process stderr"; + const isFatal = isFatalCodexProcessStderrMessage(message); return [ - { - type: "runtime.warning", - ...runtimeEventBase(event, canonicalThreadId), - payload: { - message: event.message ?? "Codex process stderr", - ...(event.payload !== undefined ? { detail: event.payload } : {}), - }, - }, + isFatal + ? { + type: "runtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + class: "provider_error" as const, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + } + : { + type: "runtime.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, ]; } diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 1fe98ea798..499d4c6ffd 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -46,7 +46,8 @@ import { } from "../codexAccount"; import { probeCodexAccount } from "../codexAppServer"; import { CodexProvider } from "../Services/CodexProvider"; -import { ServerSettingsError, ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsService } from "../../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; const PROVIDER = "codex" as const; const OPENAI_AUTH_PROVIDERS = new Set(["openai"]); diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index e519e82af5..4c1d0878fc 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -3,7 +3,7 @@ import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect"; import * as Semaphore from "effect/Semaphore"; import type { ServerProviderShape } from "./Services/ServerProvider"; -import { ServerSettingsError } from "../serverSettings"; +import { ServerSettingsError } from "@t3tools/contracts"; export function makeManagedServerProvider(input: { readonly getSettings: Effect.Effect; diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts new file mode 100644 index 0000000000..0e53eae43e --- /dev/null +++ b/apps/server/src/server.test.ts @@ -0,0 +1,1391 @@ +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CommandId, + DEFAULT_SERVER_SETTINGS, + GitCommandError, + KeybindingRule, + OpenError, + TerminalNotRunningError, + type OrchestrationEvent, + ORCHESTRATION_WS_METHODS, + ProjectId, + ResolvedKeybindingRule, + ThreadId, + WS_METHODS, + WsRpcGroup, + EditorId, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; +import { Effect, FileSystem, Layer, Path, Stream } from "effect"; +import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; +import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; + +import type { ServerConfigShape } from "./config.ts"; +import { deriveServerPaths, ServerConfig } from "./config.ts"; +import { makeRoutesLayer } from "./server.ts"; +import { resolveAttachmentRelativePath } from "./attachmentPaths.ts"; +import { + CheckpointDiffQuery, + type CheckpointDiffQueryShape, +} from "./checkpointing/Services/CheckpointDiffQuery.ts"; +import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts"; +import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; +import { Keybindings, type KeybindingsShape } from "./keybindings.ts"; +import { Open, type OpenShape } from "./open.ts"; +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "./orchestration/Services/OrchestrationEngine.ts"; +import { + ProjectionSnapshotQuery, + type ProjectionSnapshotQueryShape, +} from "./orchestration/Services/ProjectionSnapshotQuery.ts"; +import { PersistenceSqlError } from "./persistence/Errors.ts"; +import { + ProviderRegistry, + type ProviderRegistryShape, +} from "./provider/Services/ProviderRegistry.ts"; +import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts"; +import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts"; +import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts"; +import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; + +const defaultProjectId = ProjectId.makeUnsafe("project-default"); +const defaultThreadId = ThreadId.makeUnsafe("thread-default"); +const defaultModelSelection = { + provider: "codex", + model: "gpt-5-codex", +} as const; + +const makeDefaultOrchestrationReadModel = () => { + const now = new Date().toISOString(); + return { + snapshotSequence: 0, + updatedAt: now, + projects: [ + { + id: defaultProjectId, + title: "Default Project", + workspaceRoot: "/tmp/default-project", + defaultModelSelection, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: defaultThreadId, + projectId: defaultProjectId, + title: "Default Thread", + modelSelection: defaultModelSelection, + interactionMode: "default" as const, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + ], + }; +}; + +const workspaceAndProjectServicesLayer = Layer.mergeAll( + WorkspacePathsLive, + WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), + WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + ), + ProjectFaviconResolverLive, +); + +const buildAppUnderTest = (options?: { + config?: Partial; + layers?: { + keybindings?: Partial; + providerRegistry?: Partial; + serverSettings?: Partial; + open?: Partial; + gitCore?: Partial; + gitManager?: Partial; + terminalManager?: Partial; + orchestrationEngine?: Partial; + projectionSnapshotQuery?: Partial; + checkpointDiffQuery?: Partial; + serverLifecycleEvents?: Partial; + serverRuntimeStartup?: Partial; + }; +}) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const tempBaseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-test-" }); + const baseDir = options?.config?.baseDir ?? tempBaseDir; + const devUrl = options?.config?.devUrl; + const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); + const config = { + logLevel: "Info", + mode: "web", + port: 0, + host: "127.0.0.1", + cwd: process.cwd(), + baseDir, + ...derivedPaths, + staticDir: undefined, + devUrl, + noBrowser: true, + authToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + ...options?.config, + } satisfies ServerConfigShape; + const layerConfig = Layer.succeed(ServerConfig, config); + + const appLayer = HttpRouter.serve(makeRoutesLayer, { + disableListenLog: true, + disableLogger: true, + }).pipe( + Layer.provide( + Layer.mock(Keybindings)({ + streamChanges: Stream.empty, + ...options?.layers?.keybindings, + }), + ), + Layer.provide( + Layer.mock(ProviderRegistry)({ + getProviders: Effect.succeed([]), + refresh: () => Effect.succeed([]), + streamChanges: Stream.empty, + ...options?.layers?.providerRegistry, + }), + ), + Layer.provide( + Layer.mock(ServerSettingsService)({ + start: Effect.void, + ready: Effect.void, + getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), + updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS), + streamChanges: Stream.empty, + ...options?.layers?.serverSettings, + }), + ), + Layer.provide( + Layer.mock(Open)({ + ...options?.layers?.open, + }), + ), + Layer.provide( + Layer.mock(GitCore)({ + ...options?.layers?.gitCore, + }), + ), + Layer.provide( + Layer.mock(GitManager)({ + ...options?.layers?.gitManager, + }), + ), + Layer.provide( + Layer.mock(TerminalManager)({ + ...options?.layers?.terminalManager, + }), + ), + Layer.provide( + Layer.mock(OrchestrationEngineService)({ + getReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()), + readEvents: () => Stream.empty, + dispatch: () => Effect.succeed({ sequence: 0 }), + streamDomainEvents: Stream.empty, + ...options?.layers?.orchestrationEngine, + }), + ), + Layer.provide( + Layer.mock(ProjectionSnapshotQuery)({ + getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()), + ...options?.layers?.projectionSnapshotQuery, + }), + ), + Layer.provide( + Layer.mock(CheckpointDiffQuery)({ + getTurnDiff: () => + Effect.succeed({ + threadId: defaultThreadId, + fromTurnCount: 0, + toTurnCount: 0, + diff: "", + }), + getFullThreadDiff: () => + Effect.succeed({ + threadId: defaultThreadId, + fromTurnCount: 0, + toTurnCount: 0, + diff: "", + }), + ...options?.layers?.checkpointDiffQuery, + }), + ), + Layer.provide( + Layer.mock(ServerLifecycleEvents)({ + publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }), + snapshot: Effect.succeed({ sequence: 0, events: [] }), + stream: Stream.empty, + ...options?.layers?.serverLifecycleEvents, + }), + ), + Layer.provide( + Layer.mock(ServerRuntimeStartup)({ + awaitCommandReady: Effect.void, + markHttpListening: Effect.void, + enqueueCommand: (effect) => effect, + ...options?.layers?.serverRuntimeStartup, + }), + ), + Layer.provide(workspaceAndProjectServicesLayer), + Layer.provide(layerConfig), + ); + + yield* Layer.build(appLayer); + return config; + }); + +const wsRpcProtocolLayer = (wsUrl: string) => + RpcClient.layerProtocolSocket().pipe( + Layer.provide(NodeSocket.layerWebSocket(wsUrl)), + Layer.provide(RpcSerialization.layerJson), + ); + +const makeWsRpcClient = RpcClient.make(WsRpcGroup); +type WsRpcClient = + typeof makeWsRpcClient extends Effect.Effect ? Client : never; + +const withWsRpcClient = ( + wsUrl: string, + f: (client: WsRpcClient) => Effect.Effect, +) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); + +const getHttpServerUrl = (pathname = "") => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + return `http://127.0.0.1:${address.port}${pathname}`; + }); + +const getWsServerUrl = (pathname = "") => + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + const address = server.address as HttpServer.TcpAddress; + return `ws://127.0.0.1:${address.port}${pathname}`; + }); + +it.layer(NodeServices.layer)("server router seam", (it) => { + it.effect("serves static index content for GET / when staticDir is configured", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-static-" }); + const indexPath = path.join(staticDir, "index.html"); + yield* fileSystem.writeFileString(indexPath, "router-static-ok"); + + yield* buildAppUnderTest({ config: { staticDir } }); + + const response = yield* HttpClient.get("/"); + assert.equal(response.status, 200); + assert.include(yield* response.text, "router-static-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("redirects to dev URL when configured", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const url = yield* getHttpServerUrl("/foo/bar"); + const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" })); + + assert.equal(response.status, 302); + assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves project favicon requests before the dev URL redirect", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-", + }); + yield* fileSystem.writeFileString( + path.join(projectDir, "favicon.svg"), + "router-project-favicon", + ); + + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + ); + + assert.equal(response.status, 200); + assert.equal(yield* response.text, "router-project-favicon"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves the fallback project favicon when no icon exists", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-fallback-", + }); + + yield* buildAppUnderTest({ + config: { devUrl: new URL("http://127.0.0.1:5173") }, + }); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + ); + + assert.equal(response.status, 200); + assert.include(yield* response.text, 'data-fallback="project-favicon"'); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves attachment files from state dir", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const attachmentId = "thread-11111111-1111-4111-8111-111111111111"; + + const config = yield* buildAppUnderTest(); + const attachmentPath = resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: `${attachmentId}.bin`, + }); + assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); + yield* fileSystem.writeFileString(attachmentPath, "attachment-ok"); + + const response = yield* HttpClient.get(`/attachments/${attachmentId}`); + assert.equal(response.status, 200); + assert.equal(yield* response.text, "attachment-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("serves attachment files for URL-encoded paths", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const config = yield* buildAppUnderTest(); + const attachmentPath = resolveAttachmentRelativePath({ + attachmentsDir: config.attachmentsDir, + relativePath: "thread%20folder/message%20folder/file%20name.png", + }); + assert.isNotNull(attachmentPath, "Attachment path should be resolvable"); + + yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); + yield* fileSystem.writeFileString(attachmentPath, "attachment-encoded-ok"); + + const response = yield* HttpClient.get( + "/attachments/thread%20folder/message%20folder/file%20name.png", + ); + assert.equal(response.status, 200); + assert.equal(yield* response.text, "attachment-encoded-ok"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("returns 404 for missing attachment id lookups", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.get( + "/attachments/missing-11111111-1111-4111-8111-111111111111", + ); + assert.equal(response.status, 404); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc server.upsertKeybinding", () => + Effect.gen(function* () { + const rule: KeybindingRule = { + command: "terminal.toggle", + key: "ctrl+k", + }; + const resolved: ResolvedKeybindingRule = { + command: "terminal.toggle", + shortcut: { + key: "k", + metaKey: false, + ctrlKey: true, + shiftKey: false, + altKey: false, + modKey: true, + }, + }; + + yield* buildAppUnderTest({ + layers: { + keybindings: { + upsertKeybindingRule: () => Effect.succeed([resolved]), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverUpsertKeybinding](rule)), + ); + + assert.deepEqual(response.issues, []); + assert.deepEqual(response.keybindings, [resolved]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects websocket rpc handshake when auth token is missing", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-required-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest({ + config: { + authToken: "secret-token", + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertInclude(String(result.failure), "SocketOpenError"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("accepts websocket rpc handshake when auth token is provided", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest({ + config: { + authToken: "secret-token", + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws?token=secret-token"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ), + ); + + assert.isAtLeast(response.entries.length, 1); + assert.equal(response.truncated, false); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => + Effect.gen(function* () { + const providers = [] as const; + const changeEvent = { + keybindings: [], + issues: [], + } as const; + + yield* buildAppUnderTest({ + layers: { + keybindings: { + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), + streamChanges: Stream.succeed(changeEvent), + }, + providerRegistry: { + getProviders: Effect.succeed(providers), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "snapshot"); + if (first?.type === "snapshot") { + assert.equal(first.version, 1); + assert.deepEqual(first.config.keybindings, []); + assert.deepEqual(first.config.issues, []); + assert.deepEqual(first.config.providers, providers); + assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS); + } + assert.deepEqual(second, { + version: 1, + type: "keybindingsUpdated", + payload: { issues: [] }, + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () => + Effect.gen(function* () { + const providers = [] as const; + + yield* buildAppUnderTest({ + layers: { + keybindings: { + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), + streamChanges: Stream.empty, + }, + providerRegistry: { + getProviders: Effect.succeed([]), + streamChanges: Stream.succeed(providers), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "snapshot"); + assert.deepEqual(second, { + version: 1, + type: "providerStatuses", + payload: { providers }, + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates", + () => + Effect.gen(function* () { + const lifecycleEvents = [ + { + version: 1 as const, + sequence: 1, + type: "welcome" as const, + payload: { + cwd: "/tmp/project", + projectName: "project", + }, + }, + ] as const; + const liveEvents = Stream.make({ + version: 1 as const, + sequence: 2, + type: "ready" as const, + payload: { at: new Date().toISOString() }, + }); + + yield* buildAppUnderTest({ + layers: { + serverLifecycleEvents: { + snapshot: Effect.succeed({ + sequence: 1, + events: lifecycleEvents, + }), + stream: liveEvents, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect), + ), + ); + + const [first, second] = Array.from(events); + assert.equal(first?.type, "welcome"); + assert.equal(first?.sequence, 1); + assert.equal(second?.type, "ready"); + assert.equal(second?.sequence, 2); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.searchEntries", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-search-" }); + yield* fs.writeFileString( + path.join(workspaceDir, "needle-file.ts"), + "export const needle = 1;", + ); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: workspaceDir, + query: "needle", + limit: 10, + }), + ), + ); + + assert.isAtLeast(response.entries.length, 1); + assert.isTrue(response.entries.some((entry) => entry.path === "needle-file.ts")); + assert.equal(response.truncated, false); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.searchEntries errors", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsSearchEntries]({ + cwd: "/definitely/not/a/real/workspace/path", + query: "needle", + limit: 10, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "ProjectSearchEntriesError"); + assertInclude( + result.failure.message, + "Workspace root does not exist: /definitely/not/a/real/workspace/path", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.writeFile", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsWriteFile]({ + cwd: workspaceDir, + relativePath: "nested/created.txt", + contents: "written-by-rpc", + }), + ), + ); + + assert.equal(response.relativePath, "nested/created.txt"); + const persisted = yield* fs.readFileString(path.join(workspaceDir, "nested", "created.txt")); + assert.equal(persisted, "written-by-rpc"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc projects.writeFile errors", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); + + yield* buildAppUnderTest(); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.projectsWriteFile]({ + cwd: workspaceDir, + relativePath: "../escape.txt", + contents: "nope", + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "ProjectWriteFileError"); + assert.equal( + result.failure.message, + "Workspace file path must stay within the project root.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc shell.openInEditor", () => + Effect.gen(function* () { + let openedInput: { cwd: string; editor: EditorId } | null = null; + yield* buildAppUnderTest({ + layers: { + open: { + openInEditor: (input) => + Effect.sync(() => { + openedInput = input; + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.shellOpenInEditor]({ + cwd: "/tmp/project", + editor: "cursor", + }), + ), + ); + + assert.deepEqual(openedInput, { cwd: "/tmp/project", editor: "cursor" }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc shell.openInEditor errors", () => + Effect.gen(function* () { + const openError = new OpenError({ message: "Editor command not found: cursor" }); + yield* buildAppUnderTest({ + layers: { + open: { + openInEditor: () => Effect.fail(openError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.shellOpenInEditor]({ + cwd: "/tmp/project", + editor: "cursor", + }), + ).pipe(Effect.result), + ); + + assertFailure(result, openError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git methods", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + gitManager: { + status: () => + Effect.succeed({ + branch: "main", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + runStackedAction: (input, options) => + Effect.gen(function* () { + const result = { + action: "commit" as const, + branch: { status: "skipped_not_requested" as const }, + commit: { + status: "created" as const, + commitSha: "abc123", + subject: "feat: demo", + }, + push: { status: "skipped_not_requested" as const }, + pr: { status: "skipped_not_requested" as const }, + }; + + yield* ( + options?.progressReporter?.publish({ + actionId: options.actionId ?? input.actionId, + cwd: input.cwd, + action: input.action, + kind: "phase_started", + phase: "commit", + label: "Committing...", + }) ?? Effect.void + ); + + yield* ( + options?.progressReporter?.publish({ + actionId: options.actionId ?? input.actionId, + cwd: input.cwd, + action: input.action, + kind: "action_finished", + result, + }) ?? Effect.void + ); + + return result; + }), + resolvePullRequest: () => + Effect.succeed({ + pullRequest: { + number: 1, + title: "Demo PR", + url: "https://example.com/pr/1", + baseBranch: "main", + headBranch: "feature/demo", + state: "open", + }, + }), + preparePullRequestThread: () => + Effect.succeed({ + pullRequest: { + number: 1, + title: "Demo PR", + url: "https://example.com/pr/1", + baseBranch: "main", + headBranch: "feature/demo", + state: "open", + }, + branch: "feature/demo", + worktreePath: null, + }), + }, + gitCore: { + pullCurrentBranch: () => + Effect.succeed({ + status: "pulled", + branch: "main", + upstreamBranch: "origin/main", + }), + listBranches: () => + Effect.succeed({ + branches: [ + { + name: "main", + current: true, + isDefault: true, + worktreePath: null, + }, + ], + isRepo: true, + hasOriginRemote: true, + }), + createWorktree: () => + Effect.succeed({ + worktree: { path: "/tmp/wt", branch: "feature/demo" }, + }), + removeWorktree: () => Effect.void, + createBranch: () => Effect.void, + checkoutBranch: () => Effect.void, + initRepo: () => Effect.void, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + + const status = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitStatus]({ cwd: "/tmp/repo" })), + ); + assert.equal(status.branch, "main"); + + const pull = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })), + ); + assert.equal(pull.status, "pulled"); + + const stackedEvents = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/tmp/repo", + action: "commit", + }).pipe( + Stream.runCollect, + Effect.map((events) => Array.from(events)), + ), + ), + ); + const lastStackedEvent = stackedEvents.at(-1); + assert.equal(lastStackedEvent?.kind, "action_finished"); + if (lastStackedEvent?.kind === "action_finished") { + assert.equal(lastStackedEvent.result.action, "commit"); + } + + const resolvedPr = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitResolvePullRequest]({ + cwd: "/tmp/repo", + reference: "1", + }), + ), + ); + assert.equal(resolvedPr.pullRequest.number, 1); + + const prepared = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitPreparePullRequestThread]({ + cwd: "/tmp/repo", + reference: "1", + mode: "local", + }), + ), + ); + assert.equal(prepared.branch, "feature/demo"); + + const branches = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }), + ), + ); + assert.equal(branches.branches[0]?.name, "main"); + + const worktree = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCreateWorktree]({ + cwd: "/tmp/repo", + branch: "main", + path: null, + }), + ), + ); + assert.equal(worktree.worktree.branch, "feature/demo"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitRemoveWorktree]({ + cwd: "/tmp/repo", + path: "/tmp/wt", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCreateBranch]({ + cwd: "/tmp/repo", + branch: "feature/new", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitCheckout]({ + cwd: "/tmp/repo", + branch: "main", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.gitInit]({ + cwd: "/tmp/repo", + }), + ), + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc git.pull errors", () => + Effect.gen(function* () { + const gitError = new GitCommandError({ + operation: "pull", + command: "git pull --ff-only", + cwd: "/tmp/repo", + detail: "upstream missing", + }); + yield* buildAppUnderTest({ + layers: { + gitCore: { + pullCurrentBranch: () => Effect.fail(gitError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })).pipe( + Effect.result, + ), + ); + + assertFailure(result, gitError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc orchestration methods", () => + Effect.gen(function* () { + const now = new Date().toISOString(); + const snapshot = { + snapshotSequence: 1, + updatedAt: now, + projects: [ + { + id: ProjectId.makeUnsafe("project-a"), + title: "Project A", + workspaceRoot: "/tmp/project-a", + defaultModelSelection, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads: [ + { + id: ThreadId.makeUnsafe("thread-1"), + projectId: ProjectId.makeUnsafe("project-a"), + title: "Thread A", + modelSelection: defaultModelSelection, + interactionMode: "default" as const, + runtimeMode: "full-access" as const, + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + latestTurn: null, + messages: [], + session: null, + activities: [], + proposedPlans: [], + checkpoints: [], + deletedAt: null, + }, + ], + }; + + yield* buildAppUnderTest({ + layers: { + projectionSnapshotQuery: { + getSnapshot: () => Effect.succeed(snapshot), + }, + orchestrationEngine: { + dispatch: () => Effect.succeed({ sequence: 7 }), + readEvents: () => Stream.empty, + }, + checkpointDiffQuery: { + getTurnDiff: () => + Effect.succeed({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + diff: "turn-diff", + }), + getFullThreadDiff: () => + Effect.succeed({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + diff: "full-diff", + }), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const snapshotResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})), + ); + assert.equal(snapshotResult.snapshotSequence, 1); + + const dispatchResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.session.stop", + commandId: CommandId.makeUnsafe("cmd-1"), + threadId: ThreadId.makeUnsafe("thread-1"), + createdAt: now, + }), + ), + ); + assert.equal(dispatchResult.sequence, 7); + + const turnDiffResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ + threadId: ThreadId.makeUnsafe("thread-1"), + fromTurnCount: 0, + toTurnCount: 1, + }), + ), + ); + assert.equal(turnDiffResult.diff, "turn-diff"); + + const fullDiffResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.getFullThreadDiff]({ + threadId: ThreadId.makeUnsafe("thread-1"), + toTurnCount: 1, + }), + ), + ); + assert.equal(fullDiffResult.diff, "full-diff"); + + const replayResult = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.replayEvents]({ + fromSequenceExclusive: 0, + }), + ), + ); + assert.deepEqual(replayResult, []); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience", + () => + Effect.gen(function* () { + const now = new Date().toISOString(); + const threadId = ThreadId.makeUnsafe("thread-1"); + let replayCursor: number | null = null; + const makeEvent = (sequence: number): OrchestrationEvent => + ({ + sequence, + eventId: `event-${sequence}`, + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.reverted", + payload: { + threadId, + turnCount: sequence, + }, + }) as OrchestrationEvent; + + yield* buildAppUnderTest({ + layers: { + orchestrationEngine: { + getReadModel: () => + Effect.succeed({ + ...makeDefaultOrchestrationReadModel(), + snapshotSequence: 1, + }), + readEvents: (fromSequenceExclusive) => { + replayCursor = fromSequenceExclusive; + return Stream.make(makeEvent(2), makeEvent(3)); + }, + streamDomainEvents: Stream.make(makeEvent(3), makeEvent(4)), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const events = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.subscribeOrchestrationDomainEvents]({}).pipe( + Stream.take(3), + Stream.runCollect, + ), + ), + ); + + assert.equal(replayCursor, 1); + assert.deepEqual( + Array.from(events).map((event) => event.sequence), + [2, 3, 4], + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc orchestration.getSnapshot errors", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + layers: { + projectionSnapshotQuery: { + getSnapshot: () => + Effect.fail( + new PersistenceSqlError({ + operation: "ProjectionSnapshotQuery.getSnapshot", + detail: "projection unavailable", + }), + ), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})).pipe( + Effect.result, + ), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "OrchestrationGetSnapshotError"); + assertInclude(result.failure.message, "Failed to load orchestration snapshot"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc terminal methods", () => + Effect.gen(function* () { + const snapshot = { + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + status: "running" as const, + pid: 1234, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + }; + + yield* buildAppUnderTest({ + layers: { + terminalManager: { + open: () => Effect.succeed(snapshot), + write: () => Effect.void, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.succeed(snapshot), + close: () => Effect.void, + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + + const opened = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalOpen]({ + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + }), + ), + ); + assert.equal(opened.terminalId, "default"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalWrite]({ + threadId: "thread-1", + terminalId: "default", + data: "echo hi\n", + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalResize]({ + threadId: "thread-1", + terminalId: "default", + cols: 120, + rows: 40, + }), + ), + ); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalClear]({ + threadId: "thread-1", + terminalId: "default", + }), + ), + ); + + const restarted = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalRestart]({ + threadId: "thread-1", + terminalId: "default", + cwd: "/tmp/project", + cols: 120, + rows: 40, + }), + ), + ); + assert.equal(restarted.terminalId, "default"); + + yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalClose]({ + threadId: "thread-1", + terminalId: "default", + }), + ), + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("routes websocket rpc terminal.write errors", () => + Effect.gen(function* () { + const terminalError = new TerminalNotRunningError({ + threadId: "thread-1", + terminalId: "default", + }); + yield* buildAppUnderTest({ + layers: { + terminalManager: { + write: () => Effect.fail(terminalError), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.terminalWrite]({ + threadId: "thread-1", + terminalId: "default", + data: "echo fail\n", + }), + ).pipe(Effect.result), + ); + + assertFailure(result, terminalError); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); +}); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts new file mode 100644 index 0000000000..40a8eb09bc --- /dev/null +++ b/apps/server/src/server.ts @@ -0,0 +1,234 @@ +import { Effect, Layer } from "effect"; +import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; + +import { ServerConfig } from "./config"; +import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http"; +import { fixPath } from "./os-jank"; +import { websocketRpcRouteLayer } from "./ws"; +import { OpenLive } from "./open"; +import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite"; +import { ServerLifecycleEventsLive } from "./serverLifecycleEvents"; +import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService"; +import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger"; +import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; +import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; +import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; +import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter"; +import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; +import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; +import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine"; +import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; +import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; +import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; +import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery"; +import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; +import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; +import { GitCoreLive } from "./git/Layers/GitCore"; +import { GitHubCliLive } from "./git/Layers/GitHubCli"; +import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; +import { TerminalManagerLive } from "./terminal/Layers/Manager"; +import { GitManagerLive } from "./git/Layers/GitManager"; +import { KeybindingsLive } from "./keybindings"; +import { ServerLoggerLive } from "./serverLogger"; +import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup"; +import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor"; +import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus"; +import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; +import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor"; +import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor"; +import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry"; +import { ServerSettingsLive } from "./serverSettings"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; + +const PtyAdapterLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY")); + return BunPTY.layer; + } else { + const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY")); + return NodePTY.layer; + } + }), +); + +const HttpServerLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + if (typeof Bun !== "undefined") { + const BunHttpServer = yield* Effect.promise( + () => import("@effect/platform-bun/BunHttpServer"), + ); + return BunHttpServer.layer({ + port: config.port, + ...(config.host ? { hostname: config.host } : {}), + }); + } else { + const [NodeHttpServer, NodeHttp] = yield* Effect.all([ + Effect.promise(() => import("@effect/platform-node/NodeHttpServer")), + Effect.promise(() => import("node:http")), + ]); + return NodeHttpServer.layer(NodeHttp.createServer, { + host: config.host, + port: config.port, + }); + } + }), +); + +const PlatformServicesLive = Layer.unwrap( + Effect.gen(function* () { + if (typeof Bun !== "undefined") { + const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices")); + return layer; + } else { + const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices")); + return layer; + } + }), +); + +const ReactorLayerLive = Layer.empty.pipe( + Layer.provideMerge(OrchestrationReactorLive), + Layer.provideMerge(ProviderRuntimeIngestionLive), + Layer.provideMerge(ProviderCommandReactorLive), + Layer.provideMerge(CheckpointReactorLive), + Layer.provideMerge(RuntimeReceiptBusLive), +); + +const OrchestrationLayerLive = Layer.empty.pipe( + Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive), + Layer.provideMerge(OrchestrationEngineLive), + Layer.provideMerge(OrchestrationProjectionPipelineLive), + Layer.provideMerge(OrchestrationEventStoreLive), + Layer.provideMerge(OrchestrationCommandReceiptRepositoryLive), +); + +const CheckpointingLayerLive = Layer.empty.pipe( + Layer.provideMerge(CheckpointDiffQueryLive), + Layer.provideMerge(CheckpointStoreLive), +); + +const ProviderLayerLive = Layer.unwrap( + Effect.gen(function* () { + const { providerEventLogPath } = yield* ServerConfig; + const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "native", + }); + const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { + stream: "canonical", + }); + const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( + Layer.provide(ProviderSessionRuntimeRepositoryLive), + ); + const codexAdapterLayer = makeCodexAdapterLive( + nativeEventLogger ? { nativeEventLogger } : undefined, + ); + const claudeAdapterLayer = makeClaudeAdapterLive( + nativeEventLogger ? { nativeEventLogger } : undefined, + ); + const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( + Layer.provide(codexAdapterLayer), + Layer.provide(claudeAdapterLayer), + Layer.provideMerge(providerSessionDirectoryLayer), + ); + return makeProviderServiceLive( + canonicalEventLogger ? { canonicalEventLogger } : undefined, + ).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer)); + }), +); + +const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); + +const GitLayerLive = Layer.empty.pipe( + Layer.provideMerge( + GitManagerLive.pipe( + Layer.provideMerge(GitCoreLive), + Layer.provideMerge(GitHubCliLive), + Layer.provideMerge(RoutingTextGenerationLive), + ), + ), + Layer.provideMerge(GitCoreLive), +); + +const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive)); + +const WorkspaceLayerLive = Layer.mergeAll( + WorkspacePathsLive, + WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)), + WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + ), +); + +const RuntimeServicesLive = Layer.empty.pipe( + Layer.provideMerge(ServerRuntimeStartupLive), + Layer.provideMerge(ReactorLayerLive), + + // Core Services + Layer.provideMerge(CheckpointingLayerLive), + Layer.provideMerge(OrchestrationLayerLive), + Layer.provideMerge(ProviderLayerLive), + Layer.provideMerge(GitLayerLive), + Layer.provideMerge(TerminalLayerLive), + Layer.provideMerge(PersistenceLayerLive), + Layer.provideMerge(KeybindingsLive), + Layer.provideMerge(ProviderRegistryLive), + Layer.provideMerge(ServerSettingsLive), + Layer.provideMerge(WorkspaceLayerLive), + Layer.provideMerge(ProjectFaviconResolverLive), + + // Misc. + Layer.provideMerge(AnalyticsServiceLayerLive), + Layer.provideMerge(OpenLive), + Layer.provideMerge(ServerLifecycleEventsLive), +); + +export const makeRoutesLayer = Layer.mergeAll( + attachmentsRouteLayer, + projectFaviconRouteLayer, + staticAndDevRouteLayer, + websocketRpcRouteLayer, +); + +export const makeServerLayer = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + + fixPath(); + + const httpListeningLayer = Layer.effectDiscard( + Effect.gen(function* () { + yield* HttpServer.HttpServer; + const startup = yield* ServerRuntimeStartup; + yield* startup.markHttpListening; + }), + ); + + const serverApplicationLayer = Layer.mergeAll( + HttpRouter.serve(makeRoutesLayer, { + disableLogger: !config.logWebSocketEvents, + }), + httpListeningLayer, + ); + + return serverApplicationLayer.pipe( + Layer.provideMerge(RuntimeServicesLive), + Layer.provideMerge(HttpServerLive), + Layer.provide(ServerLoggerLive), + Layer.provideMerge(FetchHttpClient.layer), + Layer.provideMerge(PlatformServicesLive), + ); + }), +); + +// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer. +export const runServer = Layer.launch(makeServerLayer) satisfies Effect.Effect< + never, + any, + ServerConfig +>; diff --git a/apps/server/src/serverLayers.ts b/apps/server/src/serverLayers.ts deleted file mode 100644 index a8c1a13f7f..0000000000 --- a/apps/server/src/serverLayers.ts +++ /dev/null @@ -1,146 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, FileSystem, Layer, Path } from "effect"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery"; -import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; -import { ServerConfig } from "./config"; -import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; -import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; -import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; -import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine"; -import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor"; -import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor"; -import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor"; -import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; -import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; -import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; -import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus"; -import { ProviderUnsupportedError } from "./provider/Errors"; -import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter"; -import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; -import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; -import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; -import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; -import { ProviderService } from "./provider/Services/ProviderService"; -import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger"; -import { ServerSettingsService } from "./serverSettings"; - -import { TerminalManagerLive } from "./terminal/Layers/Manager"; -import { KeybindingsLive } from "./keybindings"; -import { GitManagerLive } from "./git/Layers/GitManager"; -import { GitCoreLive } from "./git/Layers/GitCore"; -import { GitHubCliLive } from "./git/Layers/GitHubCli"; -import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; -import { PtyAdapter } from "./terminal/Services/PTY"; -import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; - -type RuntimePtyAdapterLoader = { - layer: Layer.Layer; -}; - -const runtimePtyAdapterLoaders = { - bun: () => import("./terminal/Layers/BunPTY"), - node: () => import("./terminal/Layers/NodePTY"), -} satisfies Record Promise>; - -const makeRuntimePtyAdapterLayer = () => - Effect.gen(function* () { - const runtime = process.versions.bun !== undefined ? "bun" : "node"; - const loader = runtimePtyAdapterLoaders[runtime]; - const ptyAdapterModule = yield* Effect.promise(loader); - return ptyAdapterModule.layer; - }).pipe(Layer.unwrap); - -export function makeServerProviderLayer(): Layer.Layer< - ProviderService, - ProviderUnsupportedError, - | SqlClient.SqlClient - | ServerConfig - | ServerSettingsService - | FileSystem.FileSystem - | AnalyticsService -> { - return Effect.gen(function* () { - const { providerEventLogPath } = yield* ServerConfig; - const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "native", - }); - const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, { - stream: "canonical", - }); - const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(ProviderSessionRuntimeRepositoryLive), - ); - const codexAdapterLayer = makeCodexAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const claudeAdapterLayer = makeClaudeAdapterLive( - nativeEventLogger ? { nativeEventLogger } : undefined, - ); - const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( - Layer.provide(codexAdapterLayer), - Layer.provide(claudeAdapterLayer), - Layer.provideMerge(providerSessionDirectoryLayer), - ); - return makeProviderServiceLive( - canonicalEventLogger ? { canonicalEventLogger } : undefined, - ).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer)); - }).pipe(Layer.unwrap); -} - -export function makeServerRuntimeServicesLayer() { - const textGenerationLayer = RoutingTextGenerationLive; - const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); - - const orchestrationLayer = OrchestrationEngineLive.pipe( - Layer.provide(OrchestrationProjectionPipelineLive), - Layer.provide(OrchestrationEventStoreLive), - Layer.provide(OrchestrationCommandReceiptRepositoryLive), - ); - - const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe( - Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive), - Layer.provideMerge(checkpointStoreLayer), - ); - - const runtimeServicesLayer = Layer.mergeAll( - orchestrationLayer, - OrchestrationProjectionSnapshotQueryLive, - checkpointStoreLayer, - checkpointDiffQueryLayer, - RuntimeReceiptBusLive, - ); - const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( - Layer.provideMerge(runtimeServicesLayer), - ); - const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( - Layer.provideMerge(runtimeServicesLayer), - Layer.provideMerge(GitCoreLive), - Layer.provideMerge(textGenerationLayer), - ); - const checkpointReactorLayer = CheckpointReactorLive.pipe( - Layer.provideMerge(runtimeServicesLayer), - ); - const orchestrationReactorLayer = OrchestrationReactorLive.pipe( - Layer.provideMerge(runtimeIngestionLayer), - Layer.provideMerge(providerCommandReactorLayer), - Layer.provideMerge(checkpointReactorLayer), - ); - - const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer())); - - const gitManagerLayer = GitManagerLive.pipe( - Layer.provideMerge(GitCoreLive), - Layer.provideMerge(GitHubCliLive), - Layer.provideMerge(textGenerationLayer), - ); - - return Layer.mergeAll( - orchestrationReactorLayer, - GitCoreLive, - gitManagerLayer, - terminalLayer, - KeybindingsLive, - ).pipe(Layer.provideMerge(NodeServices.layer)); -} diff --git a/apps/server/src/serverLifecycleEvents.test.ts b/apps/server/src/serverLifecycleEvents.test.ts new file mode 100644 index 0000000000..1cd8c25c03 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.test.ts @@ -0,0 +1,42 @@ +import { assert, it } from "@effect/vitest"; +import { assertTrue } from "@effect/vitest/utils"; +import { Effect, Option } from "effect"; + +import { ServerLifecycleEvents, ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts"; + +it.effect( + "publishes lifecycle events without subscribers and snapshots the latest welcome/ready", + () => + Effect.gen(function* () { + const lifecycleEvents = yield* ServerLifecycleEvents; + + const welcome = yield* lifecycleEvents + .publish({ + version: 1, + type: "welcome", + payload: { + cwd: "/tmp/project", + projectName: "project", + }, + }) + .pipe(Effect.timeoutOption("50 millis")); + assertTrue(Option.isSome(welcome)); + assert.equal(welcome.value.sequence, 1); + + const ready = yield* lifecycleEvents + .publish({ + version: 1, + type: "ready", + payload: { + at: new Date().toISOString(), + }, + }) + .pipe(Effect.timeoutOption("50 millis")); + assertTrue(Option.isSome(ready)); + assert.equal(ready.value.sequence, 2); + + const snapshot = yield* lifecycleEvents.snapshot; + assert.equal(snapshot.sequence, 2); + assert.deepEqual(snapshot.events.map((event) => event.type).toSorted(), ["ready", "welcome"]); + }).pipe(Effect.provide(ServerLifecycleEventsLive)), +); diff --git a/apps/server/src/serverLifecycleEvents.ts b/apps/server/src/serverLifecycleEvents.ts new file mode 100644 index 0000000000..4808a19d72 --- /dev/null +++ b/apps/server/src/serverLifecycleEvents.ts @@ -0,0 +1,53 @@ +import type { ServerLifecycleStreamEvent } from "@t3tools/contracts"; +import { Effect, Layer, PubSub, Ref, ServiceMap, Stream } from "effect"; + +type LifecycleEventInput = + | Omit, "sequence"> + | Omit, "sequence">; + +interface SnapshotState { + readonly sequence: number; + readonly events: ReadonlyArray; +} + +export interface ServerLifecycleEventsShape { + readonly publish: (event: LifecycleEventInput) => Effect.Effect; + readonly snapshot: Effect.Effect; + readonly stream: Stream.Stream; +} + +export class ServerLifecycleEvents extends ServiceMap.Service< + ServerLifecycleEvents, + ServerLifecycleEventsShape +>()("t3/serverLifecycleEvents") {} + +export const ServerLifecycleEventsLive = Layer.effect( + ServerLifecycleEvents, + Effect.gen(function* () { + const pubsub = yield* PubSub.unbounded(); + const state = yield* Ref.make({ + sequence: 0, + events: [], + }); + + return { + publish: (event) => + Ref.modify(state, (current) => { + const nextSequence = current.sequence + 1; + const nextEvent = { + ...event, + sequence: nextSequence, + } satisfies ServerLifecycleStreamEvent; + const nextEvents = + nextEvent.type === "welcome" + ? [nextEvent, ...current.events.filter((entry) => entry.type !== "welcome")] + : [nextEvent, ...current.events.filter((entry) => entry.type !== "ready")]; + return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const; + }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))), + snapshot: Ref.get(state), + get stream() { + return Stream.fromPubSub(pubsub); + }, + } satisfies ServerLifecycleEventsShape; + }), +); diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts index 1b90babaad..aea53aacfb 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -1,20 +1,16 @@ -import fs from "node:fs"; - -import { Effect, Logger } from "effect"; -import * as Layer from "effect/Layer"; +import { Effect, Logger, References, Layer } from "effect"; import { ServerConfig } from "./config"; export const ServerLoggerLive = Effect.gen(function* () { - const { logsDir, serverLogPath } = yield* ServerConfig; - - yield* Effect.sync(() => { - fs.mkdirSync(logsDir, { recursive: true }); - }); + const config = yield* ServerConfig; + const { serverLogPath } = config; const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath)); - - return Logger.layer([Logger.defaultLogger, fileLogger], { + const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel); + const loggerLayer = Logger.layer([Logger.consolePretty(), fileLogger], { mergeWithExisting: false, }); + + return Layer.mergeAll(loggerLayer, minimumLogLevelLayer); }).pipe(Layer.unwrap); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts new file mode 100644 index 0000000000..55700e3482 --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -0,0 +1,49 @@ +import { assert, it } from "@effect/vitest"; +import { Deferred, Effect, Fiber, Ref } from "effect"; +import { TestClock } from "effect/testing"; + +import { makeCommandGate, ServerRuntimeStartupError } from "./serverRuntimeStartup.ts"; + +it.effect("enqueueCommand waits for readiness and then drains queued work", () => + Effect.scoped( + Effect.gen(function* () { + const executionCount = yield* Ref.make(0); + const commandGate = yield* makeCommandGate; + + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Ref.updateAndGet(executionCount, (count) => count + 1)) + .pipe(Effect.forkScoped); + + yield* TestClock.adjust("50 millis"); + assert.equal(yield* Ref.get(executionCount), 0); + + yield* commandGate.signalCommandReady; + + const result = yield* Fiber.join(queuedCommandFiber); + assert.equal(result, 1); + assert.equal(yield* Ref.get(executionCount), 1); + }), + ), +); + +it.effect("enqueueCommand fails queued work when readiness fails", () => + Effect.scoped( + Effect.gen(function* () { + const commandGate = yield* makeCommandGate; + const failure = yield* Deferred.make(); + + const queuedCommandFiber = yield* commandGate + .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run"))) + .pipe(Effect.forkScoped); + + yield* commandGate.failCommandReady( + new ServerRuntimeStartupError({ + message: "startup failed", + }), + ); + + const error = yield* Effect.flip(Fiber.join(queuedCommandFiber)); + assert.equal(error.message, "startup failed"); + }), + ), +); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts new file mode 100644 index 0000000000..2457f6ffe8 --- /dev/null +++ b/apps/server/src/serverRuntimeStartup.ts @@ -0,0 +1,334 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + type ModelSelection, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import { Data, Deferred, Effect, Exit, Layer, Path, Queue, Ref, Scope, ServiceMap } from "effect"; + +import { ServerConfig } from "./config"; +import { Keybindings } from "./keybindings"; +import { Open } from "./open"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; +import { ServerLifecycleEvents } from "./serverLifecycleEvents"; +import { ServerSettingsService } from "./serverSettings"; +import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; + +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 class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface ServerRuntimeStartupShape { + readonly awaitCommandReady: Effect.Effect; + readonly markHttpListening: Effect.Effect; + readonly enqueueCommand: ( + effect: Effect.Effect, + ) => Effect.Effect; +} + +export class ServerRuntimeStartup extends ServiceMap.Service< + ServerRuntimeStartup, + ServerRuntimeStartupShape +>()("t3/serverRuntimeStartup") {} + +interface QueuedCommand { + readonly run: Effect.Effect; +} + +type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError; + +interface CommandGate { + readonly awaitCommandReady: Effect.Effect; + readonly signalCommandReady: Effect.Effect; + readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect; + readonly enqueueCommand: ( + effect: Effect.Effect, + ) => Effect.Effect; +} + +const settleQueuedCommand = (deferred: Deferred.Deferred, exit: Exit.Exit) => + Exit.isSuccess(exit) + ? Deferred.succeed(deferred, exit.value) + : Deferred.failCause(deferred, exit.cause); + +export const makeCommandGate = Effect.gen(function* () { + const commandReady = yield* Deferred.make(); + const commandQueue = yield* Queue.unbounded(); + const commandReadinessState = yield* Ref.make("pending"); + + const commandWorker = Effect.forever( + Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)), + ); + yield* Effect.forkScoped(commandWorker); + + return { + awaitCommandReady: Deferred.await(commandReady), + signalCommandReady: Effect.gen(function* () { + yield* Ref.set(commandReadinessState, "ready"); + yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie); + }), + failCommandReady: (error) => + Effect.gen(function* () { + yield* Ref.set(commandReadinessState, error); + yield* Deferred.fail(commandReady, error).pipe(Effect.orDie); + }), + enqueueCommand: (effect: Effect.Effect) => + Effect.gen(function* () { + const readinessState = yield* Ref.get(commandReadinessState); + if (readinessState === "ready") { + return yield* effect; + } + if (readinessState !== "pending") { + return yield* readinessState; + } + + const result = yield* Deferred.make(); + yield* Queue.offer(commandQueue, { + run: Deferred.await(commandReady).pipe( + Effect.flatMap(() => effect), + Effect.exit, + Effect.flatMap((exit) => settleQueuedCommand(result, exit)), + ), + }); + return yield* Deferred.await(result); + }), + } satisfies CommandGate; +}); + +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 autoBootstrapWelcome = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + const projectionReadModelQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const path = yield* Path.Path; + + let bootstrapProjectId: ProjectId | undefined; + let bootstrapThreadId: ThreadId | undefined; + + if (serverConfig.autoBootstrapProjectFromCwd) { + yield* Effect.gen(function* () { + const snapshot = yield* projectionReadModelQuery.getSnapshot(); + const existingProject = snapshot.projects.find( + (project) => project.workspaceRoot === serverConfig.cwd && project.deletedAt === null, + ); + let nextProjectId: ProjectId; + let nextProjectDefaultModelSelection: ModelSelection; + + if (!existingProject) { + const createdAt = new Date().toISOString(); + nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); + const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project"; + nextProjectDefaultModelSelection = { + provider: "codex", + model: "gpt-5-codex", + }; + yield* orchestrationEngine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + projectId: nextProjectId, + title: bootstrapProjectTitle, + workspaceRoot: serverConfig.cwd, + defaultModelSelection: nextProjectDefaultModelSelection, + createdAt, + }); + } else { + nextProjectId = existingProject.id; + nextProjectDefaultModelSelection = existingProject.defaultModelSelection ?? { + provider: "codex", + model: "gpt-5-codex", + }; + } + + const existingThread = snapshot.threads.find( + (thread) => thread.projectId === nextProjectId && thread.deletedAt === null, + ); + if (!existingThread) { + const createdAt = new Date().toISOString(); + const createdThreadId = ThreadId.makeUnsafe(crypto.randomUUID()); + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe(crypto.randomUUID()), + threadId: createdThreadId, + projectId: nextProjectId, + title: "New thread", + modelSelection: nextProjectDefaultModelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }); + bootstrapProjectId = nextProjectId; + bootstrapThreadId = createdThreadId; + } else { + bootstrapProjectId = nextProjectId; + bootstrapThreadId = existingThread.id; + } + }); + } + + const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean); + const projectName = segments[segments.length - 1] ?? "project"; + + return { + cwd: serverConfig.cwd, + projectName, + ...(bootstrapProjectId ? { bootstrapProjectId } : {}), + ...(bootstrapThreadId ? { bootstrapThreadId } : {}), + } as const; +}); + +const maybeOpenBrowser = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + if (serverConfig.noBrowser) { + return; + } + const { openBrowser } = yield* Open; + const localUrl = `http://localhost:${serverConfig.port}`; + const bindUrl = + serverConfig.host && !isWildcardHost(serverConfig.host) + ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}` + : localUrl; + const target = serverConfig.devUrl?.toString() ?? bindUrl; + + yield* openBrowser(target).pipe( + Effect.catch(() => + Effect.logInfo("browser auto-open unavailable", { + hint: `Open ${target} in your browser.`, + }), + ), + ); +}); + +const makeServerRuntimeStartup = Effect.gen(function* () { + const keybindings = yield* Keybindings; + const orchestrationReactor = yield* OrchestrationReactor; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + + const commandGate = yield* makeCommandGate; + const httpListening = yield* Deferred.make(); + const reactorScope = yield* Scope.make("sequential"); + + yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void)); + + const startup = Effect.gen(function* () { + yield* Effect.logDebug("startup phase: starting keybindings runtime"); + yield* keybindings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start keybindings runtime", { + path: error.configPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, + ); + + yield* Effect.logDebug("startup phase: starting server settings runtime"); + yield* serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, + ); + + yield* Effect.logDebug("startup phase: starting orchestration reactors"); + yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope)); + + yield* Effect.logDebug("startup phase: preparing welcome payload"); + const welcome = yield* autoBootstrapWelcome; + yield* Effect.logDebug("startup phase: publishing welcome event", { + cwd: welcome.cwd, + projectName: welcome.projectName, + bootstrapProjectId: welcome.bootstrapProjectId, + bootstrapThreadId: welcome.bootstrapThreadId, + }); + yield* lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: welcome, + }); + }); + + yield* Effect.forkScoped( + Effect.gen(function* () { + const startupExit = yield* Effect.exit(startup); + if (Exit.isFailure(startupExit)) { + const error = new ServerRuntimeStartupError({ + message: "Server runtime startup failed before command readiness.", + cause: startupExit.cause, + }); + yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause }); + yield* commandGate.failCommandReady(error); + return; + } + + yield* Effect.logDebug("Accepting commands"); + yield* commandGate.signalCommandReady; + yield* Effect.logDebug("startup phase: waiting for http listener"); + yield* Deferred.await(httpListening); + yield* Effect.logDebug("startup phase: publishing ready event"); + yield* lifecycleEvents.publish({ + version: 1, + type: "ready", + payload: { at: new Date().toISOString() }, + }); + + yield* Effect.logDebug("startup phase: recording startup heartbeat"); + yield* recordStartupHeartbeat; + yield* Effect.logDebug("startup phase: browser open check"); + yield* maybeOpenBrowser; + yield* Effect.logDebug("startup phase: complete"); + }), + ); + + return { + awaitCommandReady: commandGate.awaitCommandReady, + markHttpListening: Deferred.succeed(httpListening, undefined), + enqueueCommand: commandGate.enqueueCommand, + } satisfies ServerRuntimeStartupShape; +}); + +export const ServerRuntimeStartupLive = Layer.effect( + ServerRuntimeStartup, + makeServerRuntimeStartup, +); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 06e38e2465..dbbf62ddef 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -16,6 +16,7 @@ import { type ModelSelection, type ProviderKind, ServerSettings, + ServerSettingsError, type ServerSettingsPatch, } from "@t3tools/contracts"; import { @@ -35,25 +36,13 @@ import { Scope, ServiceMap, Stream, + Cause, } from "effect"; import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config"; import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; import { encodePrettyJsonEffect, fromLenientJson } from "@t3tools/shared/schemaJson"; -export class ServerSettingsError extends Schema.TaggedErrorClass()( - "ServerSettingsError", - { - settingsPath: Schema.String, - detail: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Server settings error at ${this.settingsPath}: ${this.detail}`; - } -} - export interface ServerSettingsShape { /** Start the settings runtime and attach file watching. */ readonly start: Effect.Effect; @@ -234,6 +223,7 @@ const makeServerSettings = Effect.gen(function* () { if (decoded._tag === "Failure") { yield* Effect.logWarning("failed to parse settings.json, using defaults", { path: settingsPath, + issues: Cause.pretty(decoded.cause), }); return DEFAULT_SERVER_SETTINGS; } diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index 067cd55438..bdfbc85cc5 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -10,84 +10,58 @@ import { TerminalClearInput, TerminalCloseInput, TerminalEvent, + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, TerminalOpenInput, TerminalResizeInput, TerminalRestartInput, TerminalSessionSnapshot, + TerminalSessionLookupError, + TerminalSessionStatus, TerminalWriteInput, } from "@t3tools/contracts"; -import { Effect, Schema, ServiceMap } from "effect"; +import { PtyProcess } from "./PTY"; +import { Effect, ServiceMap } from "effect"; -export class TerminalCwdError extends Schema.TaggedErrorClass()( - "TerminalCwdError", - { - cwd: Schema.String, - reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]), - cause: Schema.optional(Schema.Defect), - }, -) { - override get message() { - if (this.reason === "notDirectory") { - return `Terminal cwd is not a directory: ${this.cwd}`; - } - if (this.reason === "notFound") { - return `Terminal cwd does not exist: ${this.cwd}`; - } - const causeMessage = - this.cause && typeof this.cause === "object" && "message" in this.cause - ? this.cause.message - : undefined; - return causeMessage - ? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})` - : `Failed to access terminal cwd: ${this.cwd}`; - } -} - -export class TerminalHistoryError extends Schema.TaggedErrorClass()( - "TerminalHistoryError", - { - operation: Schema.Literals(["read", "truncate", "migrate"]), - threadId: Schema.String, - terminalId: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message() { - return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export class TerminalSessionLookupError extends Schema.TaggedErrorClass()( - "TerminalSessionLookupError", - { - threadId: Schema.String, - terminalId: Schema.String, - }, -) { - override get message() { - return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export class TerminalNotRunningError extends Schema.TaggedErrorClass()( - "TerminalNotRunningError", - { - threadId: Schema.String, - terminalId: Schema.String, - }, -) { - override get message() { - return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`; - } -} - -export const TerminalError = Schema.Union([ +export { TerminalCwdError, + TerminalError, TerminalHistoryError, - TerminalSessionLookupError, TerminalNotRunningError, -]); -export type TerminalError = typeof TerminalError.Type; + TerminalSessionLookupError, +}; + +export interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + exitCode: number | null; + exitSignal: number | null; + updatedAt: string; + cols: number; + rows: number; + process: PtyProcess | null; + unsubscribeData: (() => void) | null; + unsubscribeExit: (() => void) | null; + hasRunningSubprocess: boolean; + runtimeEnv: Record | null; +} + +export interface ShellCandidate { + shell: string; + args?: string[]; +} + +export interface TerminalStartInput extends TerminalOpenInput { + cols: number; + rows: number; +} /** * TerminalManagerShape - Service API for terminal session lifecycle operations. diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts new file mode 100644 index 0000000000..960cb69bf1 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts @@ -0,0 +1,266 @@ +import fsPromises from "node:fs/promises"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, afterEach, describe, expect, vi } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path, PlatformError } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-entries-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) { + const fileSystem = yield* FileSystem.FileSystem; + const gitCore = yield* GitCore; + const dir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: opts?.prefix ?? "t3code-workspace-entries-", + }); + if (opts?.git) { + yield* gitCore.initRepo({ cwd: dir }); + } + return dir; +}); + +function writeTextFile( + cwd: string, + relativePath: string, + contents = "", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true }); + yield* fileSystem.writeFileString(absolutePath, contents); + }); +} + +const git = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => + Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "WorkspaceEntries.test.git", + cwd, + args, + ...(env ? { env } : {}), + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); + +const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + return yield* workspaceEntries.search(input); + }); + +it.layer(TestLayer)("WorkspaceEntriesLive", (it) => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("search", () => { + it.effect("returns files and directories relative to cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/index.ts"); + yield* writeTextFile(cwd, "README.md"); + yield* writeTextFile(cwd, ".git/HEAD"); + yield* writeTextFile(cwd, "node_modules/pkg/index.js"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + expect(paths).toContain("README.md"); + expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false); + expect(result.truncated).toBe(false); + }), + ); + + it.effect("filters and ranks entries by query", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); + + expect(result.entries.length).toBeGreaterThan(0); + expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true); + expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe( + true, + ); + }), + ); + + it.effect("supports fuzzy subsequence queries for composer path search", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); + const paths = result.entries.map((entry) => entry.path); + + expect(result.entries.length).toBeGreaterThan(0); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + }), + ); + + it.effect("tracks truncation without sorting every fuzzy match", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); + + expect(result.entries).toHaveLength(1); + expect(result.truncated).toBe(true); + }), + ); + + it.effect("excludes gitignored paths for git repositories", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true }); + yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* writeTextFile(cwd, "ignored.txt", "ignore me"); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths).not.toContain("ignored.txt"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false); + }), + ); + + it.effect("excludes tracked paths that match ignore rules", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ + prefix: "t3code-workspace-tracked-gitignore-", + git: true, + }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]); + yield* writeTextFile(cwd, ".gitignore", ".convex/\n"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("excludes .convex in non-git workspaces", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("deduplicates concurrent index builds for the same cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-concurrent-build-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + + let rootReadCount = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === cwd) { + rootReadCount += 1; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* Effect.all( + [ + searchWorkspaceEntries({ cwd, query: "", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "src", limit: 100 }), + ], + { concurrency: "unbounded" }, + ); + + expect(rootReadCount).toBe(1); + }), + ); + + it.effect("limits concurrent directory reads while walking the filesystem", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-read-concurrency-" }); + yield* Effect.forEach( + Array.from({ length: 80 }, (_, index) => index), + (index) => writeTextFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"), + { discard: true }, + ); + + let activeReads = 0; + let peakReads = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + const target = args[0]; + if (typeof target === "string" && target.startsWith(cwd)) { + activeReads += 1; + peakReads = Math.max(peakReads, activeReads); + await new Promise((resolve) => setTimeout(resolve, 4)); + try { + return await originalReaddir(...args); + } finally { + activeReads -= 1; + } + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }); + + expect(peakReads).toBeLessThanOrEqual(32); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts new file mode 100644 index 0000000000..12af8601ca --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -0,0 +1,503 @@ +import fsPromises from "node:fs/promises"; +import type { Dirent } from "node:fs"; + +import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect"; + +import { type ProjectEntry } from "@t3tools/contracts"; + +import { GitCore } from "../../git/Services/GitCore.ts"; +import { + WorkspaceEntries, + WorkspaceEntriesError, + type WorkspaceEntriesShape, +} from "../Services/WorkspaceEntries.ts"; +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; + +const WORKSPACE_CACHE_TTL_MS = 15_000; +const WORKSPACE_CACHE_MAX_KEYS = 4; +const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; +const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32; +const IGNORED_DIRECTORY_NAMES = new Set([ + ".git", + ".convex", + "node_modules", + ".next", + ".turbo", + "dist", + "build", + "out", + ".cache", +]); + +interface WorkspaceIndex { + scannedAt: number; + entries: SearchableWorkspaceEntry[]; + truncated: boolean; +} + +interface SearchableWorkspaceEntry extends ProjectEntry { + normalizedPath: string; + normalizedName: string; +} + +interface RankedWorkspaceEntry { + entry: SearchableWorkspaceEntry; + score: number; +} + +function toPosixPath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function parentPathOf(input: string): string | undefined { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return undefined; + } + return input.slice(0, separatorIndex); +} + +function basenameOf(input: string): string { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return input; + } + return input.slice(separatorIndex + 1); +} + +function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry { + const normalizedPath = entry.path.toLowerCase(); + return { + ...entry, + normalizedPath, + normalizedName: basenameOf(normalizedPath), + }; +} + +function normalizeQuery(input: string): string { + return input + .trim() + .replace(/^[@./]+/, "") + .toLowerCase(); +} + +function scoreSubsequenceMatch(value: string, query: string): number | null { + if (!query) return 0; + + let queryIndex = 0; + let firstMatchIndex = -1; + let previousMatchIndex = -1; + let gapPenalty = 0; + + for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) { + if (value[valueIndex] !== query[queryIndex]) { + continue; + } + + if (firstMatchIndex === -1) { + firstMatchIndex = valueIndex; + } + if (previousMatchIndex !== -1) { + gapPenalty += valueIndex - previousMatchIndex - 1; + } + + previousMatchIndex = valueIndex; + queryIndex += 1; + if (queryIndex === query.length) { + const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length; + const lengthPenalty = Math.min(64, value.length - query.length); + return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty; + } + } + + return null; +} + +function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null { + if (!query) { + return entry.kind === "directory" ? 0 : 1; + } + + const { normalizedPath, normalizedName } = entry; + + if (normalizedName === query) return 0; + if (normalizedPath === query) return 1; + if (normalizedName.startsWith(query)) return 2; + if (normalizedPath.startsWith(query)) return 3; + if (normalizedPath.includes(`/${query}`)) return 4; + if (normalizedName.includes(query)) return 5; + if (normalizedPath.includes(query)) return 6; + + const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); + if (nameFuzzyScore !== null) { + return 100 + nameFuzzyScore; + } + + const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query); + if (pathFuzzyScore !== null) { + return 200 + pathFuzzyScore; + } + + return null; +} + +function compareRankedWorkspaceEntries( + left: RankedWorkspaceEntry, + right: RankedWorkspaceEntry, +): number { + const scoreDelta = left.score - right.score; + if (scoreDelta !== 0) return scoreDelta; + return left.entry.path.localeCompare(right.entry.path); +} + +function findInsertionIndex( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, +): number { + let low = 0; + let high = rankedEntries.length; + + while (low < high) { + const middle = low + Math.floor((high - low) / 2); + const current = rankedEntries[middle]; + if (!current) { + break; + } + + if (compareRankedWorkspaceEntries(candidate, current) < 0) { + high = middle; + } else { + low = middle + 1; + } + } + + return low; +} + +function insertRankedEntry( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, + limit: number, +): void { + if (limit <= 0) { + return; + } + + const insertionIndex = findInsertionIndex(rankedEntries, candidate); + if (rankedEntries.length < limit) { + rankedEntries.splice(insertionIndex, 0, candidate); + return; + } + + if (insertionIndex >= limit) { + return; + } + + rankedEntries.splice(insertionIndex, 0, candidate); + rankedEntries.pop(); +} + +function isPathInIgnoredDirectory(relativePath: string): boolean { + const firstSegment = relativePath.split("/")[0]; + if (!firstSegment) return false; + return IGNORED_DIRECTORY_NAMES.has(firstSegment); +} + +function directoryAncestorsOf(relativePath: string): string[] { + const segments = relativePath.split("/").filter((segment) => segment.length > 0); + if (segments.length <= 1) return []; + + const directories: string[] = []; + for (let index = 1; index < segments.length; index += 1) { + directories.push(segments.slice(0, index).join("/")); + } + return directories; +} + +const processErrorDetail = (cause: unknown): string => + cause instanceof Error ? cause.message : String(cause); + +export const makeWorkspaceEntries = Effect.gen(function* () { + const path = yield* Path.Path; + const gitOption = yield* Effect.serviceOption(GitCore); + const workspacePaths = yield* WorkspacePaths; + + const isInsideGitWorkTree = (cwd: string): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + onNone: () => Effect.succeed(false), + }); + + const filterGitIgnoredPaths = ( + cwd: string, + relativePaths: string[], + ): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => + git.filterIgnoredPaths(cwd, relativePaths).pipe( + Effect.map((paths) => [...paths]), + Effect.catch(() => Effect.succeed(relativePaths)), + ), + onNone: () => Effect.succeed(relativePaths), + }); + + const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")( + function* (cwd: string) { + if (Option.isNone(gitOption)) { + return null; + } + if (!(yield* isInsideGitWorkTree(cwd))) { + return null; + } + + const listedFiles = yield* gitOption.value + .listWorkspaceFiles(cwd) + .pipe(Effect.catch(() => Effect.succeed(null))); + + if (!listedFiles) { + return null; + } + + const listedPaths = [...listedFiles.paths] + .map((entry) => toPosixPath(entry)) + .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); + const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths); + + const directorySet = new Set(); + for (const filePath of filePaths) { + for (const directoryPath of directoryAncestorsOf(filePath)) { + if (!isPathInIgnoredDirectory(directoryPath)) { + directorySet.add(directoryPath); + } + } + } + + const directoryEntries = [...directorySet] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (directoryPath): ProjectEntry => ({ + path: directoryPath, + kind: "directory", + parentPath: parentPathOf(directoryPath), + }), + ) + .map(toSearchableWorkspaceEntry); + const fileEntries = [...new Set(filePaths)] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (filePath): ProjectEntry => ({ + path: filePath, + kind: "file", + parentPath: parentPathOf(filePath), + }), + ) + .map(toSearchableWorkspaceEntry); + + const entries = [...directoryEntries, ...fileEntries]; + return { + scannedAt: Date.now(), + entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES), + truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES, + }; + }, + ); + + const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* ( + cwd: string, + relativeDir: string, + ): Effect.fn.Return< + { readonly relativeDir: string; readonly dirents: Dirent[] | null }, + WorkspaceEntriesError + > { + return yield* Effect.tryPromise({ + try: async () => { + const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd; + const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true }); + return { relativeDir, dirents }; + }, + catch: (cause) => + new WorkspaceEntriesError({ + cwd, + operation: "workspaceEntries.readDirectoryEntries", + detail: processErrorDetail(cause), + cause, + }), + }).pipe( + Effect.catchIf( + () => relativeDir.length > 0, + () => Effect.succeed({ relativeDir, dirents: null }), + ), + ); + }); + + const buildWorkspaceIndexFromFilesystem = Effect.fn( + "WorkspaceEntries.buildWorkspaceIndexFromFilesystem", + )(function* (cwd: string): Effect.fn.Return { + const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd); + + let pendingDirectories: string[] = [""]; + const entries: SearchableWorkspaceEntry[] = []; + let truncated = false; + + while (pendingDirectories.length > 0 && !truncated) { + const currentDirectories = pendingDirectories; + pendingDirectories = []; + + const directoryEntries = yield* Effect.forEach( + currentDirectories, + (relativeDir) => readDirectoryEntries(cwd, relativeDir), + { concurrency: WORKSPACE_SCAN_READDIR_CONCURRENCY }, + ); + + const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => { + const { relativeDir, dirents } = directoryEntry; + if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>; + + dirents.sort((left, right) => left.name.localeCompare(right.name)); + const candidates: Array<{ dirent: Dirent; relativePath: string }> = []; + for (const dirent of dirents) { + if (!dirent.name || dirent.name === "." || dirent.name === "..") { + continue; + } + if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) { + continue; + } + if (!dirent.isDirectory() && !dirent.isFile()) { + continue; + } + + const relativePath = toPosixPath( + relativeDir ? path.join(relativeDir, dirent.name) : dirent.name, + ); + if (isPathInIgnoredDirectory(relativePath)) { + continue; + } + candidates.push({ dirent, relativePath }); + } + return candidates; + }); + + const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) => + candidateEntries.map((entry) => entry.relativePath), + ); + const allowedPathSet = shouldFilterWithGitIgnore + ? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths)) + : null; + + for (const candidateEntries of candidateEntriesByDirectory) { + for (const candidate of candidateEntries) { + if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) { + continue; + } + + const entry = toSearchableWorkspaceEntry({ + path: candidate.relativePath, + kind: candidate.dirent.isDirectory() ? "directory" : "file", + parentPath: parentPathOf(candidate.relativePath), + }); + entries.push(entry); + + if (candidate.dirent.isDirectory()) { + pendingDirectories.push(candidate.relativePath); + } + + if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) { + truncated = true; + break; + } + } + + if (truncated) { + break; + } + } + } + + return { + scannedAt: Date.now(), + entries, + truncated, + }; + }); + + const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* ( + cwd: string, + ): Effect.fn.Return { + const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd); + if (gitIndexed) { + return gitIndexed; + } + return yield* buildWorkspaceIndexFromFilesystem(cwd); + }); + + const workspaceIndexCache = yield* Cache.makeWith({ + capacity: WORKSPACE_CACHE_MAX_KEYS, + lookup: buildWorkspaceIndex, + timeToLive: (exit) => + Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero, + }); + + const normalizeWorkspaceRoot = Effect.fn("WorkspaceEntries.normalizeWorkspaceRoot")(function* ( + cwd: string, + ): Effect.fn.Return { + return yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe( + Effect.mapError( + (cause) => + new WorkspaceEntriesError({ + cwd, + operation: "workspaceEntries.normalizeWorkspaceRoot", + detail: cause.message, + cause, + }), + ), + ); + }); + + const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")( + function* (cwd) { + const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe( + Effect.catch(() => Effect.succeed(cwd)), + ); + yield* Cache.invalidate(workspaceIndexCache, cwd); + if (normalizedCwd !== cwd) { + yield* Cache.invalidate(workspaceIndexCache, normalizedCwd); + } + }, + ); + + const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")( + function* (input) { + const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd); + return yield* Cache.get(workspaceIndexCache, normalizedCwd).pipe( + Effect.map((index) => { + const normalizedQuery = normalizeQuery(input.query); + const limit = Math.max(0, Math.floor(input.limit)); + const rankedEntries: RankedWorkspaceEntry[] = []; + let matchedEntryCount = 0; + + for (const entry of index.entries) { + const score = scoreEntry(entry, normalizedQuery); + if (score === null) { + continue; + } + + matchedEntryCount += 1; + insertRankedEntry(rankedEntries, { entry, score }, limit); + } + + return { + entries: rankedEntries.map((candidate) => candidate.entry), + truncated: index.truncated || matchedEntryCount > limit, + }; + }), + ); + }, + ); + + return { + invalidate, + search, + } satisfies WorkspaceEntriesShape; +}); + +export const WorkspaceEntriesLive = Layer.effect(WorkspaceEntries, makeWorkspaceEntries); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts new file mode 100644 index 0000000000..fcfd13c912 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts @@ -0,0 +1,136 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const ProjectLayer = WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), +); + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectLayer), + Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))), + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-files-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-workspace-files-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => { + describe("writeFile", () => { + it.effect("writes files relative to the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const result = yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + const saved = yield* fileSystem + .readFileString(path.join(cwd, "plans/effect-rpc.md")) + .pipe(Effect.orDie); + + expect(result).toEqual({ relativePath: "plans/effect-rpc.md" }); + expect(saved).toBe("# Plan\n"); + }), + ); + + it.effect("invalidates workspace entry search cache after writes", () => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "src/existing.ts", "export {};\n"); + + const beforeWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(beforeWrite).toEqual({ + entries: [], + truncated: false, + }); + + yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + + const afterWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(afterWrite.entries).toEqual( + expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]), + ); + expect(afterWrite.truncated).toBe(false); + }), + ); + + it.effect("rejects writes outside the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + + const error = yield* workspaceFileSystem + .writeFile({ + cwd, + relativePath: "../escape.md", + contents: "# nope\n", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + + const escapedPath = path.resolve(cwd, "..", "escape.md"); + const escapedStat = yield* fileSystem + .stat(escapedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + expect(escapedStat).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..84e5d9c6d1 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts @@ -0,0 +1,55 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspaceFileSystem, + WorkspaceFileSystemError, + type WorkspaceFileSystemShape, +} from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; + +export const makeWorkspaceFileSystem = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspacePaths = yield* WorkspacePaths; + const workspaceEntries = yield* WorkspaceEntries; + + const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn( + "WorkspaceFileSystem.writeFile", + )(function* (input) { + const target = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + }); + + yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.makeDirectory", + detail: cause.message, + cause, + }), + ), + ); + yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.writeFile", + detail: cause.message, + cause, + }), + ), + ); + yield* workspaceEntries.invalidate(input.cwd); + return { relativePath: target.relativePath }; + }); + return { writeFile } satisfies WorkspaceFileSystemShape; +}); + +export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.test.ts b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts new file mode 100644 index 0000000000..d02a5929d2 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts @@ -0,0 +1,113 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn("makeTempDir")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-paths-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspacePathsLive", (it) => { + describe("normalizeWorkspaceRoot", () => { + it.effect("resolves an existing directory", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd); + + expect(resolved).toBe(cwd); + }), + ); + + it.effect("rejects missing directories", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const error = yield* workspacePaths + .normalizeWorkspaceRoot(path.join(cwd, "missing")) + .pipe(Effect.flip); + + expect(error.message).toContain("Workspace root does not exist:"); + }), + ); + + it.effect("rejects file paths", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + const filePath = path.join(cwd, "README.md"); + yield* writeTextFile(cwd, "README.md", "# hi\n"); + + const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip); + + expect(error.message).toContain("Workspace root is not a directory:"); + }), + ); + }); + + describe("resolveRelativePathWithinRoot", () => { + it.effect("resolves relative paths inside the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "plans/effect-rpc.md", + }); + + expect(resolved).toEqual({ + absolutePath: path.join(cwd, "plans/effect-rpc.md"), + relativePath: "plans/effect-rpc.md", + }); + }), + ); + + it.effect("rejects paths that escape the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const error = yield* workspacePaths + .resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "../escape.md", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.ts b/apps/server/src/workspace/Layers/WorkspacePaths.ts new file mode 100644 index 0000000000..fa7a90cf07 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.ts @@ -0,0 +1,89 @@ +import * as OS from "node:os"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspacePaths, + WorkspacePathOutsideRootError, + WorkspaceRootNotDirectoryError, + WorkspaceRootNotExistsError, + type WorkspacePathsShape, +} from "../Services/WorkspacePaths.ts"; + +function toPosixRelativePath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function expandHomePath(input: string, path: Path.Path): string { + if (input === "~") { + return OS.homedir(); + } + if (input.startsWith("~/") || input.startsWith("~\\")) { + return path.join(OS.homedir(), input.slice(2)); + } + return input; +} + +export const makeWorkspacePaths = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn( + "WorkspacePaths.normalizeWorkspaceRoot", + )(function* (workspaceRoot) { + const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path)); + const workspaceStat = yield* fileSystem + .stat(normalizedWorkspaceRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!workspaceStat) { + return yield* new WorkspaceRootNotExistsError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + if (workspaceStat.type !== "Directory") { + return yield* new WorkspaceRootNotDirectoryError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + return normalizedWorkspaceRoot; + }); + + const resolveRelativePathWithinRoot: WorkspacePathsShape["resolveRelativePathWithinRoot"] = + Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) { + const normalizedInputPath = input.relativePath.trim(); + if (path.isAbsolute(normalizedInputPath)) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath); + const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath)); + if ( + relativeToRoot.length === 0 || + relativeToRoot === "." || + relativeToRoot.startsWith("../") || + relativeToRoot === ".." || + path.isAbsolute(relativeToRoot) + ) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + return { + absolutePath, + relativePath: relativeToRoot, + }; + }); + + return { + normalizeWorkspaceRoot, + resolveRelativePathWithinRoot, + } satisfies WorkspacePathsShape; +}); + +export const WorkspacePathsLive = Layer.effect(WorkspacePaths, makeWorkspacePaths); diff --git a/apps/server/src/workspace/Services/WorkspaceEntries.ts b/apps/server/src/workspace/Services/WorkspaceEntries.ts new file mode 100644 index 0000000000..2841b1fe2f --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceEntries.ts @@ -0,0 +1,48 @@ +/** + * WorkspaceEntries - Effect service contract for cached workspace entry search. + * + * Owns indexed workspace entry search plus cache invalidation for workspace + * roots when the underlying filesystem changes. + * + * @module WorkspaceEntries + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts"; + +export class WorkspaceEntriesError extends Schema.TaggedErrorClass()( + "WorkspaceEntriesError", + { + cwd: Schema.String, + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceEntriesShape - Service API for workspace entry search and cache + * invalidation. + */ +export interface WorkspaceEntriesShape { + /** + * Search indexed workspace entries for files and directories matching the + * provided query. + */ + readonly search: ( + input: ProjectSearchEntriesInput, + ) => Effect.Effect; + + /** + * Drop any cached workspace entries for the given workspace root. + */ + readonly invalidate: (cwd: string) => Effect.Effect; +} + +/** + * WorkspaceEntries - Service tag for cached workspace entry search. + */ +export class WorkspaceEntries extends ServiceMap.Service()( + "t3/workspace/Services/WorkspaceEntries", +) {} diff --git a/apps/server/src/workspace/Services/WorkspaceFileSystem.ts b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..85db1514a3 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts @@ -0,0 +1,50 @@ +/** + * WorkspaceFileSystem - Effect service contract for workspace file mutations. + * + * Owns workspace-root-relative file write operations and their associated + * safety checks and cache invalidation hooks. + * + * @module WorkspaceFileSystem + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts"; +import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts"; + +export class WorkspaceFileSystemError extends Schema.TaggedErrorClass()( + "WorkspaceFileSystemError", + { + cwd: Schema.String, + relativePath: Schema.optional(Schema.String), + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceFileSystemShape - Service API for workspace-relative file operations. + */ +export interface WorkspaceFileSystemShape { + /** + * Write a file relative to the workspace root. + * + * Creates parent directories as needed and rejects paths that escape the + * workspace root. + */ + readonly writeFile: ( + input: ProjectWriteFileInput, + ) => Effect.Effect< + ProjectWriteFileResult, + WorkspaceFileSystemError | WorkspacePathOutsideRootError + >; +} + +/** + * WorkspaceFileSystem - Service tag for workspace file operations. + */ +export class WorkspaceFileSystem extends ServiceMap.Service< + WorkspaceFileSystem, + WorkspaceFileSystemShape +>()("t3/workspace/Services/WorkspaceFileSystem") {} diff --git a/apps/server/src/workspace/Services/WorkspacePaths.ts b/apps/server/src/workspace/Services/WorkspacePaths.ts new file mode 100644 index 0000000000..ad6d9cd3e5 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspacePaths.ts @@ -0,0 +1,85 @@ +/** + * WorkspacePaths - Effect service contract for workspace path handling. + * + * Owns normalization and validation of workspace roots plus safe resolution of + * workspace-root-relative paths. + * + * @module WorkspacePaths + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotExistsError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotDirectoryError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass()( + "WorkspacePathOutsideRootError", + { + workspaceRoot: Schema.String, + relativePath: Schema.String, + }, +) { + override get message(): string { + return `Workspace file path must be relative to the project root: ${this.relativePath}`; + } +} + +export const WorkspacePathsError = Schema.Union([ + WorkspaceRootNotExistsError, + WorkspaceRootNotDirectoryError, + WorkspacePathOutsideRootError, +]); +export type WorkspacePathsError = typeof WorkspacePathsError.Type; + +/** + * WorkspacePathsShape - Service API for workspace path normalization and guards. + */ +export interface WorkspacePathsShape { + /** + * Normalize a user-provided workspace root and verify it exists as a directory. + */ + readonly normalizeWorkspaceRoot: ( + workspaceRoot: string, + ) => Effect.Effect; + + /** + * Resolve a relative path within a validated workspace root. + * + * Rejects absolute paths and traversal attempts outside the workspace root. + */ + readonly resolveRelativePathWithinRoot: (input: { + workspaceRoot: string; + relativePath: string; + }) => Effect.Effect< + { absolutePath: string; relativePath: string }, + WorkspacePathOutsideRootError + >; +} + +/** + * WorkspacePaths - Service tag for workspace path normalization and resolution. + */ +export class WorkspacePaths extends ServiceMap.Service()( + "t3/workspace/Services/WorkspacePaths", +) {} diff --git a/apps/server/src/workspaceEntries.chunking.test.ts b/apps/server/src/workspaceEntries.chunking.test.ts deleted file mode 100644 index f978c5233e..0000000000 --- a/apps/server/src/workspaceEntries.chunking.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { assert, beforeEach, describe, it, vi } from "vitest"; -import type { ProcessRunOptions, ProcessRunResult } from "./processRunner"; - -const { runProcessMock } = vi.hoisted(() => ({ - runProcessMock: - vi.fn< - ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, - ) => Promise - >(), -})); - -vi.mock("./processRunner", () => ({ - runProcess: runProcessMock, -})); - -function processResult( - overrides: Partial & Pick, -): ProcessRunResult { - return { - stdout: overrides.stdout, - code: overrides.code, - stderr: overrides.stderr ?? "", - signal: overrides.signal ?? null, - timedOut: overrides.timedOut ?? false, - stdoutTruncated: overrides.stdoutTruncated ?? false, - stderrTruncated: overrides.stderrTruncated ?? false, - }; -} - -describe("searchWorkspaceEntries git-ignore chunking", () => { - beforeEach(() => { - runProcessMock.mockReset(); - vi.resetModules(); - }); - - it("chunks git check-ignore stdin to avoid building giant strings", async () => { - const ignoredPaths = Array.from( - { length: 5000 }, - (_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`, - ); - const keptPaths = ["src/keep.ts", "docs/readme.md"]; - const listedPaths = [...ignoredPaths, ...keptPaths]; - let checkIgnoreCalls = 0; - - runProcessMock.mockImplementation(async (_command, args, options) => { - if (args[0] === "rev-parse") { - return processResult({ code: 0, stdout: "true\n" }); - } - - if (args[0] === "ls-files") { - return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` }); - } - - if (args[0] === "check-ignore") { - checkIgnoreCalls += 1; - const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0); - const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/")); - return processResult({ - code: chunkIgnored.length > 0 ? 0 : 1, - stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "", - }); - } - - throw new Error(`Unexpected command: git ${args.join(" ")}`); - }); - - const { searchWorkspaceEntries } = await import("./workspaceEntries"); - const result = await searchWorkspaceEntries({ - cwd: "/virtual/workspace", - query: "", - limit: 100, - }); - - assert.isAbove(checkIgnoreCalls, 1); - assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/"))); - assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts")); - }); -}); diff --git a/apps/server/src/workspaceEntries.test.ts b/apps/server/src/workspaceEntries.test.ts deleted file mode 100644 index d867ad910d..0000000000 --- a/apps/server/src/workspaceEntries.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import fs from "node:fs"; -import fsPromises from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import { spawnSync } from "node:child_process"; - -import { afterEach, assert, describe, it, vi } from "vitest"; - -import { searchWorkspaceEntries } from "./workspaceEntries"; - -const tempDirs: string[] = []; - -function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; -} - -function writeFile(cwd: string, relativePath: string, contents = ""): void { - const absolutePath = path.join(cwd, relativePath); - fs.mkdirSync(path.dirname(absolutePath), { recursive: true }); - fs.writeFileSync(absolutePath, contents, "utf8"); -} - -function runGit(cwd: string, args: string[]): void { - const result = spawnSync("git", args, { cwd, encoding: "utf8" }); - if (result.status !== 0) { - throw new Error(result.stderr || `git ${args.join(" ")} failed`); - } -} - -describe("searchWorkspaceEntries", () => { - afterEach(() => { - vi.restoreAllMocks(); - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); - - it("returns files and directories relative to cwd", async () => { - const cwd = makeTempDir("t3code-workspace-entries-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/index.ts"); - writeFile(cwd, "README.md"); - writeFile(cwd, ".git/HEAD"); - writeFile(cwd, "node_modules/pkg/index.js"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/components"); - assert.include(paths, "src/components/Composer.tsx"); - assert.include(paths, "README.md"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git"))); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules"))); - assert.isFalse(result.truncated); - }); - - it("filters and ranks entries by query", async () => { - const cwd = makeTempDir("t3code-workspace-query-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); - - assert.isAbove(result.entries.length, 0); - assert.isTrue(result.entries.some((entry) => entry.path === "src/components")); - assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))); - }); - - it("supports fuzzy subsequence queries for composer path search", async () => { - const cwd = makeTempDir("t3code-workspace-fuzzy-query-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); - const paths = result.entries.map((entry) => entry.path); - - assert.isAbove(result.entries.length, 0); - assert.include(paths, "src/components"); - assert.include(paths, "src/components/Composer.tsx"); - }); - - it("tracks truncation without sorting every fuzzy match", async () => { - const cwd = makeTempDir("t3code-workspace-fuzzy-limit-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); - - assert.lengthOf(result.entries, 1); - assert.isTrue(result.truncated); - }); - - it("excludes gitignored paths for git repositories", async () => { - const cwd = makeTempDir("t3code-workspace-gitignore-"); - runGit(cwd, ["init"]); - writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n"); - writeFile(cwd, "src/keep.ts", "export {};"); - writeFile(cwd, "ignored.txt", "ignore me"); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.notInclude(paths, "ignored.txt"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/"))); - }); - - it("excludes tracked paths that match ignore rules", async () => { - const cwd = makeTempDir("t3code-workspace-tracked-gitignore-"); - runGit(cwd, ["init"]); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "src/keep.ts", "export {};"); - runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]); - writeFile(cwd, ".gitignore", ".convex/\n"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - }); - - it("excludes .convex in non-git workspaces", async () => { - const cwd = makeTempDir("t3code-workspace-non-git-convex-"); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "src/keep.ts", "export {};"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - }); - - it("deduplicates concurrent index builds for the same cwd", async () => { - const cwd = makeTempDir("t3code-workspace-concurrent-build-"); - writeFile(cwd, "src/components/Composer.tsx"); - - let rootReadCount = 0; - const originalReaddir = fsPromises.readdir.bind(fsPromises); - vi.spyOn(fsPromises, "readdir").mockImplementation((async ( - ...args: Parameters - ) => { - if (args[0] === cwd) { - rootReadCount += 1; - await new Promise((resolve) => setTimeout(resolve, 20)); - } - return originalReaddir(...args); - }) as typeof fsPromises.readdir); - - await Promise.all([ - searchWorkspaceEntries({ cwd, query: "", limit: 100 }), - searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }), - searchWorkspaceEntries({ cwd, query: "src", limit: 100 }), - ]); - - assert.equal(rootReadCount, 1); - }); - - it("limits concurrent directory reads while walking the filesystem", async () => { - const cwd = makeTempDir("t3code-workspace-read-concurrency-"); - for (let index = 0; index < 80; index += 1) { - writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"); - } - - let activeReads = 0; - let peakReads = 0; - const originalReaddir = fsPromises.readdir.bind(fsPromises); - vi.spyOn(fsPromises, "readdir").mockImplementation((async ( - ...args: Parameters - ) => { - const target = args[0]; - if (typeof target === "string" && target.startsWith(cwd)) { - activeReads += 1; - peakReads = Math.max(peakReads, activeReads); - await new Promise((resolve) => setTimeout(resolve, 4)); - try { - return await originalReaddir(...args); - } finally { - activeReads -= 1; - } - } - return originalReaddir(...args); - }) as typeof fsPromises.readdir); - - await searchWorkspaceEntries({ cwd, query: "", limit: 200 }); - - assert.isAtMost(peakReads, 32); - }); -}); diff --git a/apps/server/src/workspaceEntries.ts b/apps/server/src/workspaceEntries.ts deleted file mode 100644 index 684b005e83..0000000000 --- a/apps/server/src/workspaceEntries.ts +++ /dev/null @@ -1,565 +0,0 @@ -import fs from "node:fs/promises"; -import type { Dirent } from "node:fs"; -import path from "node:path"; -import { runProcess } from "./processRunner"; - -import { - ProjectEntry, - ProjectSearchEntriesInput, - ProjectSearchEntriesResult, -} from "@t3tools/contracts"; - -const WORKSPACE_CACHE_TTL_MS = 15_000; -const WORKSPACE_CACHE_MAX_KEYS = 4; -const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; -const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32; -const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; -const IGNORED_DIRECTORY_NAMES = new Set([ - ".git", - ".convex", - "node_modules", - ".next", - ".turbo", - "dist", - "build", - "out", - ".cache", -]); - -interface WorkspaceIndex { - scannedAt: number; - entries: SearchableWorkspaceEntry[]; - truncated: boolean; -} - -interface SearchableWorkspaceEntry extends ProjectEntry { - normalizedPath: string; - normalizedName: string; -} - -interface RankedWorkspaceEntry { - entry: SearchableWorkspaceEntry; - score: number; -} - -const workspaceIndexCache = new Map(); -const inFlightWorkspaceIndexBuilds = new Map>(); - -function toPosixPath(input: string): string { - return input.split(path.sep).join("/"); -} - -function parentPathOf(input: string): string | undefined { - const separatorIndex = input.lastIndexOf("/"); - if (separatorIndex === -1) { - return undefined; - } - return input.slice(0, separatorIndex); -} - -function basenameOf(input: string): string { - const separatorIndex = input.lastIndexOf("/"); - if (separatorIndex === -1) { - return input; - } - return input.slice(separatorIndex + 1); -} - -function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry { - const normalizedPath = entry.path.toLowerCase(); - return { - ...entry, - normalizedPath, - normalizedName: basenameOf(normalizedPath), - }; -} - -function normalizeQuery(input: string): string { - return input - .trim() - .replace(/^[@./]+/, "") - .toLowerCase(); -} - -function scoreSubsequenceMatch(value: string, query: string): number | null { - if (!query) return 0; - - let queryIndex = 0; - let firstMatchIndex = -1; - let previousMatchIndex = -1; - let gapPenalty = 0; - - for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) { - if (value[valueIndex] !== query[queryIndex]) { - continue; - } - - if (firstMatchIndex === -1) { - firstMatchIndex = valueIndex; - } - if (previousMatchIndex !== -1) { - gapPenalty += valueIndex - previousMatchIndex - 1; - } - - previousMatchIndex = valueIndex; - queryIndex += 1; - if (queryIndex === query.length) { - const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length; - const lengthPenalty = Math.min(64, value.length - query.length); - return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty; - } - } - - return null; -} - -function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null { - if (!query) { - return entry.kind === "directory" ? 0 : 1; - } - - const { normalizedPath, normalizedName } = entry; - - if (normalizedName === query) return 0; - if (normalizedPath === query) return 1; - if (normalizedName.startsWith(query)) return 2; - if (normalizedPath.startsWith(query)) return 3; - if (normalizedPath.includes(`/${query}`)) return 4; - if (normalizedName.includes(query)) return 5; - if (normalizedPath.includes(query)) return 6; - - const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); - if (nameFuzzyScore !== null) { - return 100 + nameFuzzyScore; - } - - const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query); - if (pathFuzzyScore !== null) { - return 200 + pathFuzzyScore; - } - - return null; -} - -function compareRankedWorkspaceEntries( - left: RankedWorkspaceEntry, - right: RankedWorkspaceEntry, -): number { - const scoreDelta = left.score - right.score; - if (scoreDelta !== 0) return scoreDelta; - return left.entry.path.localeCompare(right.entry.path); -} - -function findInsertionIndex( - rankedEntries: RankedWorkspaceEntry[], - candidate: RankedWorkspaceEntry, -): number { - let low = 0; - let high = rankedEntries.length; - - while (low < high) { - const middle = low + Math.floor((high - low) / 2); - const current = rankedEntries[middle]; - if (!current) { - break; - } - - if (compareRankedWorkspaceEntries(candidate, current) < 0) { - high = middle; - } else { - low = middle + 1; - } - } - - return low; -} - -function insertRankedEntry( - rankedEntries: RankedWorkspaceEntry[], - candidate: RankedWorkspaceEntry, - limit: number, -): void { - if (limit <= 0) { - return; - } - - const insertionIndex = findInsertionIndex(rankedEntries, candidate); - if (rankedEntries.length < limit) { - rankedEntries.splice(insertionIndex, 0, candidate); - return; - } - - if (insertionIndex >= limit) { - return; - } - - rankedEntries.splice(insertionIndex, 0, candidate); - rankedEntries.pop(); -} - -function isPathInIgnoredDirectory(relativePath: string): boolean { - const firstSegment = relativePath.split("/")[0]; - if (!firstSegment) return false; - return IGNORED_DIRECTORY_NAMES.has(firstSegment); -} - -function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { - const parts = input.split("\0"); - if (parts.length === 0) return []; - - // If output was truncated, the final token can be partial. - if (truncated && parts[parts.length - 1]?.length) { - parts.pop(); - } - - return parts.filter((value) => value.length > 0); -} - -function directoryAncestorsOf(relativePath: string): string[] { - const segments = relativePath.split("/").filter((segment) => segment.length > 0); - if (segments.length <= 1) return []; - const directories: string[] = []; - for (let index = 1; index < segments.length; index += 1) { - directories.push(segments.slice(0, index).join("/")); - } - return directories; -} - -async function mapWithConcurrency( - items: readonly TInput[], - concurrency: number, - mapper: (item: TInput, index: number) => Promise, -): Promise { - if (items.length === 0) { - return []; - } - - const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length)); - const results = Array.from({ length: items.length }) as TOutput[]; - let nextIndex = 0; - - const workers = Array.from({ length: boundedConcurrency }, async () => { - while (nextIndex < items.length) { - const currentIndex = nextIndex; - nextIndex += 1; - results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex); - } - }); - - await Promise.all(workers); - return results; -} - -async function isInsideGitWorkTree(cwd: string): Promise { - const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], { - cwd, - allowNonZeroExit: true, - timeoutMs: 5_000, - maxBufferBytes: 4_096, - }).catch(() => null); - return Boolean( - insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true", - ); -} - -async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise { - if (relativePaths.length === 0) { - return relativePaths; - } - - const ignoredPaths = new Set(); - let chunk: string[] = []; - let chunkBytes = 0; - - const flushChunk = async (): Promise => { - if (chunk.length === 0) { - return true; - } - - const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], { - cwd, - allowNonZeroExit: true, - timeoutMs: 20_000, - maxBufferBytes: 16 * 1024 * 1024, - outputMode: "truncate", - stdin: `${chunk.join("\0")}\0`, - }).catch(() => null); - chunk = []; - chunkBytes = 0; - - if (!checkIgnore) { - return false; - } - - // git-check-ignore exits with 1 when no paths match. - if (checkIgnore.code !== 0 && checkIgnore.code !== 1) { - return false; - } - - const matchedIgnoredPaths = splitNullSeparatedPaths( - checkIgnore.stdout, - Boolean(checkIgnore.stdoutTruncated), - ); - for (const ignoredPath of matchedIgnoredPaths) { - ignoredPaths.add(ignoredPath); - } - return true; - }; - - for (const relativePath of relativePaths) { - const relativePathBytes = Buffer.byteLength(relativePath) + 1; - if ( - chunk.length > 0 && - chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES && - !(await flushChunk()) - ) { - return relativePaths; - } - - chunk.push(relativePath); - chunkBytes += relativePathBytes; - - if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) { - return relativePaths; - } - } - - if (!(await flushChunk())) { - return relativePaths; - } - - if (ignoredPaths.size === 0) { - return relativePaths; - } - - return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); -} - -async function buildWorkspaceIndexFromGit(cwd: string): Promise { - if (!(await isInsideGitWorkTree(cwd))) { - return null; - } - - const listedFiles = await runProcess( - "git", - ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], - { - cwd, - allowNonZeroExit: true, - timeoutMs: 20_000, - maxBufferBytes: 16 * 1024 * 1024, - outputMode: "truncate", - }, - ).catch(() => null); - if (!listedFiles || listedFiles.code !== 0) { - return null; - } - - const listedPaths = splitNullSeparatedPaths( - listedFiles.stdout, - Boolean(listedFiles.stdoutTruncated), - ) - .map((entry) => toPosixPath(entry)) - .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); - const filePaths = await filterGitIgnoredPaths(cwd, listedPaths); - - const directorySet = new Set(); - for (const filePath of filePaths) { - for (const directoryPath of directoryAncestorsOf(filePath)) { - if (!isPathInIgnoredDirectory(directoryPath)) { - directorySet.add(directoryPath); - } - } - } - - const directoryEntries = [...directorySet] - .toSorted((left, right) => left.localeCompare(right)) - .map( - (directoryPath): ProjectEntry => ({ - path: directoryPath, - kind: "directory", - parentPath: parentPathOf(directoryPath), - }), - ) - .map(toSearchableWorkspaceEntry); - const fileEntries = [...new Set(filePaths)] - .toSorted((left, right) => left.localeCompare(right)) - .map( - (filePath): ProjectEntry => ({ - path: filePath, - kind: "file", - parentPath: parentPathOf(filePath), - }), - ) - .map(toSearchableWorkspaceEntry); - - const entries = [...directoryEntries, ...fileEntries]; - return { - scannedAt: Date.now(), - entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES), - truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES, - }; -} - -async function buildWorkspaceIndex(cwd: string): Promise { - const gitIndexed = await buildWorkspaceIndexFromGit(cwd); - if (gitIndexed) { - return gitIndexed; - } - const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd); - - let pendingDirectories: string[] = [""]; - const entries: SearchableWorkspaceEntry[] = []; - let truncated = false; - - while (pendingDirectories.length > 0 && !truncated) { - const currentDirectories = pendingDirectories; - pendingDirectories = []; - const directoryEntries = await mapWithConcurrency( - currentDirectories, - WORKSPACE_SCAN_READDIR_CONCURRENCY, - async (relativeDir) => { - const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd; - try { - const dirents = await fs.readdir(absoluteDir, { withFileTypes: true }); - return { relativeDir, dirents }; - } catch (error) { - if (!relativeDir) { - throw new Error( - `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`, - { cause: error }, - ); - } - return { relativeDir, dirents: null }; - } - }, - ); - - const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => { - const { relativeDir, dirents } = directoryEntry; - if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>; - - dirents.sort((left, right) => left.name.localeCompare(right.name)); - const candidates: Array<{ dirent: Dirent; relativePath: string }> = []; - for (const dirent of dirents) { - if (!dirent.name || dirent.name === "." || dirent.name === "..") { - continue; - } - if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) { - continue; - } - if (!dirent.isDirectory() && !dirent.isFile()) { - continue; - } - - const relativePath = toPosixPath( - relativeDir ? path.join(relativeDir, dirent.name) : dirent.name, - ); - if (isPathInIgnoredDirectory(relativePath)) { - continue; - } - candidates.push({ dirent, relativePath }); - } - return candidates; - }); - - const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) => - candidateEntries.map((entry) => entry.relativePath), - ); - const allowedPathSet = shouldFilterWithGitIgnore - ? new Set(await filterGitIgnoredPaths(cwd, candidatePaths)) - : null; - - for (const candidateEntries of candidateEntriesByDirectory) { - for (const candidate of candidateEntries) { - if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) { - continue; - } - - const entry = toSearchableWorkspaceEntry({ - path: candidate.relativePath, - kind: candidate.dirent.isDirectory() ? "directory" : "file", - parentPath: parentPathOf(candidate.relativePath), - }); - entries.push(entry); - - if (candidate.dirent.isDirectory()) { - pendingDirectories.push(candidate.relativePath); - } - - if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) { - truncated = true; - break; - } - } - - if (truncated) { - break; - } - } - } - - return { - scannedAt: Date.now(), - entries, - truncated, - }; -} - -async function getWorkspaceIndex(cwd: string): Promise { - const cached = workspaceIndexCache.get(cwd); - if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) { - return cached; - } - - const inFlight = inFlightWorkspaceIndexBuilds.get(cwd); - if (inFlight) { - return inFlight; - } - - const nextPromise = buildWorkspaceIndex(cwd) - .then((next) => { - workspaceIndexCache.set(cwd, next); - while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) { - const oldestKey = workspaceIndexCache.keys().next().value; - if (!oldestKey) break; - workspaceIndexCache.delete(oldestKey); - } - return next; - }) - .finally(() => { - inFlightWorkspaceIndexBuilds.delete(cwd); - }); - inFlightWorkspaceIndexBuilds.set(cwd, nextPromise); - return nextPromise; -} - -export function clearWorkspaceIndexCache(cwd: string): void { - workspaceIndexCache.delete(cwd); - inFlightWorkspaceIndexBuilds.delete(cwd); -} - -export async function searchWorkspaceEntries( - input: ProjectSearchEntriesInput, -): Promise { - const index = await getWorkspaceIndex(input.cwd); - const normalizedQuery = normalizeQuery(input.query); - const limit = Math.max(0, Math.floor(input.limit)); - const rankedEntries: RankedWorkspaceEntry[] = []; - let matchedEntryCount = 0; - - for (const entry of index.entries) { - const score = scoreEntry(entry, normalizedQuery); - if (score === null) { - continue; - } - - matchedEntryCount += 1; - insertRankedEntry(rankedEntries, { entry, score }, limit); - } - - return { - entries: rankedEntries.map((candidate) => candidate.entry), - truncated: index.truncated || matchedEntryCount > limit, - }; -} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts new file mode 100644 index 0000000000..cff7e26efa --- /dev/null +++ b/apps/server/src/ws.ts @@ -0,0 +1,343 @@ +import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; +import { + type GitActionProgressEvent, + type GitManagerServiceError, + OrchestrationDispatchCommandError, + type OrchestrationEvent, + OrchestrationGetFullThreadDiffError, + OrchestrationGetSnapshotError, + OrchestrationGetTurnDiffError, + ORCHESTRATION_WS_METHODS, + ProjectSearchEntriesError, + ProjectWriteFileError, + OrchestrationReplayEventsError, + type TerminalEvent, + WS_METHODS, + WsRpcGroup, +} from "@t3tools/contracts"; +import { clamp } from "effect/Number"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; + +import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; +import { ServerConfig } from "./config"; +import { GitCore } from "./git/Services/GitCore"; +import { GitManager } from "./git/Services/GitManager"; +import { Keybindings } from "./keybindings"; +import { Open, resolveAvailableEditors } from "./open"; +import { normalizeDispatchCommand } from "./orchestration/Normalizer"; +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { ProviderRegistry } from "./provider/Services/ProviderRegistry"; +import { ServerLifecycleEvents } from "./serverLifecycleEvents"; +import { ServerRuntimeStartup } from "./serverRuntimeStartup"; +import { ServerSettingsService } from "./serverSettings"; +import { TerminalManager } from "./terminal/Services/Manager"; +import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries"; +import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem"; +import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths"; + +const WsRpcLayer = WsRpcGroup.toLayer( + Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const checkpointDiffQuery = yield* CheckpointDiffQuery; + const keybindings = yield* Keybindings; + const open = yield* Open; + const gitManager = yield* GitManager; + const git = yield* GitCore; + const terminalManager = yield* TerminalManager; + const providerRegistry = yield* ProviderRegistry; + const config = yield* ServerConfig; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + const startup = yield* ServerRuntimeStartup; + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + + const loadServerConfig = Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.loadConfigState; + const providers = yield* providerRegistry.getProviders; + const settings = yield* serverSettings.getSettings; + + return { + cwd: config.cwd, + keybindingsConfigPath: config.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers, + availableEditors: resolveAvailableEditors(), + settings, + }; + }); + + return WsRpcGroup.of({ + [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => + projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot", + cause, + }), + ), + ), + [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => + Effect.gen(function* () { + const normalizedCommand = yield* normalizeDispatchCommand(command); + return yield* startup.enqueueCommand(orchestrationEngine.dispatch(normalizedCommand)); + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command", + cause, + }), + ), + ), + [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), + ), + [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), + ), + [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }), + ), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.mapError( + (cause) => + new OrchestrationReplayEventsError({ + message: "Failed to replay orchestration events", + cause, + }), + ), + ), + [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => + Stream.unwrap( + Effect.gen(function* () { + const snapshot = yield* orchestrationEngine.getReadModel(); + const fromSequenceExclusive = snapshot.snapshotSequence; + const replayEvents: Array = yield* Stream.runCollect( + orchestrationEngine.readEvents(fromSequenceExclusive), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.catch(() => Effect.succeed([] as Array)), + ); + const replayStream = Stream.fromIterable(replayEvents); + const source = Stream.merge(replayStream, orchestrationEngine.streamDomainEvents); + type SequenceState = { + readonly nextSequence: number; + readonly pendingBySequence: Map; + }; + const state = yield* Ref.make({ + nextSequence: fromSequenceExclusive + 1, + pendingBySequence: new Map(), + }); + + return source.pipe( + Stream.mapEffect((event) => + Ref.modify( + state, + ({ + nextSequence, + pendingBySequence, + }): [Array, SequenceState] => { + if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) { + return [[], { nextSequence, pendingBySequence }]; + } + + const updatedPending = new Map(pendingBySequence); + updatedPending.set(event.sequence, event); + + const emit: Array = []; + let expected = nextSequence; + for (;;) { + const expectedEvent = updatedPending.get(expected); + if (!expectedEvent) { + break; + } + emit.push(expectedEvent); + updatedPending.delete(expected); + expected += 1; + } + + return [emit, { nextSequence: expected, pendingBySequence: updatedPending }]; + }, + ), + ), + Stream.flatMap((events) => Stream.fromIterable(events)), + ); + }), + ), + [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig, + [WS_METHODS.serverRefreshProviders]: (_input) => + providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + [WS_METHODS.serverUpsertKeybinding]: (rule) => + Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); + return { keybindings: keybindingsConfig, issues: [] }; + }), + [WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings, + [WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch), + [WS_METHODS.projectsSearchEntries]: (input) => + workspaceEntries.search(input).pipe( + Effect.mapError( + (cause) => + new ProjectSearchEntriesError({ + message: `Failed to search workspace entries: ${cause.detail}`, + cause, + }), + ), + ), + [WS_METHODS.projectsWriteFile]: (input) => + workspaceFileSystem.writeFile(input).pipe( + Effect.mapError((cause) => { + const message = Schema.is(WorkspacePathOutsideRootError)(cause) + ? "Workspace file path must stay within the project root." + : "Failed to write workspace file"; + return new ProjectWriteFileError({ + message, + cause, + }); + }), + ), + [WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input), + [WS_METHODS.gitStatus]: (input) => gitManager.status(input), + [WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd), + [WS_METHODS.gitRunStackedAction]: (input) => + Stream.callback((queue) => + gitManager + .runStackedAction(input, { + actionId: input.actionId, + progressReporter: { + publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), + }, + }) + .pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Queue.failCause(queue, cause), + onSuccess: () => Queue.end(queue).pipe(Effect.asVoid), + }), + ), + ), + [WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input), + [WS_METHODS.gitPreparePullRequestThread]: (input) => + gitManager.preparePullRequestThread(input), + [WS_METHODS.gitListBranches]: (input) => git.listBranches(input), + [WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input), + [WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input), + [WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input), + [WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)), + [WS_METHODS.gitInit]: (input) => git.initRepo(input), + [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), + [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), + [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input), + [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), + [WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input), + [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), + [WS_METHODS.subscribeTerminalEvents]: (_input) => + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event) => Queue.offer(queue, event)), + (unsubscribe) => Effect.sync(unsubscribe), + ), + ), + [WS_METHODS.subscribeServerConfig]: (_input) => + Stream.unwrap( + Effect.gen(function* () { + const keybindingsUpdates = keybindings.streamChanges.pipe( + Stream.map((event) => ({ + version: 1 as const, + type: "keybindingsUpdated" as const, + payload: { + issues: event.issues, + }, + })), + ); + const providerStatuses = providerRegistry.streamChanges.pipe( + Stream.map((providers) => ({ + version: 1 as const, + type: "providerStatuses" as const, + payload: { providers }, + })), + ); + const settingsUpdates = serverSettings.streamChanges.pipe( + Stream.map((settings) => ({ + version: 1 as const, + type: "settingsUpdated" as const, + payload: { settings }, + })), + ); + + return Stream.concat( + Stream.make({ + version: 1 as const, + type: "snapshot" as const, + config: yield* loadServerConfig, + }), + Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)), + ); + }), + ), + [WS_METHODS.subscribeServerLifecycle]: (_input) => + Stream.unwrap( + Effect.gen(function* () { + const snapshot = yield* lifecycleEvents.snapshot; + const snapshotEvents = Array.from(snapshot.events).toSorted( + (left, right) => left.sequence - right.sequence, + ); + const liveEvents = lifecycleEvents.stream.pipe( + Stream.filter((event) => event.sequence > snapshot.sequence), + ); + return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents); + }), + ), + }); + }), +); + +export const websocketRpcRouteLayer = Layer.unwrap( + Effect.gen(function* () { + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe( + Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)), + ); + return HttpRouter.add( + "GET", + "/ws", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const config = yield* ServerConfig; + if (config.authToken) { + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 }); + } + const token = url.value.searchParams.get("token"); + if (token !== config.authToken) { + return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 }); + } + } + return yield* rpcWebSocketHttpEffect; + }), + ); + }), +); diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts deleted file mode 100644 index 0e06650fe6..0000000000 --- a/apps/server/src/wsServer.test.ts +++ /dev/null @@ -1,1969 +0,0 @@ -import * as Http from "node:http"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect"; -import { describe, expect, it, afterEach, vi } from "vitest"; -import { createServer } from "./wsServer"; -import WebSocket from "ws"; -import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config"; -import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers"; - -import { - DEFAULT_TERMINAL_ID, - DEFAULT_SERVER_SETTINGS, - EDITORS, - EventId, - ORCHESTRATION_WS_CHANNELS, - ORCHESTRATION_WS_METHODS, - ProviderItemId, - type ServerSettings, - ThreadId, - TurnId, - WS_CHANNELS, - WS_METHODS, - type WebSocketResponse, - type ProviderRuntimeEvent, - type ServerProvider, - type KeybindingsConfig, - type ResolvedKeybindingsConfig, - type WsPushChannel, - type WsPushMessage, - type WsPush, -} 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 { ProviderRegistry, type ProviderRegistryShape } from "./provider/Services/ProviderRegistry"; -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"; -import { ServerSettingsService } from "./serverSettings.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, -}; - -const defaultProviderStatuses: ReadonlyArray = [ - { - provider: "codex", - enabled: true, - installed: true, - version: "0.116.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-01-01T00:00:00.000Z", - models: [], - }, -]; - -const defaultProviderRegistryService: ProviderRegistryShape = { - getProviders: Effect.succeed(defaultProviderStatuses), - refresh: () => Effect.succeed(defaultProviderStatuses), - streamChanges: Stream.empty, -}; - -const defaultServerSettings = DEFAULT_SERVER_SETTINGS; - -class MockTerminalManager implements TerminalManagerShape { - private readonly sessions = new Map(); - private readonly eventPubSub = Effect.runSync(PubSub.unbounded()); - private activeSubscriptions = 0; - - private key(threadId: string, terminalId: string): string { - return `${threadId}\u0000${terminalId}`; - } - - emitEvent(event: TerminalEvent): void { - Effect.runSync(PubSub.publish(this.eventPubSub, event)); - } - - subscriptionCount(): number { - return this.activeSubscriptions; - } - - readonly open: TerminalManagerShape["open"] = (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: 4242, - history: "", - exitCode: null, - exitSignal: null, - updatedAt: now, - }; - this.sessions.set(this.key(input.threadId, terminalId), snapshot); - queueMicrotask(() => { - this.emitEvent({ - type: "started", - threadId: input.threadId, - terminalId, - createdAt: now, - snapshot, - }); - }); - return snapshot; - }); - - 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}`); - } - queueMicrotask(() => { - this.emitEvent({ - type: "output", - threadId: input.threadId, - terminalId, - createdAt: new Date().toISOString(), - data: input.data, - }); - }); - }); - - 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 subscribe: TerminalManagerShape["subscribe"] = (listener) => - Effect.sync(() => { - this.activeSubscriptions += 1; - const fiber = Effect.runFork( - Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)), - ); - return () => { - this.activeSubscriptions -= 1; - Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore)); - }; - }); -} - -// --------------------------------------------------------------------------- -// 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. -// --------------------------------------------------------------------------- - -interface MessageChannel { - queue: T[]; - waiters: Array<{ - resolve: (value: T) => void; - reject: (error: Error) => void; - timeoutId: ReturnType | null; - }>; -} - -interface SocketChannels { - push: MessageChannel; - response: MessageChannel; -} - -const channelsBySocket = new WeakMap(); - -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); - } - } - }); - - ws.once("open", () => resolve(ws)); - ws.once("error", () => reject(new Error("WebSocket connection failed"))); - }); -} - -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); - } -} - -function ensureParentDir(filePath: string): void { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); -} - -function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) { - return Effect.runSync( - deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)), - ); -} - -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; - baseDir?: string; - staticDir?: string; - providerLayer?: Layer.Layer; - providerRegistry?: ProviderRegistryShape; - open?: OpenShape; - gitManager?: GitManagerShape; - gitCore?: Pick; - terminalManager?: TerminalManagerShape; - serverSettings?: Partial; - } = {}, - ): Promise { - if (serverScope) { - throw new Error("Test server is already running"); - } - - const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-"); - const devUrl = options.devUrl ? new URL(options.devUrl) : undefined; - const derivedPaths = deriveServerPathsSync(baseDir, devUrl); - const scope = await Effect.runPromise(Scope.make("sequential")); - const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory; - const providerLayer = options.providerLayer ?? makeServerProviderLayer(); - const providerRegistryLayer = Layer.succeed( - ProviderRegistry, - options.providerRegistry ?? defaultProviderRegistryService, - ); - const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService); - const serverConfigLayer = Layer.succeed(ServerConfig, { - mode: "web", - port: 0, - host: undefined, - cwd: options.cwd ?? "/test/project", - baseDir, - ...derivedPaths, - staticDir: options.staticDir, - devUrl, - 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, - ); - - const runtimeLayer = Layer.merge( - Layer.merge( - makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)), - infrastructureLayer, - ), - runtimeOverrides, - ); - const dependenciesLayer = Layer.empty.pipe( - Layer.provideMerge(runtimeLayer), - Layer.provideMerge(providerRegistryLayer), - Layer.provideMerge(openLayer), - Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)), - 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; - } - } - - async function closeTestServer() { - if (!serverScope) return; - const scope = serverScope; - serverScope = null; - await Effect.runPromise(Scope.close(scope, Exit.void)); - } - - afterEach(async () => { - for (const ws of connections) { - ws.close(); - } - connections.length = 0; - await closeTestServer(); - server = null; - 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 baseDir = makeTempDir("t3code-state-attachments-"); - const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined); - const attachmentPath = path.join(attachmentsDir, "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", baseDir }); - 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 baseDir = makeTempDir("t3code-state-attachments-encoded-"); - const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined); - const attachmentPath = path.join( - attachmentsDir, - "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", baseDir }); - 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 baseDir = 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", baseDir, 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 baseDir = 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", baseDir, 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; - defaultModelSelection: { - provider: string; - model: string; - } | null; - }>; - threads: Array<{ - id: string; - projectId: string; - title: string; - modelSelection: { - provider: 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", - defaultModelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - }), - ]), - ); - expect(snapshot.threads).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - id: bootstrapThreadId, - projectId: bootstrapProjectId, - title: "New thread", - modelSelection: { - provider: "codex", - model: "gpt-5-codex", - }, - branch: null, - worktreePath: null, - }), - ]), - ); - }); - - it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => { - const baseDir = makeTempDir("t3code-state-bootstrap-existing-"); - const { dbPath } = deriveServerPathsSync(baseDir, undefined); - const persistenceLayer = makeSqlitePersistenceLive(dbPath).pipe( - Layer.provide(NodeServices.layer), - ); - const cwd = "/test/bootstrap-existing"; - - server = await createTestServer({ - cwd, - baseDir, - 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, - baseDir, - 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 baseDir = makeTempDir("t3code-state-get-config-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - fs.writeFileSync(keybindingsPath, "[]", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", baseDir }); - 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), - settings: defaultServerSettings, - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - }); - - it("bootstraps default keybindings file when missing", async () => { - const baseDir = makeTempDir("t3code-state-bootstrap-keybindings-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - expect(fs.existsSync(keybindingsPath)).toBe(false); - - server = await createTestServer({ cwd: "/my/workspace", baseDir }); - 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), - settings: defaultServerSettings, - }); - 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 baseDir = makeTempDir("t3code-state-malformed-keybindings-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - fs.writeFileSync(keybindingsPath, "{ not-json", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", baseDir }); - 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: [ - { - kind: "keybindings.malformed-config", - message: expect.stringContaining("expected JSON array"), - }, - ], - providers: defaultProviderStatuses, - availableEditors: expect.any(Array), - settings: defaultServerSettings, - }); - 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 baseDir = makeTempDir("t3code-state-partial-invalid-keybindings-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - 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", baseDir }); - 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 baseDir = makeTempDir("t3code-state-keybindings-watch-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - fs.writeFileSync(keybindingsPath, "[]", "utf8"); - - server = await createTestServer({ cwd: "/my/workspace", baseDir }); - 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) }], - }); - - const successPush = await rewriteKeybindingsAndWaitForPush( - ws, - keybindingsPath, - "[]", - (push) => Array.isArray(push.data.issues) && push.data.issues.length === 0, - ); - expect(successPush.data).toEqual({ issues: [] }); - }); - - 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 baseDir = makeTempDir("t3code-state-keybindings-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - 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", baseDir }); - 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), - settings: defaultServerSettings, - }); - expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors); - }); - - it("upserts keybinding rules and updates cached server config", async () => { - const baseDir = makeTempDir("t3code-state-upsert-keybinding-"); - const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined); - ensureParentDir(keybindingsPath); - fs.writeFileSync( - keybindingsPath, - JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), - "utf8", - ); - - server = await createTestServer({ cwd: "/my/workspace", baseDir }); - 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), - settings: defaultServerSettings, - }); - 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, - defaultModelSelection: { - provider: "codex", - model: "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", - modelSelection: { - provider: "codex", - 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, - serverSettings: { enableAssistantStreaming: true }, - }); - 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, - defaultModelSelection: { - provider: "codex", - model: "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", - modelSelection: { - provider: "codex", - 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: [], - }, - 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("shuts down cleanly for injected terminal managers", async () => { - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - - await closeTestServer(); - server = null; - - expect(() => - terminalManager.emitEvent({ - type: "output", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - createdAt: new Date().toISOString(), - data: "after shutdown\n", - }), - ).not.toThrow(); - }); - - 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", - }), - ]), - }), - ); - } 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.", - }), - ), - ); - 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, { - actionId: "client-action-1", - cwd: "/test", - action: "commit_push", - modelSelection: { - provider: "codex", - model: "gpt-5.4-mini", - }, - }); - expect(response.result).toBeUndefined(); - expect(response.error?.message).toContain("detached HEAD"); - expect(runStackedAction).toHaveBeenCalledWith( - { - actionId: "client-action-1", - cwd: "/test", - action: "commit_push", - }, - expect.objectContaining({ - actionId: "client-action-1", - progressReporter: expect.any(Object), - }), - ); - }); - - it("publishes git action progress only to the initiating websocket", async () => { - const runStackedAction = vi.fn( - (_input, options) => - options?.progressReporter - ?.publish({ - actionId: options.actionId ?? "action-1", - cwd: "/test", - action: "commit", - kind: "phase_started", - phase: "commit", - label: "Committing...", - }) - .pipe( - Effect.flatMap(() => - Effect.succeed({ - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc1234", - subject: "Test commit", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - }), - ), - ) ?? Effect.void, - ); - 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 [initiatingWs] = await connectAndAwaitWelcome(port); - const [otherWs] = await connectAndAwaitWelcome(port); - connections.push(initiatingWs, otherWs); - - const responsePromise = sendRequest(initiatingWs, WS_METHODS.gitRunStackedAction, { - actionId: "client-action-2", - cwd: "/test", - action: "commit", - modelSelection: { - provider: "codex", - model: "gpt-5.4-mini", - }, - }); - const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress); - - expect(progressPush.data).toEqual({ - actionId: "client-action-2", - cwd: "/test", - action: "commit", - kind: "phase_started", - phase: "commit", - label: "Committing...", - }); - - await expect( - waitForPush(otherWs, WS_CHANNELS.gitActionProgress, undefined, 10, 100), - ).rejects.toThrow("Timed out waiting for WebSocket message after 100ms"); - await expect(responsePromise).resolves.toEqual( - expect.objectContaining({ - result: expect.objectContaining({ - action: "commit", - }), - }), - ); - }); - - 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; - - await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed"); - - const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token"); - connections.push(authorizedWs); - }); -}); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts deleted file mode 100644 index 25f8158926..0000000000 --- a/apps/server/src/wsServer.ts +++ /dev/null @@ -1,1060 +0,0 @@ -/** - * 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 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 { createLogger } from "./logger"; -import { GitManager } from "./git/Services/GitManager.ts"; -import { TerminalManager } from "./terminal/Services/Manager.ts"; -import { Keybindings } from "./keybindings"; -import { ServerSettingsService } from "./serverSettings"; -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 { ProviderRegistry } from "./provider/Services/ProviderRegistry"; -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 { - 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"; - -/** - * 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 - >; - - /** - * 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") - ); -}; - -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, - ); -} - -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; -} - -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 - | ProviderRegistry; - -export type ServerRuntimeServices = - | ServerCoreRuntimeServices - | GitManager - | GitCore - | TerminalManager - | Keybindings - | ServerSettingsService - | 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 runtimeServices = yield* Effect.services< - ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path - >(); - const runPromise = Effect.runPromiseWith(runtimeServices); - - const gitManager = yield* GitManager; - const terminalManager = yield* TerminalManager; - const keybindingsManager = yield* Keybindings; - const serverSettingsManager = yield* ServerSettingsService; - const providerRegistry = yield* ProviderRegistry; - 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 providersRef = yield* Ref.make(yield* providerRegistry.getProviders); - - 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; - yield* serverSettingsManager.start.pipe( - Effect.mapError( - (cause) => new ServerLifecycleError({ operation: "serverSettingsRuntimeStart", cause }), - ), - ); - - 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 (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) { - return { - ...input.command, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot), - } satisfies OrchestrationCommand; - } - - 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({ - attachmentsDir: serverConfig.attachmentsDir, - 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 runPromise( - Effect.gen(function* () { - const url = new URL(req.url ?? "/", `http://localhost:${port}`); - if (tryHandleProjectFaviconRequest(url, res)) { - return; - } - - 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 isIdLookup = - !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes("."); - const filePath = isIdLookup - ? resolveAttachmentPathById({ - attachmentsDir: serverConfig.attachmentsDir, - attachmentId: normalizedRelativePath, - }) - : resolveAttachmentRelativePath({ - attachmentsDir: serverConfig.attachmentsDir, - relativePath: normalizedRelativePath, - }); - if (!filePath) { - respond( - isIdLookup ? 404 : 400, - { "Content-Type": "text/plain" }, - isIdLookup ? "Not Found" : "Invalid attachment path", - ); - return; - } - - 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; - } - - const contentType = Mime.getType(filePath) ?? "application/octet-stream"; - res.writeHead(200, { - "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; - } - - // In dev mode, redirect to Vite dev server - if (devUrl) { - respond(302, { Location: devUrl.href }); - return; - } - - // 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; - } - - const staticRoot = path.resolve(staticDir); - const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname; - const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, ""); - 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; - } - - const isWithinStaticRoot = (candidate: string) => - candidate === staticRoot || - candidate.startsWith( - staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`, - ); - - let filePath = path.resolve(staticRoot, staticRelativePath); - if (!isWithinStaticRoot(filePath)) { - respond(400, { "Content-Type": "text/plain" }, "Invalid static file path"); - return; - } - - 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; - } - } - - const fileInfo = yield* fileSystem - .stat(filePath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - const indexPath = path.resolve(staticRoot, "index.html"); - const indexData = yield* fileSystem - .readFile(indexPath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!indexData) { - respond(404, { "Content-Type": "text/plain" }, "Not Found"); - return; - } - respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData); - return; - } - - const contentType = Mime.getType(filePath) ?? "application/octet-stream"; - const data = yield* fileSystem - .readFile(filePath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!data) { - respond(500, { "Content-Type": "text/plain" }, "Internal Server Error"); - return; - } - respond(200, { "Content-Type": contentType }, data); - }), - ).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, - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) => - pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: [], - settings, - }), - ).pipe(Effect.forkIn(subscriptionsScope)); - - yield* Stream.runForEach(providerRegistry.streamChanges, (providers) => - Effect.gen(function* () { - yield* Ref.set(providersRef, providers); - yield* pushBus.publishAll(WS_CHANNELS.serverProvidersUpdated, { - providers, - }); - }), - ).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 bootstrapProjectDefaultModelSelection; - - if (!existingProject) { - const createdAt = new Date().toISOString(); - bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); - const bootstrapProjectTitle = path.basename(cwd) || "project"; - bootstrapProjectDefaultModelSelection = { - provider: "codex" as const, - model: "gpt-5-codex", - }; - yield* orchestrationEngine.dispatch({ - type: "project.create", - commandId: CommandId.makeUnsafe(crypto.randomUUID()), - projectId: bootstrapProjectId, - title: bootstrapProjectTitle, - workspaceRoot: cwd, - defaultModelSelection: bootstrapProjectDefaultModelSelection, - createdAt, - }); - } else { - bootstrapProjectId = existingProject.id; - bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? { - provider: "codex" as const, - model: "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", - modelSelection: bootstrapProjectDefaultModelSelection, - 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 unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) => - pushBus.publishAll(WS_CHANNELS.terminalEvent, event), - ); - yield* Scope.addFinalizer(subscriptionsScope, 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* (ws: WebSocket, 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, { - actionId: body.actionId, - progressReporter: { - publish: (event) => - pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid), - }, - }); - } - - 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; - const settings = yield* serverSettingsManager.getSettings; - const providers = yield* Ref.get(providersRef); - return { - cwd, - keybindingsConfigPath, - keybindings: keybindingsConfig.keybindings, - issues: keybindingsConfig.issues, - providers, - availableEditors, - settings, - }; - } - - case WS_METHODS.serverRefreshProviders: { - const providers = yield* providerRegistry.refresh(); - yield* Ref.set(providersRef, providers); - return { providers }; - } - - case WS_METHODS.serverUpsertKeybinding: { - const body = stripRequestTag(request.body); - const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body); - return { keybindings: keybindingsConfig, issues: [] }; - } - - case WS_METHODS.serverGetSettings: { - return yield* serverSettingsManager.getSettings; - } - - case WS_METHODS.serverUpdateSettings: { - const body = stripRequestTag(request.body); - return yield* serverSettingsManager.updateSettings(body.patch); - } - - 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(ws, 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 }))); - }); - - 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); diff --git a/apps/server/src/wsServer/pushBus.test.ts b/apps/server/src/wsServer/pushBus.test.ts deleted file mode 100644 index 80e8be2185..0000000000 --- a/apps/server/src/wsServer/pushBus.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import type { WebSocket } from "ws"; -import { it } from "@effect/vitest"; -import { describe, expect } from "vitest"; -import { Effect, Ref } from "effect"; -import { WS_CHANNELS } from "@t3tools/contracts"; - -import { makeServerPushBus } from "./pushBus"; - -class MockWebSocket { - static readonly OPEN = 1; - - readonly OPEN = MockWebSocket.OPEN; - readyState = MockWebSocket.OPEN; - readonly sent: string[] = []; - private readonly waiters = new Set<() => void>(); - - send(message: string) { - this.sent.push(message); - for (const waiter of this.waiters) { - waiter(); - } - } - - waitForSentCount(count: number): Promise { - if (this.sent.length >= count) { - return Promise.resolve(); - } - - return new Promise((resolve) => { - const check = () => { - if (this.sent.length < count) { - return; - } - this.waiters.delete(check); - resolve(); - }; - - this.waiters.add(check); - }); - } -} - -describe("makeServerPushBus", () => { - it.live("waits for the welcome push before a new client joins broadcast delivery", () => - Effect.scoped( - Effect.gen(function* () { - const client = new MockWebSocket(); - const clients = yield* Ref.make(new Set()); - const pushBus = yield* makeServerPushBus({ - clients, - logOutgoingPush: () => {}, - }); - - yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }], - }); - - const delivered = yield* pushBus.publishClient( - client as unknown as WebSocket, - WS_CHANNELS.serverWelcome, - { - cwd: "/tmp/project", - projectName: "project", - }, - ); - expect(delivered).toBe(true); - - yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket)); - - yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, { - issues: [], - }); - - yield* Effect.promise(() => client.waitForSentCount(2)); - - const messages = client.sent.map( - (message) => JSON.parse(message) as { channel: string; data: unknown }, - ); - - expect(messages).toHaveLength(2); - expect(messages[0]).toEqual({ - type: "push", - sequence: 2, - channel: WS_CHANNELS.serverWelcome, - data: { - cwd: "/tmp/project", - projectName: "project", - }, - }); - expect(messages[1]).toEqual({ - type: "push", - sequence: 3, - channel: WS_CHANNELS.serverConfigUpdated, - data: { - issues: [], - }, - }); - }), - ), - ); -}); diff --git a/apps/server/src/wsServer/pushBus.ts b/apps/server/src/wsServer/pushBus.ts deleted file mode 100644 index c2cd302f23..0000000000 --- a/apps/server/src/wsServer/pushBus.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { - WsPush, - type WsPushChannel, - type WsPushData, - type WsPushEnvelopeBase, -} from "@t3tools/contracts"; -import { Deferred, Effect, Queue, Ref, Schema } from "effect"; -import type { Scope } from "effect"; -import type { WebSocket } from "ws"; - -type PushTarget = - | { readonly kind: "all" } - | { readonly kind: "client"; readonly client: WebSocket }; - -interface PushJob { - readonly channel: C; - readonly data: WsPushData; - readonly target: PushTarget; - readonly delivered: Deferred.Deferred | null; -} - -export interface ServerPushBus { - readonly publishAll: ( - channel: C, - data: WsPushData, - ) => Effect.Effect; - readonly publishClient: ( - client: WebSocket, - channel: C, - data: WsPushData, - ) => Effect.Effect; -} - -export const makeServerPushBus = (input: { - readonly clients: Ref.Ref>; - readonly logOutgoingPush: (push: WsPushEnvelopeBase, recipients: number) => void; -}): Effect.Effect => - Effect.gen(function* () { - const nextSequence = yield* Ref.make(0); - const queue = yield* Queue.unbounded(); - const encodePush = Schema.encodeUnknownEffect(Schema.fromJsonString(WsPush)); - - const settleDelivery = (job: PushJob, delivered: boolean) => - job.delivered === null - ? Effect.void - : Deferred.succeed(job.delivered, delivered).pipe(Effect.orDie); - - const send = Effect.fnUntraced(function* (job: PushJob) { - const sequence = yield* Ref.updateAndGet(nextSequence, (current) => current + 1); - const push: WsPushEnvelopeBase = { - type: "push", - sequence, - channel: job.channel, - data: job.data, - }; - const recipients = - job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]); - - return yield* encodePush(push).pipe( - Effect.map((message) => { - let recipientCount = 0; - for (const client of recipients) { - if (client.readyState !== client.OPEN) { - continue; - } - client.send(message); - recipientCount += 1; - } - - input.logOutgoingPush(push, recipientCount); - return recipientCount > 0; - }), - ); - }); - - yield* Effect.forkScoped( - Effect.forever( - Queue.take(queue).pipe( - Effect.flatMap((job) => - send(job).pipe( - Effect.tap((delivered) => settleDelivery(job, delivered)), - Effect.tapCause(() => settleDelivery(job, false)), - Effect.ignoreCause({ log: true }), - ), - ), - ), - ), - ); - - const publish = - (target: PushTarget) => - (channel: C, data: WsPushData) => - Queue.offer(queue, { - channel, - data, - target, - delivered: null, - }).pipe(Effect.asVoid); - - return { - publishAll: publish({ kind: "all" }), - publishClient: (client, channel, data) => - Effect.gen(function* () { - const delivered = yield* Deferred.make(); - yield* Queue.offer(queue, { - channel, - data, - target: { kind: "client", client }, - delivered, - }).pipe(Effect.asVoid); - return yield* Deferred.await(delivered); - }), - } satisfies ServerPushBus; - }); diff --git a/apps/server/src/wsServer/readiness.ts b/apps/server/src/wsServer/readiness.ts deleted file mode 100644 index 2a973a8636..0000000000 --- a/apps/server/src/wsServer/readiness.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Deferred, Effect } from "effect"; - -export interface ServerReadiness { - readonly awaitServerReady: Effect.Effect; - readonly markHttpListening: Effect.Effect; - readonly markPushBusReady: Effect.Effect; - readonly markKeybindingsReady: Effect.Effect; - readonly markTerminalSubscriptionsReady: Effect.Effect; - readonly markOrchestrationSubscriptionsReady: Effect.Effect; -} - -export const makeServerReadiness = Effect.gen(function* () { - const httpListening = yield* Deferred.make(); - const pushBusReady = yield* Deferred.make(); - const keybindingsReady = yield* Deferred.make(); - const terminalSubscriptionsReady = yield* Deferred.make(); - const orchestrationSubscriptionsReady = yield* Deferred.make(); - - const complete = (deferred: Deferred.Deferred) => - Deferred.succeed(deferred, undefined).pipe(Effect.orDie); - - return { - awaitServerReady: Effect.all([ - Deferred.await(httpListening), - Deferred.await(pushBusReady), - Deferred.await(keybindingsReady), - Deferred.await(terminalSubscriptionsReady), - Deferred.await(orchestrationSubscriptionsReady), - ]).pipe(Effect.asVoid), - markHttpListening: complete(httpListening), - markPushBusReady: complete(pushBusReady), - markKeybindingsReady: complete(keybindingsReady), - markTerminalSubscriptionsReady: complete(terminalSubscriptionsReady), - markOrchestrationSubscriptionsReady: complete(orchestrationSubscriptionsReady), - } satisfies ServerReadiness; -}); diff --git a/apps/server/tsdown.config.ts b/apps/server/tsdown.config.ts index f89bc7d3d7..f11dd37869 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, diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts index cb86636fb6..1c5b2f0d38 100644 --- a/apps/server/vitest.config.ts +++ b/apps/server/vitest.config.ts @@ -6,8 +6,13 @@ export default mergeConfig( baseConfig, defineConfig({ test: { - testTimeout: 15_000, - hookTimeout: 15_000, + // The server suite exercises sqlite, git, temp worktrees, and orchestration + // runtimes heavily. Running files in parallel introduces load-sensitive flakes. + fileParallelism: false, + // Server integration tests exercise sqlite, git, and orchestration together. + // Under package-wide parallel runs they regularly exceed the default 15s budget. + testTimeout: 60_000, + hookTimeout: 60_000, }, }), ); diff --git a/apps/web/package.json b/apps/web/package.json index bd0fb9e0ac..499943c3f0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -19,6 +19,7 @@ "@dnd-kit/modifiers": "^9.0.0", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", + "@effect/atom-react": "catalog:", "@formkit/auto-animate": "^0.9.0", "@lexical/react": "^0.41.0", "@pierre/diffs": "^1.1.0-beta.16", diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 20816d6935..33b9b62859 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -4,15 +4,14 @@ import "../index.css"; import { EventId, ORCHESTRATION_WS_METHODS, - ORCHESTRATION_WS_CHANNELS, type MessageId, type OrchestrationEvent, type OrchestrationReadModel, type ProjectId, type ServerConfig, + type ServerLifecycleWelcomePayload, type ThreadId, - type WsWelcomePayload, - WS_CHANNELS, + type TurnId, WS_METHODS, OrchestrationSessionStatus, DEFAULT_SERVER_SETTINGS, @@ -31,8 +30,10 @@ import { removeInlineTerminalContextPlaceholder, } from "../lib/terminalContext"; import { isMacPlatform } from "../lib/utils"; +import { __resetNativeApiForTests } from "../nativeApi"; import { getRouter } from "../router"; import { useStore } from "../store"; +import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness"; import { estimateTimelineMessageHeight } from "./timelineHeight"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; @@ -43,25 +44,16 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z"; const BASE_TIME_MS = Date.parse(NOW_ISO); const ATTACHMENT_SVG = ""; -interface WsRequestEnvelope { - id: string; - body: { - _tag: string; - [key: string]: unknown; - }; -} - interface TestFixture { snapshot: OrchestrationReadModel; serverConfig: ServerConfig; - welcome: WsWelcomePayload; + welcome: ServerLifecycleWelcomePayload; } let fixture: TestFixture; -const wsRequests: WsRequestEnvelope["body"][] = []; -let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null; -let wsClient: { send: (message: string) => void } | null = null; -let pushSequence = 1; +const rpcHarness = new BrowserWsRpcHarness(); +const wsRequests = rpcHarness.requests; +let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null; const wsLink = ws.link(/ws(s)?:\/\/.*/); interface ViewportSpec { @@ -79,6 +71,20 @@ const DEFAULT_VIEWPORT: ViewportSpec = { textTolerancePx: 44, attachmentTolerancePx: 56, }; +const WIDE_FOOTER_VIEWPORT: ViewportSpec = { + name: "wide-footer", + width: 1_400, + height: 1_100, + textTolerancePx: 44, + attachmentTolerancePx: 56, +}; +const COMPACT_FOOTER_VIEWPORT: ViewportSpec = { + name: "compact-footer", + width: 430, + height: 932, + textTolerancePx: 56, + attachmentTolerancePx: 56, +}; const TEXT_VIEWPORT_MATRIX = [ DEFAULT_VIEWPORT, { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 }, @@ -102,6 +108,7 @@ interface MountedChatView { cleanup: () => Promise; measureUserRow: (targetMessageId: MessageId) => Promise; setViewport: (viewport: ViewportSpec) => Promise; + setContainerSize: (viewport: Pick) => Promise; router: ReturnType; } @@ -372,32 +379,20 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest } function sendOrchestrationDomainEvent(event: OrchestrationEvent): void { - if (!wsClient) { - throw new Error("WebSocket client not connected"); - } - wsClient.send( - JSON.stringify({ - type: "push", - sequence: pushSequence++, - channel: ORCHESTRATION_WS_CHANNELS.domainEvent, - data: event, - }), - ); + rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event); } -async function waitForWsClient(): Promise<{ send: (message: string) => void }> { - let client: { send: (message: string) => void } | null = null; +async function waitForWsClient(): Promise { await vi.waitFor( () => { - client = wsClient; - expect(client).toBeTruthy(); + expect( + wsRequests.some( + (request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents, + ), + ).toBe(true); }, { timeout: 8_000, interval: 16 }, ); - if (!client) { - throw new Error("WebSocket client not connected"); - } - return client; } async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { @@ -513,7 +508,115 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { }; } -function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { +function createSnapshotWithPendingUserInput(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-pending-input-target" as MessageId, + targetText: "question thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + activities: [ + { + id: EventId.makeUnsafe("activity-user-input-requested"), + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + requestId: "req-browser-user-input", + questions: [ + { + id: "scope", + header: "Scope", + question: "What should this change cover?", + options: [ + { + label: "Tight", + description: "Touch only the footer layout logic.", + }, + { + label: "Broad", + description: "Also adjust the related composer controls.", + }, + ], + }, + { + id: "risk", + header: "Risk", + question: "How aggressive should the imaginary plan be?", + options: [ + { + label: "Conservative", + description: "Favor reliability and low-risk changes.", + }, + { + label: "Balanced", + description: "Mix quick wins with one structural improvement.", + }, + ], + }, + ], + }, + turnId: null, + sequence: 1, + createdAt: isoAt(1_000), + }, + ], + updatedAt: isoAt(1_000), + }) + : thread, + ), + }; +} + +function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-plan-follow-up-target" as MessageId, + targetText: "plan follow-up thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + latestTurn: { + turnId: "turn-plan-follow-up" as TurnId, + state: "completed", + requestedAt: isoAt(1_000), + startedAt: isoAt(1_001), + completedAt: isoAt(1_010), + assistantMessageId: null, + }, + proposedPlans: [ + { + id: "plan-follow-up-browser-test", + turnId: "turn-plan-follow-up" as TurnId, + planMarkdown: "# Follow-up plan\n\n- Keep the composer footer stable on resize.", + implementedAt: null, + implementationThreadId: null, + createdAt: isoAt(1_002), + updatedAt: isoAt(1_003), + }, + ], + session: { + ...thread.session, + status: "ready", + updatedAt: isoAt(1_010), + }, + updatedAt: isoAt(1_010), + }) + : thread, + ), + }; +} + +function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { const customResult = customWsRpcResolver?.(body); if (customResult !== undefined) { return customResult; @@ -560,6 +663,9 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { truncated: false, }; } + if (tag === WS_METHODS.shellOpenInEditor) { + return null; + } if (tag === WS_METHODS.terminalOpen) { return { threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID, @@ -578,34 +684,11 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { const worker = setupWorker( wsLink.addEventListener("connection", ({ client }) => { - wsClient = client; - pushSequence = 1; - client.send( - JSON.stringify({ - type: "push", - sequence: pushSequence++, - channel: WS_CHANNELS.serverWelcome, - data: fixture.welcome, - }), - ); + void rpcHarness.connect(client); client.addEventListener("message", (event) => { const rawData = event.data; if (typeof rawData !== "string") return; - let request: WsRequestEnvelope; - try { - request = JSON.parse(rawData) as WsRequestEnvelope; - } catch { - return; - } - const method = request.body?._tag; - if (typeof method !== "string") return; - wsRequests.push(request.body); - client.send( - JSON.stringify({ - id: request.id, - result: resolveWsRpc(request.body), - }), - ); + void rpcHarness.onMessage(rawData); }); }), http.get("*/attachments/:attachmentId", () => @@ -694,6 +777,13 @@ async function waitForComposerEditor(): Promise { ); } +async function waitForComposerMenuItem(itemId: string): Promise { + return waitForElement( + () => document.querySelector(`[data-composer-item-id="${itemId}"]`), + `Unable to find composer menu item "${itemId}".`, + ); +} + async function waitForSendButton(): Promise { return waitForElement( () => document.querySelector('button[aria-label="Send message"]'), @@ -701,6 +791,62 @@ async function waitForSendButton(): Promise { ); } +function findComposerProviderModelPicker(): HTMLButtonElement | null { + return document.querySelector('[data-chat-provider-model-picker="true"]'); +} + +function findButtonByText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === text, + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonByText(text: string): Promise { + return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); +} + +function findButtonContainingText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find((button) => + button.textContent?.includes(text), + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonContainingText(text: string): Promise { + return waitForElement( + () => findButtonContainingText(text), + `Unable to find button containing "${text}".`, + ); +} + +async function expectComposerActionsContained(): Promise { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const actions = await waitForElement( + () => document.querySelector('[data-chat-composer-actions="right"]'), + "Unable to find composer actions container.", + ); + + await vi.waitFor( + () => { + const footerRect = footer.getBoundingClientRect(); + const actionButtons = Array.from(actions.querySelectorAll("button")); + expect(actionButtons.length).toBeGreaterThanOrEqual(1); + + const buttonRects = actionButtons.map((button) => button.getBoundingClientRect()); + const firstTop = buttonRects[0]?.top ?? 0; + + for (const rect of buttonRects) { + expect(rect.right).toBeLessThanOrEqual(footerRect.right + 0.5); + expect(rect.bottom).toBeLessThanOrEqual(footerRect.bottom + 0.5); + expect(Math.abs(rect.top - firstTop)).toBeLessThanOrEqual(1.5); + } + }, + { timeout: 8_000, interval: 16 }, + ); +} + async function waitForInteractionModeButton( expectedLabel: "Chat" | "Plan", ): Promise { @@ -716,7 +862,9 @@ async function waitForInteractionModeButton( async function waitForServerConfigToApply(): Promise { await vi.waitFor( () => { - expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true); + expect(wsRequests.some((request) => request._tag === WS_METHODS.subscribeServerConfig)).toBe( + true, + ); }, { timeout: 8_000, interval: 16 }, ); @@ -854,7 +1002,7 @@ async function mountChatView(options: { viewport: ViewportSpec; snapshot: OrchestrationReadModel; configureFixture?: (fixture: TestFixture) => void; - resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined; + resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined; }): Promise { fixture = buildFixture(options.snapshot); options.configureFixture?.(fixture); @@ -864,7 +1012,8 @@ async function mountChatView(options: { const host = document.createElement("div"); host.style.position = "fixed"; - host.style.inset = "0"; + host.style.top = "0"; + host.style.left = "0"; host.style.width = "100vw"; host.style.height = "100vh"; host.style.display = "grid"; @@ -897,6 +1046,11 @@ async function mountChatView(options: { await setViewport(viewport); await waitForProductionStyles(); }, + setContainerSize: async (viewport) => { + host.style.width = `${viewport.width}px`; + host.style.height = `${viewport.height}px`; + await waitForLayout(); + }, router, }; } @@ -936,10 +1090,37 @@ describe("ChatView timeline estimator parity (full app)", () => { }); afterAll(async () => { + await rpcHarness.disconnect(); await worker.stop(); }); beforeEach(async () => { + await rpcHarness.reset({ + resolveUnary: resolveWsRpc, + getInitialStreamValues: (request) => { + if (request._tag === WS_METHODS.subscribeServerLifecycle) { + return [ + { + version: 1, + sequence: 1, + type: "welcome", + payload: fixture.welcome, + }, + ]; + } + if (request._tag === WS_METHODS.subscribeServerConfig) { + return [ + { + version: 1, + type: "snapshot", + config: fixture.serverConfig, + }, + ]; + } + return []; + }, + }); + __resetNativeApiForTests(); await setViewport(DEFAULT_VIEWPORT); localStorage.clear(); document.body.innerHTML = ""; @@ -1149,6 +1330,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { + await waitForServerConfigToApply(); const openButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( @@ -1156,6 +1338,9 @@ describe("ChatView timeline estimator parity (full app)", () => { ) as HTMLButtonElement | null, "Unable to find Open button.", ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); openButton.click(); await vi.waitFor( @@ -1191,6 +1376,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { + await waitForServerConfigToApply(); const openButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( @@ -1198,6 +1384,9 @@ describe("ChatView timeline estimator parity (full app)", () => { ) as HTMLButtonElement | null, "Unable to find Open button.", ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); openButton.click(); await vi.waitFor( @@ -1233,6 +1422,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { + await waitForServerConfigToApply(); const menuButton = await waitForElement( () => document.querySelector('button[aria-label="Copy options"]'), "Unable to find Open picker button.", @@ -1281,7 +1471,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); it("falls back to the first installed editor when the stored favorite is unavailable", async () => { - localStorage.setItem("t3code:last-editor", "vscodium"); + localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium")); setDraftThreadWithoutWorktree(); const mounted = await mountChatView({ @@ -1296,6 +1486,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { + await waitForServerConfigToApply(); const openButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( @@ -1303,6 +1494,9 @@ describe("ChatView timeline estimator parity (full app)", () => { ) as HTMLButtonElement | null, "Unable to find Open button.", ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); openButton.click(); await vi.waitFor( @@ -2341,4 +2535,125 @@ describe("ChatView timeline estimator parity (full app)", () => { await mounted.cleanup(); } }); + + it("keeps pending-question footer actions inside the composer after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPendingUserInput(), + }); + + try { + const firstOption = await waitForButtonContainingText("Tight"); + firstOption.click(); + + await waitForButtonByText("Previous"); + await waitForButtonByText("Submit answers"); + + await mounted.setContainerSize(COMPACT_FOOTER_VIEWPORT); + await expectComposerActionsContained(); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPlanFollowUpPrompt(), + }); + + try { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const initialModelPicker = await waitForElement( + findComposerProviderModelPicker, + "Unable to find provider model picker.", + ); + const initialModelPickerOffset = + initialModelPicker.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + await waitForButtonByText("Implement"); + await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await mounted.setContainerSize({ + width: 440, + height: WIDE_FOOTER_VIEWPORT.height, + }); + await expectComposerActionsContained(); + + const implementButton = await waitForButtonByText("Implement"); + const implementActionsButton = await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await vi.waitFor( + () => { + const implementRect = implementButton.getBoundingClientRect(); + const implementActionsRect = implementActionsButton.getBoundingClientRect(); + const compactModelPicker = findComposerProviderModelPicker(); + expect(compactModelPicker).toBeTruthy(); + + const compactModelPickerOffset = + compactModelPicker!.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + expect(Math.abs(implementRect.right - implementActionsRect.left)).toBeLessThanOrEqual(1); + expect(Math.abs(implementRect.top - implementActionsRect.top)).toBeLessThanOrEqual(1); + expect(Math.abs(compactModelPickerOffset - initialModelPickerOffset)).toBeLessThanOrEqual( + 1, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the slash-command menu visible above the composer", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-command-menu-target" as MessageId, + targetText: "command menu thread", + }), + }); + + try { + await waitForComposerEditor(); + await page.getByTestId("composer-editor").fill("/"); + + const menuItem = await waitForComposerMenuItem("slash:model"); + const composerForm = await waitForElement( + () => document.querySelector('[data-chat-composer-form="true"]'), + "Unable to find composer form.", + ); + + await vi.waitFor( + () => { + const menuRect = menuItem.getBoundingClientRect(); + const composerRect = composerForm.getBoundingClientRect(); + const hitTarget = document.elementFromPoint( + menuRect.left + menuRect.width / 2, + menuRect.top + menuRect.height / 2, + ); + + expect(menuRect.width).toBeGreaterThan(0); + expect(menuRect.height).toBeGreaterThan(0); + expect(menuRect.bottom).toBeLessThanOrEqual(composerRect.bottom); + expect(hitTarget instanceof Element && menuItem.contains(hitTarget)).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7562f845e2..76133712d4 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -11,11 +11,9 @@ import { type ProviderApprovalDecision, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, - type ResolvedKeybindingsConfig, type ServerProvider, type ThreadId, type TurnId, - type EditorId, type KeybindingCommand, OrchestrationThreadActivity, ProviderInteractionMode, @@ -30,7 +28,6 @@ import { useDebouncedValue } from "@tanstack/react-pacer"; import { useNavigate, useSearch } from "@tanstack/react-router"; import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery"; import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; -import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery"; import { isElectron } from "../env"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { @@ -106,7 +103,6 @@ import { } from "lucide-react"; import { Button } from "./ui/button"; import { Separator } from "./ui/separator"; -import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu"; import { cn, randomUUID } from "~/lib/utils"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { toastManager } from "./ui/toast"; @@ -148,7 +144,12 @@ import { type TerminalContextSelection, } from "../lib/terminalContext"; import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow"; -import { shouldUseCompactComposerFooter } from "./composerFooterLayout"; +import { + resolveComposerFooterContentWidth, + shouldForceCompactComposerFooterForFit, + shouldUseCompactComposerPrimaryActions, + shouldUseCompactComposerFooter, +} from "./composerFooterLayout"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; @@ -160,6 +161,7 @@ import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/Provider import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions"; import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu"; +import { ComposerPrimaryActions } from "./chat/ComposerPrimaryActions"; import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner"; @@ -190,15 +192,18 @@ import { waitForStartedServerThread, } from "./ChatView.logic"; import { useLocalStorage } from "~/hooks/useLocalStorage"; +import { + useServerAvailableEditors, + useServerConfig, + useServerKeybindings, +} from "~/rpc/serverState"; const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = []; -const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = []; -const EMPTY_AVAILABLE_EDITORS: EditorId[] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; @@ -499,6 +504,7 @@ export default function ChatView({ threadId }: ChatViewProps) { const [expandedWorkGroups, setExpandedWorkGroups] = useState>({}); const [planSidebarOpen, setPlanSidebarOpen] = useState(false); const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); + const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); // Tracks whether the user explicitly dismissed the sidebar for the active turn. const planSidebarDismissedForTurnRef = useRef(null); // When set, the thread-change reset effect will open the sidebar instead of closing it. @@ -541,6 +547,9 @@ export default function ChatView({ threadId }: ChatViewProps) { const composerEditorRef = useRef(null); const composerFormRef = useRef(null); const composerFormHeightRef = useRef(0); + const composerFooterRef = useRef(null); + const composerFooterLeadingRef = useRef(null); + const composerFooterActionsRef = useRef(null); const composerImagesRef = useRef([]); const composerSelectLockRef = useRef(false); const composerMenuOpenRef = useRef(false); @@ -785,8 +794,8 @@ export default function ChatView({ threadId }: ChatViewProps) { const lockedProvider: ProviderKind | null = hasThreadStarted ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null) : null; - const serverConfigQuery = useQuery(serverConfigQueryOptions()); - const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS; + const serverConfig = useServerConfig(); + const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, selectedProviderByThreadId ?? threadProvider ?? "codex", @@ -930,6 +939,28 @@ export default function ChatView({ threadId }: ChatViewProps) { pendingUserInputs.length > 0 || (showPlanFollowUpPrompt && activeProposedPlan !== null); const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterActionLayoutKey = useMemo(() => { + if (activePendingProgress) { + return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`; + } + if (phase === "running") { + return "running"; + } + if (showPlanFollowUpPrompt) { + return prompt.trim().length > 0 ? "plan:refine" : "plan:implement"; + } + return `idle:${composerSendState.hasSendableContent}:${isSendBusy}:${isConnecting}:${isPreparingWorktree}`; + }, [ + activePendingIsResponding, + activePendingProgress, + composerSendState.hasSendableContent, + isConnecting, + isPreparingWorktree, + isSendBusy, + phase, + prompt, + showPlanFollowUpPrompt, + ]); const lastSyncedPendingInputRef = useRef<{ requestId: string | null; questionId: string | null; @@ -1171,8 +1202,8 @@ export default function ChatView({ threadId }: ChatViewProps) { ); const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : ""; const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd)); - const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS; - const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS; + const keybindings = useServerKeybindings(); + const availableEditors = useServerAvailableEditors(); const modelOptionsByProvider = useMemo( () => ({ codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [], @@ -1667,10 +1698,9 @@ export default function ChatView({ threadId }: ChatViewProps) { if (isElectron && keybindingRule) { await api.server.upsertKeybinding(keybindingRule); - await queryClient.invalidateQueries({ queryKey: serverQueryKeys.all }); } }, - [queryClient], + [], ); const saveProjectScript = useCallback( async (input: NewProjectScriptInput) => { @@ -2038,23 +2068,56 @@ export default function ChatView({ threadId }: ChatViewProps) { const composerForm = composerFormRef.current; if (!composerForm) return; const measureComposerFormWidth = () => composerForm.clientWidth; + const measureFooterCompactness = () => { + const composerFormWidth = measureComposerFormWidth(); + const heuristicFooterCompact = shouldUseCompactComposerFooter(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + const footer = composerFooterRef.current; + const footerStyle = footer ? window.getComputedStyle(footer) : null; + const footerContentWidth = resolveComposerFooterContentWidth({ + footerWidth: footer?.clientWidth ?? null, + paddingLeft: footerStyle ? Number.parseFloat(footerStyle.paddingLeft) : null, + paddingRight: footerStyle ? Number.parseFloat(footerStyle.paddingRight) : null, + }); + const fitInput = { + footerContentWidth, + leadingContentWidth: composerFooterLeadingRef.current?.scrollWidth ?? null, + actionsWidth: composerFooterActionsRef.current?.scrollWidth ?? null, + }; + const nextFooterCompact = + heuristicFooterCompact || shouldForceCompactComposerFooterForFit(fitInput); + const nextPrimaryActionsCompact = + nextFooterCompact && + shouldUseCompactComposerPrimaryActions(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + + return { + primaryActionsCompact: nextPrimaryActionsCompact, + footerCompact: nextFooterCompact, + }; + }; composerFormHeightRef.current = composerForm.getBoundingClientRect().height; - setIsComposerFooterCompact( - shouldUseCompactComposerFooter(measureComposerFormWidth(), { - hasWideActions: composerFooterHasWideActions, - }), - ); + const initialCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact); + setIsComposerFooterCompact(initialCompactness.footerCompact); if (typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver((entries) => { const [entry] = entries; if (!entry) return; - const nextCompact = shouldUseCompactComposerFooter(measureComposerFormWidth(), { - hasWideActions: composerFooterHasWideActions, - }); - setIsComposerFooterCompact((previous) => (previous === nextCompact ? previous : nextCompact)); + const nextCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact((previous) => + previous === nextCompactness.primaryActionsCompact + ? previous + : nextCompactness.primaryActionsCompact, + ); + setIsComposerFooterCompact((previous) => + previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, + ); const nextHeight = entry.contentRect.height; const previousHeight = composerFormHeightRef.current; @@ -2069,7 +2132,12 @@ export default function ChatView({ threadId }: ChatViewProps) { return () => { observer.disconnect(); }; - }, [activeThread?.id, composerFooterHasWideActions, scheduleStickToBottom]); + }, [ + activeThread?.id, + composerFooterActionLayoutKey, + composerFooterHasWideActions, + scheduleStickToBottom, + ]); useEffect(() => { if (!shouldAutoScrollRef.current) return; scheduleStickToBottom(); @@ -3243,6 +3311,10 @@ export default function ChatView({ threadId }: ChatViewProps) { titleSeed: nextThreadTitle, runtimeMode, interactionMode: "default", + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, createdAt, }); }) @@ -3788,7 +3860,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
) : (
@@ -4113,8 +4186,12 @@ export default function ChatView({ threadId }: ChatViewProps) { {/* Right side: send / stop button */}
{activeContextWindow ? ( @@ -4124,156 +4201,32 @@ export default function ChatView({ threadId }: ChatViewProps) { Preparing worktree... ) : null} - {activePendingProgress ? ( -
- {activePendingProgress.questionIndex > 0 ? ( - - ) : null} - -
- ) : phase === "running" ? ( - - ) : pendingUserInputs.length === 0 ? ( - showPlanFollowUpPrompt ? ( - prompt.trim().length > 0 ? ( - - ) : ( -
- - - - } - > - - - - void onImplementPlanInNewThread()} - > - Implement in a new thread - - - -
- ) - ) : ( - - ) - ) : null} + 0} + isSendBusy={isSendBusy} + isConnecting={isConnecting} + isPreparingWorktree={isPreparingWorktree} + hasSendableContent={composerSendState.hasSendableContent} + onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} + onInterrupt={() => void onInterrupt()} + onImplementPlanInNewThread={() => void onImplementPlanInNewThread()} + />
)} diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 1593a151da..6384709620 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -294,74 +294,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }) : null; - useEffect(() => { - const api = readNativeApi(); - if (!api) { - return; - } - - const applyProgressEvent = (event: GitActionProgressEvent) => { - const progress = activeGitActionProgressRef.current; - if (!progress) { - return; - } - if (gitCwd && event.cwd !== gitCwd) { - return; - } - if (progress.actionId !== event.actionId) { - return; - } - - const now = Date.now(); - switch (event.kind) { - case "action_started": - progress.phaseStartedAtMs = now; - progress.hookStartedAtMs = null; - progress.hookName = null; - progress.lastOutputLine = null; - break; - case "phase_started": - progress.title = event.label; - progress.currentPhaseLabel = event.label; - progress.phaseStartedAtMs = now; - progress.hookStartedAtMs = null; - progress.hookName = null; - progress.lastOutputLine = null; - break; - case "hook_started": - progress.title = `Running ${event.hookName}...`; - progress.hookName = event.hookName; - progress.hookStartedAtMs = now; - progress.lastOutputLine = null; - break; - case "hook_output": - progress.lastOutputLine = event.text; - break; - case "hook_finished": - progress.title = progress.currentPhaseLabel ?? "Committing..."; - progress.hookName = null; - progress.hookStartedAtMs = null; - progress.lastOutputLine = null; - break; - case "action_finished": - // Don't clear timestamps here — the HTTP response handler (line 496) - // sets activeGitActionProgressRef to null and shows the success toast. - // Clearing timestamps early causes the "Running for Xs" description - // to disappear before the success state renders, leaving a bare - // "Pushing..." toast in the gap between the WS event and HTTP response. - return; - case "action_failed": - // Same reasoning as action_finished — let the HTTP error handler - // manage the final toast state to avoid a flash of bare title. - return; - } - - updateActiveProgressToast(); - }; - - return api.git.onActionProgress(applyProgressEvent); - }, [gitCwd, updateActiveProgressToast]); - useEffect(() => { const interval = window.setInterval(() => { if (!activeGitActionProgressRef.current) { @@ -483,12 +415,69 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions }); } + const applyProgressEvent = (event: GitActionProgressEvent) => { + const progress = activeGitActionProgressRef.current; + if (!progress) { + return; + } + if (gitCwd && event.cwd !== gitCwd) { + return; + } + if (progress.actionId !== event.actionId) { + return; + } + + const now = Date.now(); + switch (event.kind) { + case "action_started": + progress.phaseStartedAtMs = now; + progress.hookStartedAtMs = null; + progress.hookName = null; + progress.lastOutputLine = null; + break; + case "phase_started": + progress.title = event.label; + progress.currentPhaseLabel = event.label; + progress.phaseStartedAtMs = now; + progress.hookStartedAtMs = null; + progress.hookName = null; + progress.lastOutputLine = null; + break; + case "hook_started": + progress.title = `Running ${event.hookName}...`; + progress.hookName = event.hookName; + progress.hookStartedAtMs = now; + progress.lastOutputLine = null; + break; + case "hook_output": + progress.lastOutputLine = event.text; + break; + case "hook_finished": + progress.title = progress.currentPhaseLabel ?? "Committing..."; + progress.hookName = null; + progress.hookStartedAtMs = null; + progress.lastOutputLine = null; + break; + case "action_finished": + // Let the resolved mutation update the toast so we keep the + // elapsed description visible until the final success state renders. + return; + case "action_failed": + // Let the rejected mutation publish the error toast to avoid a + // transient intermediate state before the final failure message. + return; + } + + updateActiveProgressToast(); + }; + const promise = runImmediateGitActionMutation.mutateAsync({ actionId, action, ...(commitMessage ? { commitMessage } : {}), ...(featureBranch ? { featureBranch } : {}), ...(filePaths ? { filePaths } : {}), + onProgress: applyProgressEvent, }); try { diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 224bd2f887..9581e72cd2 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -6,9 +6,8 @@ import { type OrchestrationReadModel, type ProjectId, type ServerConfig, + type ServerLifecycleWelcomePayload, type ThreadId, - type WsWelcomePayload, - WS_CHANNELS, WS_METHODS, } from "@t3tools/contracts"; import { RouterProvider, createMemoryHistory } from "@tanstack/react-router"; @@ -18,8 +17,10 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { render } from "vitest-browser-react"; import { useComposerDraftStore } from "../composerDraftStore"; +import { __resetNativeApiForTests } from "../nativeApi"; import { getRouter } from "../router"; import { useStore } from "../store"; +import { BrowserWsRpcHarness } from "../../test/wsRpcHarness"; const THREAD_ID = "thread-kb-toast-test" as ThreadId; const PROJECT_ID = "project-1" as ProjectId; @@ -28,12 +29,11 @@ const NOW_ISO = "2026-03-04T12:00:00.000Z"; interface TestFixture { snapshot: OrchestrationReadModel; serverConfig: ServerConfig; - welcome: WsWelcomePayload; + welcome: ServerLifecycleWelcomePayload; } let fixture: TestFixture; -let wsClient: { send: (data: string) => void } | null = null; -let pushSequence = 1; +const rpcHarness = new BrowserWsRpcHarness(); const wsLink = ws.link(/ws(s)?:\/\/.*/); @@ -179,52 +179,23 @@ function resolveWsRpc(tag: string): unknown { const worker = setupWorker( wsLink.addEventListener("connection", ({ client }) => { - wsClient = client; - pushSequence = 1; - client.send( - JSON.stringify({ - type: "push", - sequence: pushSequence++, - channel: WS_CHANNELS.serverWelcome, - data: fixture.welcome, - }), - ); + void rpcHarness.connect(client); client.addEventListener("message", (event) => { const rawData = event.data; if (typeof rawData !== "string") return; - let request: { id: string; body: { _tag: string; [key: string]: unknown } }; - try { - request = JSON.parse(rawData); - } catch { - return; - } - const method = request.body?._tag; - if (typeof method !== "string") return; - client.send( - JSON.stringify({ - id: request.id, - result: resolveWsRpc(method), - }), - ); + void rpcHarness.onMessage(rawData); }); }), http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })), http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })), ); -function sendServerConfigUpdatedPush(issues: Array<{ kind: string; message: string }>) { - if (!wsClient) throw new Error("WebSocket client not connected"); - wsClient.send( - JSON.stringify({ - type: "push", - sequence: pushSequence++, - channel: WS_CHANNELS.serverConfigUpdated, - data: { - issues, - providers: fixture.serverConfig.providers, - }, - }), - ); +function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) { + rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, { + version: 1, + type: "keybindingsUpdated", + payload: { issues }, + }); } function queryToastTitles(): string[] { @@ -308,13 +279,39 @@ describe("Keybindings update toast", () => { }); afterAll(async () => { + await rpcHarness.disconnect(); await worker.stop(); }); - beforeEach(() => { + beforeEach(async () => { + await rpcHarness.reset({ + resolveUnary: (request) => resolveWsRpc(request._tag), + getInitialStreamValues: (request) => { + if (request._tag === WS_METHODS.subscribeServerLifecycle) { + return [ + { + version: 1, + sequence: 1, + type: "welcome", + payload: fixture.welcome, + }, + ]; + } + if (request._tag === WS_METHODS.subscribeServerConfig) { + return [ + { + version: 1, + type: "snapshot", + config: fixture.serverConfig, + }, + ]; + } + return []; + }, + }); + __resetNativeApiForTests(); localStorage.clear(); document.body.innerHTML = ""; - pushSequence = 1; useComposerDraftStore.setState({ draftsByThreadId: {}, draftThreadsByThreadId: {}, diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index bc0118120f..58426f50ba 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -1,30 +1,15 @@ import { FolderIcon } from "lucide-react"; import { useState } from "react"; - -function getServerHttpOrigin(): string { - const bridgeUrl = window.desktopBridge?.getWsUrl(); - const envUrl = import.meta.env.VITE_WS_URL as string | undefined; - const wsUrl = - bridgeUrl && bridgeUrl.length > 0 - ? bridgeUrl - : envUrl && envUrl.length > 0 - ? envUrl - : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`; - // Parse to extract just the origin, dropping path/query (e.g. ?token=…) - const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:"); - try { - return new URL(httpUrl).origin; - } catch { - return httpUrl; - } -} - -const serverHttpOrigin = getServerHttpOrigin(); +import { resolveServerUrl } from "~/lib/utils"; const loadedProjectFaviconSrcs = new Set(); export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) { - const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`; + const src = resolveServerUrl({ + protocol: "http", + pathname: "/api/project-favicon", + searchParams: { cwd }, + }); const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", ); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index efa5124288..c819ce81cd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -43,9 +43,8 @@ import { ProjectId, ThreadId, type GitStatusResult, - type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; -import { useQueries, useQuery } from "@tanstack/react-query"; +import { useQueries } from "@tanstack/react-query"; import { useLocation, useNavigate, useParams } from "@tanstack/react-router"; import { type SidebarProjectSortOrder, @@ -67,7 +66,6 @@ import { } from "../keybindings"; import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic"; import { gitStatusQueryOptions } from "../lib/gitReactQuery"; -import { serverConfigQueryOptions } from "../lib/serverReactQuery"; import { readNativeApi } from "../nativeApi"; import { useComposerDraftStore } from "../composerDraftStore"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; @@ -125,9 +123,8 @@ import { import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; +import { useServerKeybindings } from "../rpc/serverState"; import type { Project, Thread } from "../types"; - -const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; const THREAD_PREVIEW_LIMIT = 6; const SIDEBAR_SORT_LABELS: Record = { updated_at: "Last user message", @@ -469,10 +466,7 @@ export default function Sidebar() { strict: false, select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), }); - const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({ - ...serverConfigQueryOptions(), - select: (config) => config.keybindings, - }); + const keybindings = useServerKeybindings(); const [addingProject, setAddingProject] = useState(false); const [newCwd, setNewCwd] = useState(""); const [isPickingFolder, setIsPickingFolder] = useState(false); diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx new file mode 100644 index 0000000000..09b343c900 --- /dev/null +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -0,0 +1,217 @@ +import { memo } from "react"; +import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react"; +import { cn } from "~/lib/utils"; +import { Button } from "../ui/button"; +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; + +interface PendingActionState { + questionIndex: number; + isLastQuestion: boolean; + canAdvance: boolean; + isResponding: boolean; + isComplete: boolean; +} + +interface ComposerPrimaryActionsProps { + compact: boolean; + pendingAction: PendingActionState | null; + isRunning: boolean; + showPlanFollowUpPrompt: boolean; + promptHasText: boolean; + isSendBusy: boolean; + isConnecting: boolean; + isPreparingWorktree: boolean; + hasSendableContent: boolean; + onPreviousPendingQuestion: () => void; + onInterrupt: () => void; + onImplementPlanInNewThread: () => void; +} + +const formatPendingPrimaryActionLabel = (input: { + compact: boolean; + isLastQuestion: boolean; + isResponding: boolean; +}) => { + if (input.isResponding) { + return "Submitting..."; + } + if (input.compact) { + return input.isLastQuestion ? "Submit" : "Next"; + } + return input.isLastQuestion ? "Submit answers" : "Next question"; +}; + +export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ + compact, + pendingAction, + isRunning, + showPlanFollowUpPrompt, + promptHasText, + isSendBusy, + isConnecting, + isPreparingWorktree, + hasSendableContent, + onPreviousPendingQuestion, + onInterrupt, + onImplementPlanInNewThread, +}: ComposerPrimaryActionsProps) { + if (pendingAction) { + return ( +
+ {pendingAction.questionIndex > 0 ? ( + compact ? ( + + ) : ( + + ) + ) : null} + +
+ ); + } + + if (isRunning) { + return ( + + ); + } + + if (showPlanFollowUpPrompt) { + if (promptHasText) { + return ( + + ); + } + + return ( +
+ + + + } + > + + + + void onImplementPlanInNewThread()} + > + Implement in a new thread + + + +
+ ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 565a9d399d..01fa37516e 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -98,6 +98,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {