diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..705bd8f43e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt +* text=auto eol=lf diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 72f270dca3..5535d54a5b 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -28,4 +28,5 @@ github:realAhmedRoach github:shiroyasha9 github:Yash-Singh1 github:eggfriedrice24 -github:Ymit24 \ No newline at end of file +github:Ymit24 +github:shivamhwp diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index ced845a28f..15c04d663d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -124,25 +124,49 @@ jobs: group: pr-size-${{ github.event.pull_request.number }} cancel-in-progress: true steps: + - name: Checkout base repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Sync PR size label uses: actions/github-script@v8 env: PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} with: script: | + const { execFileSync } = require("node:child_process"); + const issueNumber = context.payload.pull_request.number; + const baseSha = context.payload.pull_request.base.sha; + const headSha = context.payload.pull_request.head.sha; + const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`; const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]"); const managedLabelNames = new Set(managedLabels.map((label) => label.name)); // Keep this aligned with the repo's test entrypoints and test-only support files. - const testFilePatterns = [ - /(^|\/)__tests__(\/|$)/, - /(^|\/)tests?(\/|$)/, - /^apps\/server\/integration\//, - /\.(test|spec|browser|integration)\.[^.\/]+$/, + const testExcludePathspecs = [ + ":(glob,exclude)**/__tests__/**", + ":(glob,exclude)**/test/**", + ":(glob,exclude)**/tests/**", + ":(glob,exclude)apps/server/integration/**", + ":(glob,exclude)**/*.test.*", + ":(glob,exclude)**/*.spec.*", + ":(glob,exclude)**/*.browser.*", + ":(glob,exclude)**/*.integration.*", ]; - const isTestFile = (filename) => - testFilePatterns.some((pattern) => pattern.test(filename)); + const sumNumstat = (text) => + text + .split("\n") + .filter(Boolean) + .reduce((total, line) => { + const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t"); + const additions = + insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0; + const deletions = + deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0; + + return total + additions + deletions; + }, 0); const resolveSizeLabel = (totalChangedLines) => { if (totalChangedLines < 10) { @@ -168,40 +192,53 @@ jobs: return "size:XXL"; }; - const files = await github.paginate( - github.rest.pulls.listFiles, + execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], { + stdio: "inherit", + }); + + execFileSync( + "git", + ["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`], { - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: issueNumber, - per_page: 100, + stdio: "inherit", }, - (response) => response.data, ); - if (files.length >= 3000) { + const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], { + encoding: "utf8", + }).trim(); + + if (resolvedHeadSha !== headSha) { core.warning( - "The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.", + `Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`, ); } - let testChangedLines = 0; - let nonTestChangedLines = 0; + execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], { + stdio: "inherit", + }); - for (const file of files) { - const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0); + const diffArgs = [ + "diff", + "--numstat", + "--ignore-all-space", + "--ignore-blank-lines", + `${baseSha}...${resolvedHeadSha}`, + ]; - if (changedLinesForFile === 0) { - continue; - } - - if (isTestFile(file.filename)) { - testChangedLines += changedLinesForFile; - continue; - } - - nonTestChangedLines += changedLinesForFile; - } + const totalChangedLines = sumNumstat( + execFileSync( + "git", + diffArgs, + { encoding: "utf8" }, + ), + ); + const nonTestChangedLines = sumNumstat( + execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], { + encoding: "utf8", + }), + ); + const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines); const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines; const nextLabelName = resolveSizeLabel(changedLines); diff --git a/.gitignore b/.gitignore index 471855de15..6e5f8cc59c 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ packages/*/dist build/ .logs/ release/ +release-mock/ .t3 .idea/ apps/web/.playwright diff --git a/.oxfmtrc.json b/.oxfmtrc.json index ef2236d0f2..a3e32c9797 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/README.md b/README.md index 5f842e3709..d7b2fccb8f 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,42 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon). -## How to use +## Installation > [!WARNING] -> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work. +> T3 Code currently supports Codex and Claude. +> Install and authenticate at least one provider before use: +> +> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login` +> - Claude: install Claude Code and run `claude auth login` + +### Run without installing ```bash npx t3 ``` -You can also just install the desktop app. It's cooler. +### Desktop app -Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases) +Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry: + +#### Windows (`winget`) + +```bash +winget install T3Tools.T3Code +``` + +#### macOS (Homebrew) + +```bash +brew install --cask t3-code +``` + +#### Arch Linux (AUR) + +```bash +yay -S t3code-bin +``` ## Some notes diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 188e701e7e..dfa3bde2f8 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.14", + "version": "0.0.15", "private": true, "main": "dist-electron/main.js", "scripts": { @@ -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/confirmDialog.ts b/apps/desktop/src/confirmDialog.ts index 1beda8543b..c941d09065 100644 --- a/apps/desktop/src/confirmDialog.ts +++ b/apps/desktop/src/confirmDialog.ts @@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog( const options = { type: "question" as const, buttons: ["No", "Yes"], - defaultId: CONFIRM_BUTTON_INDEX, + defaultId: 0, cancelId: 0, noLink: true, message: normalizedMessage, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 0bb3d20c4d..34391a5995 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -20,6 +20,7 @@ import * as Effect from "effect/Effect"; import type { DesktopTheme, DesktopUpdateActionResult, + DesktopUpdateCheckResult, DesktopUpdateState, } from "@t3tools/contracts"; import { autoUpdater } from "electron-updater"; @@ -56,6 +57,7 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state"; const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); const STATE_DIR = Path.join(BASE_DIR, "userdata"); @@ -64,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; @@ -78,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; @@ -261,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) { @@ -287,10 +298,12 @@ let updatePollTimer: ReturnType | null = null; let updateStartupTimer: ReturnType | null = null; let updateCheckInFlight = false; let updateDownloadInFlight = false; +let updateInstallInFlight = false; let updaterConfigured = false; let updateState: DesktopUpdateState = initialUpdateState(); function resolveUpdaterErrorContext(): DesktopUpdateErrorContext { + if (updateInstallInFlight) return "install"; if (updateDownloadInFlight) return "download"; if (updateCheckInFlight) return "check"; return updateState.errorContext; @@ -386,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 { @@ -711,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) { @@ -754,13 +771,13 @@ function shouldEnableAutoUpdates(): boolean { ); } -async function checkForUpdates(reason: string): Promise { - if (isQuitting || !updaterConfigured || updateCheckInFlight) return; +async function checkForUpdates(reason: string): Promise { + if (isQuitting || !updaterConfigured || updateCheckInFlight) return false; if (updateState.status === "downloading" || updateState.status === "downloaded") { console.info( `[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`, ); - return; + return false; } updateCheckInFlight = true; setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString())); @@ -768,12 +785,14 @@ async function checkForUpdates(reason: string): Promise { try { await autoUpdater.checkForUpdates(); + return true; } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error); setUpdateState( reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()), ); console.error(`[desktop-updater] Failed to check for updates: ${message}`); + return true; } finally { updateCheckInFlight = false; } @@ -807,13 +826,22 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed } isQuitting = true; + updateInstallInFlight = true; clearUpdatePollTimer(); try { await stopBackendAndWaitForExit(); - autoUpdater.quitAndInstall(); - return { accepted: true, completed: true }; + // Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close. + for (const win of BrowserWindow.getAllWindows()) { + win.destroy(); + } + // `quitAndInstall()` only starts the handoff to the updater. The actual + // install may still fail asynchronously, so keep the action incomplete + // until we either quit or receive an updater error. + autoUpdater.quitAndInstall(true, true); + return { accepted: true, completed: false }; } catch (error: unknown) { const message = formatErrorMessage(error); + updateInstallInFlight = false; isQuitting = false; setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); console.error(`[desktop-updater] Failed to install update: ${message}`); @@ -850,6 +878,13 @@ function configureAutoUpdater(): void { } } + if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) { + autoUpdater.setFeedURL({ + provider: "generic", + url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`, + }); + } + autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; // Keep alpha branding, but force all installs onto the stable update track. @@ -886,6 +921,13 @@ function configureAutoUpdater(): void { }); autoUpdater.on("error", (error) => { const message = formatErrorMessage(error); + if (updateInstallInFlight) { + updateInstallInFlight = false; + isQuitting = false; + setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); + console.error(`[desktop-updater] Updater error: ${message}`); + return; + } if (!updateCheckInFlight && !updateDownloadInFlight) { setUpdateState({ status: "error", @@ -1141,6 +1183,7 @@ function registerIpcHandlers(): void { id: item.id, label: item.label, destructive: item.destructive === true, + disabled: item.disabled === true, })); if (normalizedItems.length === 0) { return null; @@ -1171,6 +1214,7 @@ function registerIpcHandlers(): void { } const itemOption: MenuItemConstructorOptions = { label: item.label, + enabled: !item.disabled, click: () => resolve(item.id), }; if (item.destructive) { @@ -1236,6 +1280,21 @@ function registerIpcHandlers(): void { state: updateState, } satisfies DesktopUpdateActionResult; }); + + ipcMain.removeHandler(UPDATE_CHECK_CHANNEL); + ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => { + if (!updaterConfigured) { + return { + checked: false, + state: updateState, + } satisfies DesktopUpdateCheckResult; + } + const checked = await checkForUpdates("web-ui"); + return { + checked, + state: updateState, + } satisfies DesktopUpdateCheckResult; + }); } function getIconOption(): { icon: string } | Record { @@ -1359,6 +1418,7 @@ async function bootstrap(): Promise { app.on("before-quit", () => { isQuitting = true; + updateInstallInFlight = false; writeDesktopLogHeader("before-quit received"); clearUpdatePollTimer(); stopBackend(); @@ -1388,7 +1448,7 @@ app }); app.on("window-all-closed", () => { - if (process.platform !== "darwin") { + if (process.platform !== "darwin" && !isQuitting) { app.quit(); } }); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 2fb7e3a1db..3d59db1714 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -9,6 +9,7 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; const MENU_ACTION_CHANNEL = "desktop:menu-action"; const UPDATE_STATE_CHANNEL = "desktop:update-state"; const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; @@ -35,6 +36,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { }; }, getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL), + checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL), downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL), installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL), onUpdateState: (listener) => { diff --git a/apps/desktop/src/syncShellEnvironment.test.ts b/apps/desktop/src/syncShellEnvironment.test.ts index 69e73da0aa..cda78a20b2 100644 --- a/apps/desktop/src/syncShellEnvironment.test.ts +++ b/apps/desktop/src/syncShellEnvironment.test.ts @@ -62,14 +62,13 @@ describe("syncShellEnvironment", () => { expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); }); - it("does nothing outside macOS", () => { + it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => { const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", - SSH_AUTH_SOCK: "/tmp/inherited.sock", }; const readEnvironment = vi.fn(() => ({ - PATH: "/opt/homebrew/bin:/usr/bin", + PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin", SSH_AUTH_SOCK: "/tmp/secretive.sock", })); @@ -78,8 +77,29 @@ describe("syncShellEnvironment", () => { readEnvironment, }); + expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]); + expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock"); + }); + + it("does nothing outside macOS and linux", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + SSH_AUTH_SOCK: "/tmp/inherited.sock", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/usr/local/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/secretive.sock", + })); + + syncShellEnvironment(env, { + platform: "win32", + readEnvironment, + }); + expect(readEnvironment).not.toHaveBeenCalled(); - expect(env.PATH).toBe("/usr/bin"); + expect(env.PATH).toBe("C:\\Windows\\System32"); expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); }); }); diff --git a/apps/desktop/src/syncShellEnvironment.ts b/apps/desktop/src/syncShellEnvironment.ts index 2181bea0ca..13036149b8 100644 --- a/apps/desktop/src/syncShellEnvironment.ts +++ b/apps/desktop/src/syncShellEnvironment.ts @@ -1,4 +1,8 @@ -import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell"; +import { + readEnvironmentFromLoginShell, + resolveLoginShell, + ShellEnvironmentReader, +} from "@t3tools/shared/shell"; export function syncShellEnvironment( env: NodeJS.ProcessEnv = process.env, @@ -7,10 +11,13 @@ export function syncShellEnvironment( readEnvironment?: ShellEnvironmentReader; } = {}, ): void { - if ((options.platform ?? process.platform) !== "darwin") return; + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; try { - const shell = env.SHELL ?? "/bin/zsh"; + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [ "PATH", "SSH_AUTH_SOCK", diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 115d18d02b..e625f71dbf 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -31,6 +31,7 @@ import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/La import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts"; import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts"; import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts"; +import { ProjectionTurnRepositoryLive } from "../src/persistence/Layers/ProjectionTurns.ts"; import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts"; import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts"; import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts"; @@ -68,6 +69,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 +127,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; @@ -292,6 +295,7 @@ export const makeOrchestrationIntegrationHarness = ( OrchestrationProjectionSnapshotQueryLive, ProjectionCheckpointRepositoryLive, ProjectionPendingApprovalRepositoryLive, + ProjectionTurnRepositoryLive, checkpointStoreLayer, providerLayer, RuntimeReceiptBusLive, @@ -306,7 +310,8 @@ export const makeOrchestrationIntegrationHarness = ( Effect.succeed({ branch: input.newBranch }), } as unknown as GitCoreShape); const textGenerationLayer = Layer.succeed(TextGeneration, { - generateBranchName: () => Effect.succeed({ branch: null }), + generateBranchName: () => Effect.succeed({ branch: "update" }), + generateThreadTitle: () => Effect.succeed({ title: "New thread" }), } as unknown as TextGenerationShape); const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), @@ -316,6 +321,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), @@ -359,7 +372,7 @@ export const makeOrchestrationIntegrationHarness = ( const scope = yield* Scope.make("sequential"); yield* tryRuntimePromise("start OrchestrationReactor", () => - runtime.runPromise(reactor.start.pipe(Scope.provide(scope))), + runtime.runPromise(reactor.start().pipe(Scope.provide(scope))), ).pipe(Effect.orDie); const receiptHistory = yield* Ref.make>([]); yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) => 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 ea818b7d3e..e59c7c208c 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.14", + "version": "0.0.15", "license": "MIT", "repository": { "type": "git", @@ -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/bootstrap.test.ts b/apps/server/src/bootstrap.test.ts index 804f2440a9..3fce6af9c4 100644 --- a/apps/server/src/bootstrap.test.ts +++ b/apps/server/src/bootstrap.test.ts @@ -8,10 +8,33 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import { TestClock } from "effect/testing"; +import { vi } from "vitest"; import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap"; import { assertNone, assertSome } from "@effect/vitest/utils"; +const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null })); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + openSync: (...args: Parameters) => { + const [filePath, flags] = args; + if ( + typeof filePath === "string" && + filePath === openSyncInterceptor.failPath && + flags === "r" + ) { + const error = new Error("no such device or address"); + Object.assign(error, { code: "ENXIO" }); + throw error; + } + return (actual.openSync as (...a: typeof args) => number)(...args); + }, + }; +}); + const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String }); it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => { @@ -47,6 +70,36 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => { }), ); + it.effect("falls back to reading the inherited fd when path duplication fails", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + + yield* fs.writeFileString( + filePath, + `${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({ + mode: "desktop", + })}\n`, + ); + + // Open without acquireRelease: the direct-stream fallback uses autoClose: true, + // so the stream owns the fd lifecycle and closes it asynchronously on end. + // Attempting to also close it synchronously in a finalizer races with the + // stream's async close and produces an uncaught EBADF. + const fd = NFS.openSync(filePath, "r"); + + openSyncInterceptor.failPath = `/proc/self/fd/${fd}`; + try { + const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 }); + assertSome(payload, { + mode: "desktop", + }); + } finally { + openSyncInterceptor.failPath = null; + } + }), + ); + it.effect("returns none when the fd is unavailable", () => Effect.gen(function* () { const fd = NFS.openSync("/dev/null", "r"); diff --git a/apps/server/src/bootstrap.ts b/apps/server/src/bootstrap.ts index b837ac6c18..0fb1352268 100644 --- a/apps/server/src/bootstrap.ts +++ b/apps/server/src/bootstrap.ts @@ -108,21 +108,26 @@ const makeBootstrapInputStream = (fd: number) => try: () => { const fdPath = resolveFdPath(fd); if (fdPath === undefined) { - const stream = new Net.Socket({ - fd, - readable: true, - writable: false, - }); - stream.setEncoding("utf8"); - return stream; + return makeDirectBootstrapStream(fd); } - const streamFd = NFS.openSync(fdPath, "r"); - return NFS.createReadStream("", { - fd: streamFd, - encoding: "utf8", - autoClose: true, - }); + let streamFd: number | undefined; + try { + streamFd = NFS.openSync(fdPath, "r"); + return NFS.createReadStream("", { + fd: streamFd, + encoding: "utf8", + autoClose: true, + }); + } catch (error) { + if (isBootstrapFdPathDuplicationError(error)) { + if (streamFd !== undefined) { + NFS.closeSync(streamFd); + } + return makeDirectBootstrapStream(fd); + } + throw error; + } }, catch: (error) => new BootstrapError({ @@ -131,6 +136,29 @@ const makeBootstrapInputStream = (fd: number) => }), }); +const makeDirectBootstrapStream = (fd: number): Readable => { + try { + return NFS.createReadStream("", { + fd, + encoding: "utf8", + autoClose: true, + }); + } catch { + const stream = new Net.Socket({ + fd, + readable: true, + writable: false, + }); + stream.setEncoding("utf8"); + return stream; + } +}; + +const isBootstrapFdPathDuplicationError = Predicate.compose( + Predicate.hasProperty("code"), + (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM", +); + export function resolveFdPath( fd: number, platform: NodeJS.Platform = process.platform, 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/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts index daa6eb5f4c..9fb2500ce4 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts @@ -61,6 +61,7 @@ function makeSnapshot(input: { }, createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", + archivedAt: null, deletedAt: null, messages: [], activities: [], diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts new file mode 100644 index 0000000000..7df1c71c23 --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -0,0 +1,122 @@ +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; +import { describe, expect } from "vitest"; + +import { checkpointRefForThreadTurn } from "../Utils.ts"; +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 "@t3tools/contracts"; +import { ServerConfig } from "../../config.ts"; +import { ThreadId } from "@t3tools/contracts"; + +const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-checkpoint-store-test-", +}); +const GitCoreTestLayer = GitCoreLive.pipe( + Layer.provide(ServerConfigLayer), + Layer.provide(NodeServices.layer), +); +const CheckpointStoreTestLayer = CheckpointStoreLive.pipe( + Layer.provide(GitCoreTestLayer), + Layer.provide(NodeServices.layer), +); +const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer); + +function makeTmpDir( + prefix = "checkpoint-store-test-", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + }); +} + +function writeTextFile( + filePath: string, + contents: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(filePath, contents); + }); +} + +function git( + cwd: string, + args: ReadonlyArray, +): Effect.Effect { + return Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "CheckpointStore.test.git", + cwd, + args, + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); +} + +function initRepoWithCommit( + cwd: string, +): Effect.Effect< + void, + GitCommandError | PlatformError.PlatformError, + GitCore | FileSystem.FileSystem +> { + return Effect.gen(function* () { + const core = yield* GitCore; + yield* core.initRepo({ cwd }); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial commit"]); + }); +} + +function buildLargeText(lineCount = 20_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .concat("\n"); +} + +it.layer(TestLayer)("CheckpointStoreLive", (it) => { + describe("diffCheckpoints", () => { + it.effect("returns full oversized checkpoint diffs without truncation", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const checkpointStore = yield* CheckpointStore; + const threadId = ThreadId.makeUnsafe("thread-checkpoint-store"); + const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0); + const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); + + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: fromCheckpointRef, + }); + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: toCheckpointRef, + }); + + const diff = yield* checkpointStore.diffCheckpoints({ + cwd: tmp, + fromCheckpointRef, + toCheckpointRef, + }); + + expect(diff).toContain("diff --git"); + expect(diff).not.toContain("[truncated]"); + expect(diff).toContain("+line 19999"); + }), + ); + }); +}); 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/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.ts index 680d9d9608..2f740a7407 100644 --- a/apps/server/src/codexAppServerManager.test.ts +++ b/apps/server/src/codexAppServerManager.test.ts @@ -207,6 +207,42 @@ describe("classifyCodexStderrLine", () => { }); }); +describe("process stderr events", () => { + it("emits classified stderr lines as notifications", () => { + const manager = new CodexAppServerManager(); + const emitEvent = vi + .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent") + .mockImplementation(() => {}); + + ( + manager as unknown as { + emitNotificationEvent: ( + context: { session: { threadId: ThreadId } }, + method: string, + message: string, + ) => void; + } + ).emitNotificationEvent( + { + session: { + threadId: asThreadId("thread-1"), + }, + }, + "process/stderr", + "fatal: permission denied", + ); + + expect(emitEvent).toHaveBeenCalledWith( + expect.objectContaining({ + kind: "notification", + method: "process/stderr", + threadId: "thread-1", + message: "fatal: permission denied", + }), + ); + }); +}); + describe("normalizeCodexModelSlug", () => { it("maps 5.3 aliases to gpt-5.3-codex", () => { expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex"); @@ -274,7 +310,7 @@ describe("readCodexAccountSnapshot", () => { }); }); - it("keeps spark enabled for api key accounts", () => { + it("disables spark for api key accounts", () => { expect( readCodexAccountSnapshot({ type: "apiKey", @@ -282,7 +318,20 @@ describe("readCodexAccountSnapshot", () => { ).toEqual({ type: "apiKey", planType: null, - sparkEnabled: true, + sparkEnabled: false, + }); + }); + + it("disables spark for unknown chatgpt plans", () => { + expect( + readCodexAccountSnapshot({ + type: "chatgpt", + email: "unknown@example.com", + }), + ).toEqual({ + type: "chatgpt", + planType: "unknown", + sparkEnabled: false, }); }); }); @@ -307,6 +356,16 @@ describe("resolveCodexModelForAccount", () => { }), ).toBe("gpt-5.3-codex-spark"); }); + + it("falls back from spark to default for api key auth", () => { + expect( + resolveCodexModelForAccount("gpt-5.3-codex-spark", { + type: "apiKey", + planType: null, + sparkEnabled: false, + }), + ).toBe("gpt-5.3-codex"); + }); }); describe("startSession", () => { diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index 991a9783df..3145038647 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -26,6 +26,15 @@ import { isCodexCliVersionSupported, parseCodexCliVersion, } from "./provider/codexCliVersion"; +import { + readCodexAccountSnapshot, + resolveCodexModelForAccount, + type CodexAccountSnapshot, +} from "./provider/codexAccount"; +import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer"; + +export { buildCodexInitializeParams } from "./provider/codexAppServer"; +export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount"; type PendingRequestKey = string; @@ -96,23 +105,6 @@ interface JsonRpcNotification { params?: unknown; } -type CodexPlanType = - | "free" - | "go" - | "plus" - | "pro" - | "team" - | "business" - | "enterprise" - | "edu" - | "unknown"; - -interface CodexAccountSnapshot { - readonly type: "apiKey" | "chatgpt" | "unknown"; - readonly planType: CodexPlanType | null; - readonly sparkEnabled: boolean; -} - export interface CodexAppServerSendTurnInput { readonly threadId: ThreadId; readonly input?: string; @@ -162,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ "unknown thread", "does not exist", ]; -const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; -const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; -const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set(["free", "go", "plus"]); - -function asObject(value: unknown): Record | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - return value as Record; -} - -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot { - const record = asObject(response); - const account = asObject(record?.account) ?? record; - const accountType = asString(account?.type); - - if (accountType === "apiKey") { - return { - type: "apiKey", - planType: null, - sparkEnabled: true, - }; - } - - if (accountType === "chatgpt") { - const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; - return { - type: "chatgpt", - planType, - sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType), - }; - } - - return { - type: "unknown", - planType: null, - sparkEnabled: true, - }; -} - export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. @@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { }; } -export function resolveCodexModelForAccount( - model: string | undefined, - account: CodexAccountSnapshot, -): string | undefined { - if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { - return model; - } - - return CODEX_DEFAULT_MODEL; -} - /** * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` * wrapper, leaving the actual command running. Use `taskkill /T` to kill the * entire process tree instead. */ function killChildTree(child: ChildProcessWithoutNullStreams): void { - if (process.platform === "win32" && child.pid !== undefined) { - try { - spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); - return; - } catch { - // fallback to direct kill - } - } - child.kill(); + killCodexChildProcess(child); } export function normalizeCodexModelSlug( @@ -402,19 +331,6 @@ export function normalizeCodexModelSlug( return normalized; } -export function buildCodexInitializeParams() { - return { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: true, - }, - } as const; -} - function buildCodexCollaborationMode(input: { readonly interactionMode?: "default" | "plan"; readonly model?: string; @@ -1046,7 +962,7 @@ export class CodexAppServerManager extends EventEmitter()("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.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts index 29ae4796fe..0847134698 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts @@ -5,6 +5,7 @@ import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; +import { sanitizeThreadTitle } from "../Utils.ts"; import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -247,4 +248,62 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { }), ), ); + + it.effect("generates thread titles through the Claude provider", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: + ' "Reconnect failures after restart because the session state does not recover" ', + }, + }), + stdinMustContain: "You write concise thread titles for coding conversations.", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate reconnect failures after restarting the session.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe( + sanitizeThreadTitle( + '"Reconnect failures after restart because the session state does not recover"', + ), + ); + }), + ), + ); + + it.effect("falls back when Claude thread title normalization becomes whitespace-only", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: ' """ """ ', + }, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); }); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 6ffedbf7b4..7d620be3a6 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -11,23 +11,27 @@ import { Effect, Layer, Option, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ClaudeModelSelection } from "@t3tools/contracts"; +import { resolveApiModelId } from "@t3tools/shared/model"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; -import { TextGenerationError } from "../Errors.ts"; +import { TextGenerationError } from "@t3tools/contracts"; import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts"; import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "../Prompts.ts"; import { normalizeCliError, sanitizeCommitSubject, sanitizePrTitle, + sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts"; +import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts"; const CLAUDE_TIMEOUT_MS = 180_000; @@ -69,7 +73,11 @@ const makeClaudeTextGeneration = Effect.gen(function* () { outputSchemaJson, modelSelection, }: { - operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName"; + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; cwd: string; prompt: string; outputSchemaJson: S; @@ -77,8 +85,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () { }): Effect.Effect => Effect.gen(function* () { const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson)); - const normalizedOptions = normalizeClaudeModelOptions( - modelSelection.model, + const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities( + getClaudeModelCapabilities(modelSelection.model), modelSelection.options, ); const settings = { @@ -103,7 +111,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { "--json-schema", jsonSchemaStr, "--model", - modelSelection.model, + resolveApiModelId(modelSelection), ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), "--dangerously-skip-permissions", @@ -298,10 +306,39 @@ const makeClaudeTextGeneration = Effect.gen(function* () { }; }); + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "ClaudeTextGeneration.generateThreadTitle", + )(function* (input) { + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + }; + }); + return { generateCommitMessage, generatePrContent, generateBranchName, + generateThreadTitle, } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 1b07d87d90..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"; @@ -358,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { ), ); + it.effect("generates thread titles and trims them for sidebar use", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: + ' "Investigate websocket reconnect regressions after worktree restore" \nignored line', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate websocket reconnect regressions after a worktree restore.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("Investigate websocket reconnect regressions aft..."); + }), + ), + ); + + it.effect("falls back when thread title normalization becomes whitespace-only", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ' """ """ ', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); + + it.effect("trims whitespace exposed after quote removal in thread titles", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ` "' hello world '" `, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("hello world"); + }), + ), + ); + it.effect("omits attachment metadata section when no attachments are provided", () => withFakeCodexEnv( { diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 8f332bf13e..9bd838773b 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -8,9 +8,10 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar 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, type TextGenerationShape, TextGeneration, } from "../Services/TextGeneration.ts"; @@ -18,19 +19,21 @@ import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "../Prompts.ts"; import { normalizeCliError, sanitizeCommitSubject, sanitizePrTitle, + sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts"; +import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; - const makeCodexTextGeneration = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -83,7 +86,11 @@ const makeCodexTextGeneration = Effect.gen(function* () { fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void)); const materializeImageAttachments = ( - _operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName", + _operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle", attachments: BranchNameGenerationInput["attachments"], ): Effect.Effect => Effect.gen(function* () { @@ -124,7 +131,11 @@ const makeCodexTextGeneration = Effect.gen(function* () { cleanupPaths = [], modelSelection, }: { - operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName"; + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; cwd: string; prompt: string; outputSchemaJson: S; @@ -146,8 +157,8 @@ const makeCodexTextGeneration = Effect.gen(function* () { ).pipe(Effect.catch(() => Effect.undefined)); const runCodexCommand = Effect.gen(function* () { - const normalizedOptions = normalizeCodexModelOptions( - modelSelection.model, + const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( + getCodexModelCapabilities(modelSelection.model), modelSelection.options, ); const reasoningEffort = @@ -363,10 +374,44 @@ const makeCodexTextGeneration = Effect.gen(function* () { }; }); + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "CodexTextGeneration.generateThreadTitle", + )(function* (input) { + const { imagePaths } = yield* materializeImageAttachments( + "generateThreadTitle", + input.attachments, + ); + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + imagePaths, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + } satisfies ThreadTitleGenerationResult; + }); + return { generateCommitMessage, generatePrContent, generateBranchName, + generateThreadTitle, } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 635b9e8bc4..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"; @@ -132,6 +132,19 @@ function commitWithDate( }); } +function buildLargeText(lineCount = 20_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .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) => { @@ -175,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", () => { @@ -307,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(); @@ -415,6 +535,9 @@ it.layer(TestLayer)("git integration", (it) => { it.effect("refreshes upstream behind count after checkout when remote branch advanced", () => Effect.gen(function* () { + const services = yield* Effect.services(); + const runPromise = Effect.runPromiseWith(services); + const remote = yield* makeTmpDir(); const source = yield* makeTmpDir(); const clone = yield* makeTmpDir(); @@ -448,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 Effect.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, + }, + ), ); }), ); @@ -532,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); }); @@ -585,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); @@ -1667,6 +1808,40 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + expect(context!.stagedSummary).toContain("README.md"); + expect(context!.stagedPatch).toContain("[truncated]"); + }), + ); + + it.effect("readRangeContext truncates oversized diff patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText()); + yield* git(tmp, ["add", "large.txt"]); + yield* git(tmp, ["commit", "-m", "Add large range context"]); + + const rangeContext = yield* core.readRangeContext(tmp, initialBranch); + expect(rangeContext.commitSummary).toContain("Add large range context"); + expect(rangeContext.diffSummary).toContain("large.txt"); + expect(rangeContext.diffPatch).toContain("[truncated]"); + }), + ); + it.effect("pushes with upstream setup and then skips when up to date", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -1781,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 8bb5844228..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, @@ -32,6 +32,13 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson"; const DEFAULT_TIMEOUT_MS = 30_000; const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; +const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; +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; @@ -50,9 +57,12 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{ }> {} interface ExecuteGitOptions { + stdin?: string | undefined; timeoutMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorMessage?: string | undefined; + maxOutputBytes?: number | undefined; + truncateOutputAtMaxBytes?: boolean | undefined; progress?: ExecuteGitProgress | undefined; } @@ -89,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(); @@ -287,7 +338,7 @@ function trace2ChildKey(record: Record): string | null { const Trace2Record = Schema.Record(Schema.String, Schema.Unknown); -const createTrace2Monitor = Effect.fn(function* ( +const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( input: Pick, progress: ExecuteGitProgress | undefined, ): Effect.fn.Return< @@ -314,61 +365,58 @@ const createTrace2Monitor = Effect.fn(function* ( remainder: "", }); - const handleTraceLine = (line: string) => - Effect.gen(function* () { - const trimmedLine = line.trim(); - if (trimmedLine.length === 0) { - return; - } + const handleTraceLine = Effect.fn("handleTraceLine")(function* (line: string) { + const trimmedLine = line.trim(); + if (trimmedLine.length === 0) { + return; + } - const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); - if (Result.isFailure(traceRecord)) { - yield* Effect.logDebug( - `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, - traceRecord.failure, - ); - return; - } + const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); + if (Result.isFailure(traceRecord)) { + yield* Effect.logDebug( + `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, + traceRecord.failure, + ); + return; + } - if (traceRecord.success.child_class !== "hook") { - return; - } + if (traceRecord.success.child_class !== "hook") { + return; + } - const event = traceRecord.success.event; - const childKey = trace2ChildKey(traceRecord.success); - if (childKey === null) { - return; - } - const started = hookStartByChildKey.get(childKey); - const hookNameFromEvent = - typeof traceRecord.success.hook_name === "string" - ? traceRecord.success.hook_name.trim() - : ""; - const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); - if (hookName.length === 0) { - return; - } + const event = traceRecord.success.event; + const childKey = trace2ChildKey(traceRecord.success); + if (childKey === null) { + return; + } + const started = hookStartByChildKey.get(childKey); + const hookNameFromEvent = + typeof traceRecord.success.hook_name === "string" ? traceRecord.success.hook_name.trim() : ""; + const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); + if (hookName.length === 0) { + return; + } - if (event === "child_start") { - hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); - if (progress.onHookStarted) { - yield* progress.onHookStarted(hookName); - } - return; + if (event === "child_start") { + hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); + if (progress.onHookStarted) { + yield* progress.onHookStarted(hookName); } + return; + } - if (event === "child_exit") { - hookStartByChildKey.delete(childKey); - if (progress.onHookFinished) { - const code = traceRecord.success.code; - yield* progress.onHookFinished({ - hookName: started?.hookName ?? hookName, - exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, - durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, - }); - } + if (event === "child_exit") { + hookStartByChildKey.delete(childKey); + if (progress.onHookFinished) { + const code = traceRecord.success.code; + yield* progress.onHookFinished({ + hookName: started?.hookName ?? hookName, + exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, + durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, + }); } - }); + } + }); const deltaMutex = yield* Semaphore.make(1); const readTraceDelta = deltaMutex.withPermit( @@ -411,21 +459,21 @@ const createTrace2Monitor = Effect.fn(function* ( return readTraceDelta; }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - yield* readTraceDelta; - const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ - remainder.trim(), - { - processedChars, - remainder: "", - }, - ]); - if (finalLine.length > 0) { - yield* handleTraceLine(finalLine); - } - }), - ); + const finalizeTrace2Monitor = Effect.fn("finalizeTrace2Monitor")(function* () { + yield* readTraceDelta; + const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ + remainder.trim(), + { + processedChars, + remainder: "", + }, + ]); + if (finalLine.length > 0) { + yield* handleTraceLine(finalLine); + } + }); + + yield* Effect.addFinalizer(finalizeTrace2Monitor); return { env: { @@ -435,1387 +483,1518 @@ const createTrace2Monitor = Effect.fn(function* ( }; }); -const collectOutput = Effect.fn(function* ( +const collectOutput = Effect.fn("collectOutput")(function* ( input: Pick, stream: Stream.Stream, 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 = ""; let lineBuffer = ""; + let truncated = false; - const emitCompleteLines = (flush: boolean) => - Effect.gen(function* () { - let newlineIndex = lineBuffer.indexOf("\n"); - while (newlineIndex >= 0) { - const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); - lineBuffer = lineBuffer.slice(newlineIndex + 1); - if (line.length > 0 && onLine) { - yield* onLine(line); - } - newlineIndex = lineBuffer.indexOf("\n"); + const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) { + let newlineIndex = lineBuffer.indexOf("\n"); + while (newlineIndex >= 0) { + const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); + lineBuffer = lineBuffer.slice(newlineIndex + 1); + if (line.length > 0 && onLine) { + yield* onLine(line); } + newlineIndex = lineBuffer.indexOf("\n"); + } - if (flush) { - const trailing = lineBuffer.replace(/\r$/, ""); - lineBuffer = ""; - if (trailing.length > 0 && onLine) { - yield* onLine(trailing); - } + if (flush) { + const trailing = lineBuffer.replace(/\r$/, ""); + lineBuffer = ""; + if (trailing.length > 0 && onLine) { + yield* onLine(trailing); } - }); + } + }); - yield* Stream.runForEach(stream, (chunk) => - Effect.gen(function* () { - bytes += chunk.byteLength; - if (bytes > maxOutputBytes) { - return yield* new GitCommandError({ - operation: input.operation, - command: quoteGitCommand(input.args), - cwd: input.cwd, - detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, - }); - } - const decoded = decoder.decode(chunk, { stream: true }); - text += decoded; - lineBuffer += decoded; - yield* emitCompleteLines(false); - }), - ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed."))); - - const remainder = decoder.decode(); - text += remainder; - lineBuffer += remainder; - yield* emitCompleteLines(true); - return text; -}); - -export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"] }) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { worktreesDir } = yield* ServerConfig; - - let execute: GitCoreShape["execute"]; - - if (options?.executeOverride) { - execute = options.executeOverride; - } else { - const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - execute = Effect.fnUntraced(function* (input) { - const commandInput = { - ...input, - args: [...input.args], - } as const; - const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; - - const commandEffect = Effect.gen(function* () { - const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( - Effect.provideService(Path.Path, path), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), - ); - const child = yield* commandSpawner - .spawn( - ChildProcess.make("git", commandInput.args, { - cwd: commandInput.cwd, - env: { - ...process.env, - ...input.env, - ...trace2Monitor.env, - }, - }), - ) - .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); - - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectOutput( - commandInput, - child.stdout, - maxOutputBytes, - input.progress?.onStdoutLine, - ), - collectOutput( - commandInput, - child.stderr, - maxOutputBytes, - input.progress?.onStderrLine, - ), - child.exitCode.pipe( - Effect.map((value) => Number(value)), - Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), - ), - ], - { concurrency: "unbounded" }, - ); - yield* trace2Monitor.flush; - - if (!input.allowNonZeroExit && exitCode !== 0) { - const trimmedStderr = stderr.trim(); - return yield* new GitCommandError({ - operation: commandInput.operation, - command: quoteGitCommand(commandInput.args), - cwd: commandInput.cwd, - detail: - trimmedStderr.length > 0 - ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` - : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, - }); - } - - return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; - }); - - return yield* commandEffect.pipe( - Effect.scoped, - Effect.timeoutOption(timeoutMs), - Effect.flatMap((result) => - Option.match(result, { - onNone: () => - Effect.fail( - new GitCommandError({ - operation: commandInput.operation, - command: quoteGitCommand(commandInput.args), - cwd: commandInput.cwd, - detail: `${quoteGitCommand(commandInput.args)} timed out.`, - }), - ), - onSome: Effect.succeed, - }), - ), - ); + const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) { + if (truncateOutputAtMaxBytes && truncated) { + return; + } + const nextBytes = bytes + chunk.byteLength; + if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { + return yield* new GitCommandError({ + operation: input.operation, + command: quoteGitCommand(input.args), + cwd: input.cwd, + detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, }); } - const executeGit = ( - operation: string, - cwd: string, - args: readonly string[], - options: ExecuteGitOptions = {}, - ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => - execute({ - operation, - cwd, - args, - allowNonZeroExit: true, - ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(options.progress ? { progress: options.progress } : {}), - }).pipe( - Effect.flatMap((result) => { - if (options.allowNonZeroExit || result.code === 0) { - return Effect.succeed(result); - } - const stderr = result.stderr.trim(); - if (stderr.length > 0) { - return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); - } - if (options.fallbackErrorMessage) { - return Effect.fail( - createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), - ); - } - return Effect.fail( - createGitCommandError( - operation, - cwd, - args, - `${commandLabel(args)} failed: code=${result.code ?? "null"}`, + const chunkToDecode = + truncateOutputAtMaxBytes && nextBytes > maxOutputBytes + ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) + : chunk; + bytes += chunkToDecode.byteLength; + truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; + + const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); + text += decoded; + lineBuffer += decoded; + yield* emitCompleteLines(false); + }); + + yield* Stream.runForEach(stream, processChunk).pipe( + Effect.mapError(toGitCommandError(input, "output stream failed.")), + ); + + const remainder = truncated ? "" : decoder.decode(); + text += remainder; + lineBuffer += remainder; + yield* emitCompleteLines(true); + return { + text, + truncated, + }; +}); + +export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { + executeOverride?: GitCoreShape["execute"]; +}) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { worktreesDir } = yield* ServerConfig; + + let execute: GitCoreShape["execute"]; + + if (options?.executeOverride) { + execute = options.executeOverride; + } else { + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + execute = Effect.fnUntraced(function* (input) { + const commandInput = { + ...input, + args: [...input.args], + } as const; + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; + + const runGitCommand = Effect.fn("runGitCommand")(function* () { + const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( + Effect.provideService(Path.Path, path), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), + ); + const child = yield* commandSpawner + .spawn( + ChildProcess.make("git", commandInput.args, { + cwd: commandInput.cwd, + env: { + ...process.env, + ...input.env, + ...trace2Monitor.env, + }, + }), + ) + .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); + + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectOutput( + commandInput, + child.stdout, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStdoutLine, ), - ); - }), - ); - - const runGit = ( - operation: string, - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Effect.Effect => - executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); - - const runGitStdout = ( - operation: string, - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Effect.Effect => - executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( - Effect.map((result) => result.stdout), - ); - - const branchExists = (cwd: string, branch: string): Effect.Effect => - executeGit( - "GitCore.branchExists", - cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], - { - allowNonZeroExit: true, - timeoutMs: 5_000, - }, - ).pipe(Effect.map((result) => result.code === 0)); - - const resolveAvailableBranchName = ( - cwd: string, - desiredBranch: string, - ): Effect.Effect => - Effect.gen(function* () { - const isDesiredTaken = yield* branchExists(cwd, desiredBranch); - if (!isDesiredTaken) { - return desiredBranch; - } - - for (let suffix = 1; suffix <= 100; suffix += 1) { - const candidate = `${desiredBranch}-${suffix}`; - const isCandidateTaken = yield* branchExists(cwd, candidate); - if (!isCandidateTaken) { - return candidate; - } - } - - return yield* createGitCommandError( - "GitCore.renameBranch", - cwd, - ["branch", "-m", "--", desiredBranch], - `Could not find an available branch name for '${desiredBranch}'.`, - ); - }); - - const resolveCurrentUpstream = ( - cwd: string, - ): Effect.Effect< - { upstreamRef: string; remoteName: string; upstreamBranch: string } | null, - GitCommandError - > => - Effect.gen(function* () { - const upstreamRef = yield* runGitStdout( - "GitCore.resolveCurrentUpstream", - cwd, - ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { - return null; - } - - const separatorIndex = upstreamRef.indexOf("/"); - if (separatorIndex <= 0) { - return null; - } - const remoteName = upstreamRef.slice(0, separatorIndex); - const upstreamBranch = upstreamRef.slice(separatorIndex + 1); - if (remoteName.length === 0 || upstreamBranch.length === 0) { - return null; - } - - return { - upstreamRef, - remoteName, - upstreamBranch, - }; - }); - - const fetchUpstreamRef = ( - cwd: string, - upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, - ): Effect.Effect => { - const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; - return runGit( - "GitCore.fetchUpstreamRef", - cwd, - ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], - true, - ); - }; - - const fetchUpstreamRefForStatus = ( - cwd: string, - upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, - ): Effect.Effect => { - const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; - return executeGit( - "GitCore.fetchUpstreamRefForStatus", - cwd, - ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], - { - allowNonZeroExit: true, - timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), - }, - ).pipe(Effect.asVoid); - }; - - const statusUpstreamRefreshCache = yield* Cache.makeWith({ - capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, - lookup: (cacheKey: StatusUpstreamRefreshCacheKey) => - Effect.gen(function* () { - yield* fetchUpstreamRefForStatus(cacheKey.cwd, { - upstreamRef: cacheKey.upstreamRef, - remoteName: cacheKey.remoteName, - upstreamBranch: cacheKey.upstreamBranch, - }); - return true as const; - }), - // Keep successful refreshes warm; drop failures immediately so next request can retry. - timeToLive: (exit) => - Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero, - }); - - const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect => - Effect.gen(function* () { - const upstream = yield* resolveCurrentUpstream(cwd); - if (!upstream) return; - yield* Cache.get( - statusUpstreamRefreshCache, - new StatusUpstreamRefreshCacheKey({ - cwd, - upstreamRef: upstream.upstreamRef, - remoteName: upstream.remoteName, - upstreamBranch: upstream.upstreamBranch, - }), - ); - }); - - const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect => - Effect.gen(function* () { - const upstream = yield* resolveCurrentUpstream(cwd); - if (!upstream) return; - yield* fetchUpstreamRef(cwd, upstream); - }); - - const resolveDefaultBranchName = ( - cwd: string, - remoteName: string, - ): Effect.Effect => - executeGit( - "GitCore.resolveDefaultBranchName", - cwd, - ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], - { allowNonZeroExit: true }, - ).pipe( - Effect.map((result) => { - if (result.code !== 0) { - return null; - } - return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); - }), - ); - - const remoteBranchExists = ( - cwd: string, - remoteName: string, - branch: string, - ): Effect.Effect => - executeGit( - "GitCore.remoteBranchExists", - cwd, - ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], - { - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)); - - const originRemoteExists = (cwd: string): Effect.Effect => - executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { - allowNonZeroExit: true, - }).pipe(Effect.map((result) => result.code === 0)); - - const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => - runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( - Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), - ); - - const resolvePrimaryRemoteName = (cwd: string): Effect.Effect => - Effect.gen(function* () { - if (yield* originRemoteExists(cwd)) { - return "origin"; - } - const remotes = yield* listRemoteNames(cwd); - const [firstRemote] = remotes; - if (firstRemote) { - return firstRemote; - } - return yield* createGitCommandError( - "GitCore.resolvePrimaryRemoteName", - cwd, - ["remote"], - "No git remote is configured for this repository.", - ); - }); - - const resolvePushRemoteName = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const branchPushRemote = yield* runGitStdout( - "GitCore.resolvePushRemoteName.branchPushRemote", - cwd, - ["config", "--get", `branch.${branch}.pushRemote`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (branchPushRemote.length > 0) { - return branchPushRemote; - } - - const pushDefaultRemote = yield* runGitStdout( - "GitCore.resolvePushRemoteName.remotePushDefault", - cwd, - ["config", "--get", "remote.pushDefault"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (pushDefaultRemote.length > 0) { - return pushDefaultRemote; - } - - return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); - }); - - const ensureRemote: GitCoreShape["ensureRemote"] = (input) => - Effect.gen(function* () { - const preferredName = sanitizeRemoteName(input.preferredName); - const normalizedTargetUrl = normalizeRemoteUrl(input.url); - const remoteFetchUrls = yield* runGitStdout( - "GitCore.ensureRemote.listRemoteUrls", - input.cwd, - ["remote", "-v"], - ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); - - for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { - if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { - return remoteName; - } - } - - let remoteName = preferredName; - let suffix = 1; - while (remoteFetchUrls.has(remoteName)) { - remoteName = `${preferredName}-${suffix}`; - suffix += 1; - } - - yield* runGit("GitCore.ensureRemote.add", input.cwd, [ - "remote", - "add", - remoteName, - input.url, - ]); - return remoteName; - }); - - const resolveBaseBranchForNoUpstream = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const configuredBaseBranch = yield* runGitStdout( - "GitCore.resolveBaseBranchForNoUpstream.config", - cwd, - ["config", "--get", `branch.${branch}.gh-merge-base`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - const defaultBranch = - primaryRemoteName === null - ? null - : yield* resolveDefaultBranchName(cwd, primaryRemoteName); - const candidates = [ - configuredBaseBranch.length > 0 ? configuredBaseBranch : null, - defaultBranch, - ...DEFAULT_BASE_BRANCH_CANDIDATES, - ]; - - for (const candidate of candidates) { - if (!candidate) { - continue; - } - - const remotePrefix = - primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; - const normalizedCandidate = candidate.startsWith("origin/") - ? candidate.slice("origin/".length) - : remotePrefix && candidate.startsWith(remotePrefix) - ? candidate.slice(remotePrefix.length) - : candidate; - if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { - continue; - } - - if (yield* branchExists(cwd, normalizedCandidate)) { - return normalizedCandidate; - } - - if ( - primaryRemoteName && - (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) - ) { - return `${primaryRemoteName}/${normalizedCandidate}`; - } - } - - return null; - }); - - const computeAheadCountAgainstBase = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); - if (!baseBranch) { - return 0; - } - - const result = yield* executeGit( - "GitCore.computeAheadCountAgainstBase", - cwd, - ["rev-list", "--count", `${baseBranch}..HEAD`], - { allowNonZeroExit: true }, - ); - if (result.code !== 0) { - return 0; - } - - const parsed = Number.parseInt(result.stdout.trim(), 10); - return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; - }); - - const readBranchRecency = (cwd: string): Effect.Effect, GitCommandError> => - Effect.gen(function* () { - const branchRecency = yield* executeGit( - "GitCore.readBranchRecency", - cwd, - [ - "for-each-ref", - "--format=%(refname:short)%09%(committerdate:unix)", - "refs/heads", - "refs/remotes", - ], - { - timeoutMs: 15_000, - allowNonZeroExit: true, - }, - ); - - const branchLastCommit = new Map(); - if (branchRecency.code !== 0) { - return branchLastCommit; - } - - for (const line of branchRecency.stdout.split("\n")) { - if (line.length === 0) { - continue; - } - const [name, lastCommitRaw] = line.split("\t"); - if (!name) { - continue; - } - const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); - branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); - } - - return branchLastCommit; - }); - - const statusDetails: GitCoreShape["statusDetails"] = (cwd) => - Effect.gen(function* () { - yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); - - const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( - [ - runGitStdout("GitCore.statusDetails.status", cwd, [ - "status", - "--porcelain=2", - "--branch", - ]), - runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), - runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [ - "diff", - "--cached", - "--numstat", - ]), + collectOutput( + commandInput, + child.stderr, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStderrLine, + ), + child.exitCode.pipe( + 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; - let branch: string | null = null; - let upstreamRef: string | null = null; - let aheadCount = 0; - let behindCount = 0; - let hasWorkingTreeChanges = false; - const changedFilesWithoutNumstat = new Set(); - - for (const line of statusStdout.split(/\r?\n/g)) { - if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); - branch = value.startsWith("(") ? null : value; - continue; - } - if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); - upstreamRef = value.length > 0 ? value : null; - continue; - } - if (line.startsWith("# branch.ab ")) { - const value = line.slice("# branch.ab ".length).trim(); - const parsed = parseBranchAb(value); - aheadCount = parsed.ahead; - behindCount = parsed.behind; - continue; - } - if (line.trim().length > 0 && !line.startsWith("#")) { - hasWorkingTreeChanges = true; - const pathValue = parsePorcelainPath(line); - if (pathValue) changedFilesWithoutNumstat.add(pathValue); - } + if (!input.allowNonZeroExit && exitCode !== 0) { + const trimmedStderr = stderr.text.trim(); + return yield* new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: + trimmedStderr.length > 0 + ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` + : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, + }); } - if (!upstreamRef && branch) { - aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(0)), - ); - behindCount = 0; - } - - const stagedEntries = parseNumstatEntries(stagedNumstatStdout); - const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); - const fileStatMap = new Map(); - for (const entry of [...stagedEntries, ...unstagedEntries]) { - const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; - existing.insertions += entry.insertions; - existing.deletions += entry.deletions; - fileStatMap.set(entry.path, existing); - } - - let insertions = 0; - let deletions = 0; - const files = Array.from(fileStatMap.entries()) - .map(([filePath, stat]) => { - insertions += stat.insertions; - deletions += stat.deletions; - return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; - }) - .toSorted((a, b) => a.path.localeCompare(b.path)); - - for (const filePath of changedFilesWithoutNumstat) { - if (fileStatMap.has(filePath)) continue; - files.push({ path: filePath, insertions: 0, deletions: 0 }); - } - files.sort((a, b) => a.path.localeCompare(b.path)); - return { - branch, - upstreamRef, - hasWorkingTreeChanges, - workingTree: { - files, - insertions, - deletions, - }, - hasUpstream: upstreamRef !== null, - aheadCount, - behindCount, - }; + code: exitCode, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + } satisfies ExecuteGitResult; }); - const status: GitCoreShape["status"] = (input) => - statusDetails(input.cwd).pipe( - Effect.map((details) => ({ - branch: details.branch, - hasWorkingTreeChanges: details.hasWorkingTreeChanges, - workingTree: details.workingTree, - hasUpstream: details.hasUpstream, - aheadCount: details.aheadCount, - behindCount: details.behindCount, - pr: null, - })), + return yield* runGitCommand().pipe( + Effect.scoped, + Effect.timeoutOption(timeoutMs), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => + Effect.fail( + new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: `${quoteGitCommand(commandInput.args)} timed out.`, + }), + ), + onSome: Effect.succeed, + }), + ), ); + }); + } - const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) => - Effect.gen(function* () { - if (filePaths && filePaths.length > 0) { - yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( - Effect.catch(() => Effect.void), - ); - yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ - "add", - "-A", - "--", - ...filePaths, - ]); - } else { - yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); + const executeGit = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): 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 } : {}), + ...(options.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } + : {}), + ...(options.progress ? { progress: options.progress } : {}), + }).pipe( + Effect.flatMap((result) => { + if (options.allowNonZeroExit || result.code === 0) { + return Effect.succeed(result); } + const stderr = result.stderr.trim(); + if (stderr.length > 0) { + return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); + } + if (options.fallbackErrorMessage) { + return Effect.fail( + createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), + ); + } + return Effect.fail( + createGitCommandError( + operation, + cwd, + args, + `${commandLabel(args)} failed: code=${result.code ?? "null"}`, + ), + ); + }), + ); - const stagedSummary = yield* runGitStdout( - "GitCore.prepareCommitContext.stagedSummary", - cwd, - ["diff", "--cached", "--name-status"], - ).pipe(Effect.map((stdout) => stdout.trim())); - if (stagedSummary.length === 0) { + const runGit = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); + + const runGitStdout = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( + Effect.map((result) => result.stdout), + ); + + const runGitStdoutWithOptions = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + 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( + "GitCore.branchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], + { + allowNonZeroExit: true, + timeoutMs: 5_000, + }, + ).pipe(Effect.map((result) => result.code === 0)); + + const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( + cwd: string, + desiredBranch: string, + ) { + const isDesiredTaken = yield* branchExists(cwd, desiredBranch); + if (!isDesiredTaken) { + return desiredBranch; + } + + for (let suffix = 1; suffix <= 100; suffix += 1) { + const candidate = `${desiredBranch}-${suffix}`; + const isCandidateTaken = yield* branchExists(cwd, candidate); + if (!isCandidateTaken) { + return candidate; + } + } + + return yield* createGitCommandError( + "GitCore.renameBranch", + cwd, + ["branch", "-m", "--", desiredBranch], + `Could not find an available branch name for '${desiredBranch}'.`, + ); + }); + + const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (cwd: string) { + const upstreamRef = yield* runGitStdout( + "GitCore.resolveCurrentUpstream", + cwd, + ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { + return null; + } + + const separatorIndex = upstreamRef.indexOf("/"); + if (separatorIndex <= 0) { + return null; + } + const remoteName = upstreamRef.slice(0, separatorIndex); + const upstreamBranch = upstreamRef.slice(separatorIndex + 1); + if (remoteName.length === 0 || upstreamBranch.length === 0) { + return null; + } + + return { + upstreamRef, + remoteName, + upstreamBranch, + }; + }); + + const fetchUpstreamRef = ( + cwd: string, + upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, + ): Effect.Effect => { + const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + return runGit( + "GitCore.fetchUpstreamRef", + cwd, + ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + true, + ); + }; + + const fetchUpstreamRefForStatus = ( + cwd: string, + upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, + ): Effect.Effect => { + const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + return executeGit( + "GitCore.fetchUpstreamRefForStatus", + cwd, + ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + { + allowNonZeroExit: true, + timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), + }, + ).pipe(Effect.asVoid); + }; + + const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* ( + cacheKey: StatusUpstreamRefreshCacheKey, + ) { + yield* fetchUpstreamRefForStatus(cacheKey.cwd, { + upstreamRef: cacheKey.upstreamRef, + remoteName: cacheKey.remoteName, + upstreamBranch: cacheKey.upstreamBranch, + }); + return true as const; + }); + + const statusUpstreamRefreshCache = yield* Cache.makeWith({ + capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, + lookup: refreshStatusUpstreamCacheEntry, + // Keep successful refreshes warm; drop failures immediately so next request can retry. + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero), + }); + + const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( + cwd: string, + ) { + const upstream = yield* resolveCurrentUpstream(cwd); + if (!upstream) return; + yield* Cache.get( + statusUpstreamRefreshCache, + new StatusUpstreamRefreshCacheKey({ + cwd, + upstreamRef: upstream.upstreamRef, + remoteName: upstream.remoteName, + upstreamBranch: upstream.upstreamBranch, + }), + ); + }); + + const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* ( + cwd: string, + ) { + const upstream = yield* resolveCurrentUpstream(cwd); + if (!upstream) return; + yield* fetchUpstreamRef(cwd, upstream); + }); + + const resolveDefaultBranchName = ( + cwd: string, + remoteName: string, + ): Effect.Effect => + executeGit( + "GitCore.resolveDefaultBranchName", + cwd, + ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], + { allowNonZeroExit: true }, + ).pipe( + Effect.map((result) => { + if (result.code !== 0) { return null; } + return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); + }), + ); - const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [ - "diff", - "--cached", - "--patch", - "--minimal", - ]); + const remoteBranchExists = ( + cwd: string, + remoteName: string, + branch: string, + ): Effect.Effect => + executeGit( + "GitCore.remoteBranchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], + { + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)); - return { - stagedSummary, - stagedPatch, - }; - }); + const originRemoteExists = (cwd: string): Effect.Effect => + executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { + allowNonZeroExit: true, + }).pipe(Effect.map((result) => result.code === 0)); - const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) => - Effect.gen(function* () { - const args = ["commit", "-m", subject]; - const trimmedBody = body.trim(); - if (trimmedBody.length > 0) { - args.push("-m", trimmedBody); + const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => + runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( + Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), + ); + + const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { + if (yield* originRemoteExists(cwd)) { + return "origin"; + } + const remotes = yield* listRemoteNames(cwd); + const [firstRemote] = remotes; + if (firstRemote) { + return firstRemote; + } + return yield* createGitCommandError( + "GitCore.resolvePrimaryRemoteName", + cwd, + ["remote"], + "No git remote is configured for this repository.", + ); + }); + + const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( + cwd: string, + branch: string, + ) { + const branchPushRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.branchPushRemote", + cwd, + ["config", "--get", `branch.${branch}.pushRemote`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (branchPushRemote.length > 0) { + return branchPushRemote; + } + + const pushDefaultRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.remotePushDefault", + cwd, + ["config", "--get", "remote.pushDefault"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (pushDefaultRemote.length > 0) { + return pushDefaultRemote; + } + + return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); + }); + + const ensureRemote: GitCoreShape["ensureRemote"] = Effect.fn("ensureRemote")(function* (input) { + const preferredName = sanitizeRemoteName(input.preferredName); + const normalizedTargetUrl = normalizeRemoteUrl(input.url); + const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, [ + "remote", + "-v", + ]).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); + + for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { + if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { + return remoteName; + } + } + + let remoteName = preferredName; + let suffix = 1; + while (remoteFetchUrls.has(remoteName)) { + remoteName = `${preferredName}-${suffix}`; + suffix += 1; + } + + yield* runGit("GitCore.ensureRemote.add", input.cwd, ["remote", "add", remoteName, input.url]); + return remoteName; + }); + + const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( + cwd: string, + branch: string, + ) { + const configuredBaseBranch = yield* runGitStdout( + "GitCore.resolveBaseBranchForNoUpstream.config", + cwd, + ["config", "--get", `branch.${branch}.gh-merge-base`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + const defaultBranch = + primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName); + const candidates = [ + configuredBaseBranch.length > 0 ? configuredBaseBranch : null, + defaultBranch, + ...DEFAULT_BASE_BRANCH_CANDIDATES, + ]; + + for (const candidate of candidates) { + if (!candidate) { + continue; + } + + const remotePrefix = + primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; + const normalizedCandidate = candidate.startsWith("origin/") + ? candidate.slice("origin/".length) + : remotePrefix && candidate.startsWith(remotePrefix) + ? candidate.slice(remotePrefix.length) + : candidate; + if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { + continue; + } + + if (yield* branchExists(cwd, normalizedCandidate)) { + return normalizedCandidate; + } + + if ( + primaryRemoteName && + (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) + ) { + return `${primaryRemoteName}/${normalizedCandidate}`; + } + } + + return null; + }); + + const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* ( + cwd: string, + branch: string, + ) { + const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); + if (!baseBranch) { + return 0; + } + + const result = yield* executeGit( + "GitCore.computeAheadCountAgainstBase", + cwd, + ["rev-list", "--count", `${baseBranch}..HEAD`], + { allowNonZeroExit: true }, + ); + if (result.code !== 0) { + return 0; + } + + const parsed = Number.parseInt(result.stdout.trim(), 10); + return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; + }); + + const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) { + const branchRecency = yield* executeGit( + "GitCore.readBranchRecency", + cwd, + [ + "for-each-ref", + "--format=%(refname:short)%09%(committerdate:unix)", + "refs/heads", + "refs/remotes", + ], + { + timeoutMs: 15_000, + allowNonZeroExit: true, + }, + ); + + const branchLastCommit = new Map(); + if (branchRecency.code !== 0) { + return branchLastCommit; + } + + for (const line of branchRecency.stdout.split("\n")) { + if (line.length === 0) { + continue; + } + const [name, lastCommitRaw] = line.split("\t"); + if (!name) { + continue; + } + const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); + branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); + } + + return branchLastCommit; + }); + + const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); + + const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( + [ + runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]), + runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), + runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]), + ], + { concurrency: "unbounded" }, + ); + + let branch: string | null = null; + let upstreamRef: string | null = null; + let aheadCount = 0; + let behindCount = 0; + let hasWorkingTreeChanges = false; + const changedFilesWithoutNumstat = new Set(); + + for (const line of statusStdout.split(/\r?\n/g)) { + if (line.startsWith("# branch.head ")) { + const value = line.slice("# branch.head ".length).trim(); + branch = value.startsWith("(") ? null : value; + continue; + } + if (line.startsWith("# branch.upstream ")) { + const value = line.slice("# branch.upstream ".length).trim(); + upstreamRef = value.length > 0 ? value : null; + continue; + } + if (line.startsWith("# branch.ab ")) { + const value = line.slice("# branch.ab ".length).trim(); + const parsed = parseBranchAb(value); + aheadCount = parsed.ahead; + behindCount = parsed.behind; + continue; + } + if (line.trim().length > 0 && !line.startsWith("#")) { + hasWorkingTreeChanges = true; + const pathValue = parsePorcelainPath(line); + if (pathValue) changedFilesWithoutNumstat.add(pathValue); + } + } + + if (!upstreamRef && branch) { + aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(0)), + ); + behindCount = 0; + } + + const stagedEntries = parseNumstatEntries(stagedNumstatStdout); + const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); + const fileStatMap = new Map(); + for (const entry of [...stagedEntries, ...unstagedEntries]) { + const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; + existing.insertions += entry.insertions; + existing.deletions += entry.deletions; + fileStatMap.set(entry.path, existing); + } + + let insertions = 0; + let deletions = 0; + const files = Array.from(fileStatMap.entries()) + .map(([filePath, stat]) => { + insertions += stat.insertions; + deletions += stat.deletions; + return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; + }) + .toSorted((a, b) => a.path.localeCompare(b.path)); + + for (const filePath of changedFilesWithoutNumstat) { + if (fileStatMap.has(filePath)) continue; + files.push({ path: filePath, insertions: 0, deletions: 0 }); + } + files.sort((a, b) => a.path.localeCompare(b.path)); + + return { + branch, + upstreamRef, + hasWorkingTreeChanges, + workingTree: { + files, + insertions, + deletions, + }, + hasUpstream: upstreamRef !== null, + aheadCount, + behindCount, + }; + }); + + const status: GitCoreShape["status"] = (input) => + statusDetails(input.cwd).pipe( + Effect.map((details) => ({ + branch: details.branch, + hasWorkingTreeChanges: details.hasWorkingTreeChanges, + workingTree: details.workingTree, + hasUpstream: details.hasUpstream, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + pr: null, + })), + ); + + const prepareCommitContext: GitCoreShape["prepareCommitContext"] = Effect.fn( + "prepareCommitContext", + )(function* (cwd, filePaths) { + if (filePaths && filePaths.length > 0) { + yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( + Effect.catch(() => Effect.void), + ); + yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ + "add", + "-A", + "--", + ...filePaths, + ]); + } else { + yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); + } + + const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [ + "diff", + "--cached", + "--name-status", + ]).pipe(Effect.map((stdout) => stdout.trim())); + if (stagedSummary.length === 0) { + return null; + } + + const stagedPatch = yield* runGitStdoutWithOptions( + "GitCore.prepareCommitContext.stagedPatch", + cwd, + ["diff", "--cached", "--patch", "--minimal"], + { + maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + return { + stagedSummary, + stagedPatch, + }; + }); + + const commit: GitCoreShape["commit"] = Effect.fn("commit")(function* ( + cwd, + subject, + body, + options?: GitCommitOptions, + ) { + const args = ["commit", "-m", subject]; + const trimmedBody = body.trim(); + if (trimmedBody.length > 0) { + args.push("-m", trimmedBody); + } + const progress = + options?.progress?.onOutputLine === undefined + ? options?.progress + : { + ...options.progress, + onStdoutLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? Effect.void, + onStderrLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? Effect.void, + }; + yield* executeGit("GitCore.commit.commit", cwd, args, { + ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(progress ? { progress } : {}), + }).pipe(Effect.asVoid); + const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ + "rev-parse", + "HEAD", + ]).pipe(Effect.map((stdout) => stdout.trim())); + + return { commitSha }; + }); + + const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")( + function* (cwd, fallbackBranch) { + const details = yield* statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pushCurrentBranch", + cwd, + ["push"], + "Cannot push from detached HEAD.", + ); + } + + const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; + if (hasNoLocalDelta) { + if (details.hasUpstream) { + return { + status: "skipped_up_to_date" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + }; } - const progress = options?.progress - ? { - ...(options.progress.onOutputLine - ? { - onStdoutLine: (line: string) => - options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? - Effect.void, - onStderrLine: (line: string) => - options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? - Effect.void, - } - : {}), - ...(options.progress.onHookStarted - ? { onHookStarted: options.progress.onHookStarted } - : {}), - ...(options.progress.onHookFinished - ? { onHookFinished: options.progress.onHookFinished } - : {}), - } - : null; - yield* executeGit("GitCore.commit.commit", cwd, args, { - ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(progress ? { progress } : {}), - }).pipe(Effect.asVoid); - const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ - "rev-parse", - "HEAD", - ]).pipe(Effect.map((stdout) => stdout.trim())); - return { commitSha }; - }); + const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (comparableBaseBranch) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (!publishRemoteName) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } - const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) => - Effect.gen(function* () { - const details = yield* statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { + const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( + Effect.catch(() => Effect.succeed(false)), + ); + if (hasRemoteBranch) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } + } + } + + if (!details.hasUpstream) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); + if (!publishRemoteName) { return yield* createGitCommandError( "GitCore.pushCurrentBranch", cwd, ["push"], - "Cannot push from detached HEAD.", + "Cannot push because no git remote is configured for this repository.", ); } - - const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; - if (hasNoLocalDelta) { - if (details.hasUpstream) { - return { - status: "skipped_up_to_date" as const, - branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), - }; - } - - const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (comparableBaseBranch) { - const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (!publishRemoteName) { - return { - status: "skipped_up_to_date" as const, - branch, - }; - } - - const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( - Effect.catch(() => Effect.succeed(false)), - ); - if (hasRemoteBranch) { - return { - status: "skipped_up_to_date" as const, - branch, - }; - } - } - } - - if (!details.hasUpstream) { - const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); - if (!publishRemoteName) { - return yield* createGitCommandError( - "GitCore.pushCurrentBranch", - cwd, - ["push"], - "Cannot push because no git remote is configured for this repository.", - ); - } - yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ - "push", - "-u", - publishRemoteName, - branch, - ]); - return { - status: "pushed" as const, - branch, - upstreamBranch: `${publishRemoteName}/${branch}`, - setUpstream: true, - }; - } - - const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (currentUpstream) { - yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ - "push", - currentUpstream.remoteName, - `HEAD:${currentUpstream.upstreamBranch}`, - ]); - return { - status: "pushed" as const, - branch, - upstreamBranch: currentUpstream.upstreamRef, - setUpstream: false, - }; - } - - yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); + yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ + "push", + "-u", + publishRemoteName, + branch, + ]); return { status: "pushed" as const, branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + upstreamBranch: `${publishRemoteName}/${branch}`, + setUpstream: true, + }; + } + + const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (currentUpstream) { + yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ + "push", + currentUpstream.remoteName, + `HEAD:${currentUpstream.upstreamBranch}`, + ]); + return { + status: "pushed" as const, + branch, + upstreamBranch: currentUpstream.upstreamRef, setUpstream: false, }; - }); + } - const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) => - Effect.gen(function* () { - const details = yield* statusDetails(cwd); - const branch = details.branch; - if (!branch) { - return yield* createGitCommandError( - "GitCore.pullCurrentBranch", - cwd, - ["pull", "--ff-only"], - "Cannot pull from detached HEAD.", - ); - } - if (!details.hasUpstream) { - return yield* createGitCommandError( - "GitCore.pullCurrentBranch", - cwd, - ["pull", "--ff-only"], - "Current branch has no upstream configured. Push with upstream first.", - ); - } - const beforeSha = yield* runGitStdout( - "GitCore.pullCurrentBranch.beforeSha", + yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); + return { + status: "pushed" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + setUpstream: false, + }; + }, + ); + + const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = Effect.fn("pullCurrentBranch")( + function* (cwd) { + const details = yield* statusDetails(cwd); + const branch = details.branch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", cwd, - ["rev-parse", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { - timeoutMs: 30_000, - fallbackErrorMessage: "git pull failed", - }); - const afterSha = yield* runGitStdout( - "GitCore.pullCurrentBranch.afterSha", - cwd, - ["rev-parse", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - const refreshed = yield* statusDetails(cwd); - return { - status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", - branch, - upstreamBranch: refreshed.upstreamRef, - }; - }); - - const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) => - Effect.gen(function* () { - const range = `${baseBranch}..HEAD`; - const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( - [ - runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]), - runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]), - runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [ - "diff", - "--patch", - "--minimal", - range, - ]), - ], - { concurrency: "unbounded" }, + ["pull", "--ff-only"], + "Cannot pull from detached HEAD.", ); - - return { - commitSummary, - diffSummary, - diffPatch, - }; + } + if (!details.hasUpstream) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", + cwd, + ["pull", "--ff-only"], + "Current branch has no upstream configured. Push with upstream first.", + ); + } + const beforeSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.beforeSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { + timeoutMs: 30_000, + fallbackErrorMessage: "git pull failed", }); + const afterSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.afterSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); - const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => - runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), - Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + const refreshed = yield* statusDetails(cwd); + return { + status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", + branch, + upstreamBranch: refreshed.upstreamRef, + }; + }, + ); + + const readRangeContext: GitCoreShape["readRangeContext"] = Effect.fn("readRangeContext")( + function* (cwd, baseBranch) { + const range = `${baseBranch}..HEAD`; + const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( + [ + runGitStdoutWithOptions( + "GitCore.readRangeContext.log", + cwd, + ["log", "--oneline", range], + { + maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffStat", + cwd, + ["diff", "--stat", range], + { + maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffPatch", + cwd, + ["diff", "--patch", "--minimal", range], + { + maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + ], + { concurrency: "unbounded" }, ); - const listBranches: GitCoreShape["listBranches"] = (input) => - Effect.gen(function* () { - const branchRecencyPromise = readBranchRecency(input.cwd).pipe( - Effect.catch(() => Effect.succeed(new Map())), - ); - const localBranchResult = yield* executeGit( - "GitCore.listBranches.branchNoColor", - input.cwd, - ["branch", "--no-color"], - { - timeoutMs: 10_000, - allowNonZeroExit: true, - }, - ); + return { + commitSummary, + diffSummary, + diffPatch, + }; + }, + ); - if (localBranchResult.code !== 0) { - const stderr = localBranchResult.stderr.trim(); - if (stderr.toLowerCase().includes("not a git repository")) { - return { branches: [], isRepo: false, hasOriginRemote: false }; - } - return yield* createGitCommandError( - "GitCore.listBranches", - input.cwd, - ["branch", "--no-color"], - stderr || "git branch failed", - ); - } + const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => + runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( + Effect.map((stdout) => stdout.trim()), + Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + ); - const remoteBranchResultEffect = executeGit( - "GitCore.listBranches.remoteBranches", - input.cwd, - ["branch", "--no-color", "--remotes"], - { - timeoutMs: 10_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.catch((error) => - Effect.logWarning( - `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, - ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), - ), - ); + 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 remoteNamesResultEffect = executeGit( - "GitCore.listBranches.remoteNames", - input.cwd, - ["remote"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.catch((error) => - Effect.logWarning( - `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, - ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), - ), - ); - - const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = - yield* Effect.all( - [ - executeGit( - "GitCore.listBranches.defaultRef", - input.cwd, - ["symbolic-ref", "refs/remotes/origin/HEAD"], - { - timeoutMs: 5_000, - allowNonZeroExit: 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", ), - executeGit( - "GitCore.listBranches.worktreeList", - input.cwd, - ["worktree", "list", "--porcelain"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), - remoteBranchResultEffect, - remoteNamesResultEffect, - branchRecencyPromise, - ], - { concurrency: "unbounded" }, - ); - - const remoteNames = - remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; - if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { - yield* Effect.logWarning( - `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, - ); - } - if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { - yield* Effect.logWarning( - `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, - ); - } - - const defaultBranch = - defaultRef.code === 0 - ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") - : null; - - const worktreeMap = new Map(); - if (worktreeList.code === 0) { - let currentPath: string | null = null; - for (const line of worktreeList.stdout.split("\n")) { - if (line.startsWith("worktree ")) { - const candidatePath = line.slice("worktree ".length); - const exists = yield* fileSystem.stat(candidatePath).pipe( - Effect.map(() => true), - Effect.catch(() => Effect.succeed(false)), - ); - currentPath = exists ? candidatePath : null; - } else if (line.startsWith("branch refs/heads/") && currentPath) { - worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); - } else if (line === "") { - currentPath = null; - } - } - } - - const localBranches = localBranchResult.stdout - .split("\n") - .map(parseBranchLine) - .filter((branch): branch is { name: string; current: boolean } => branch !== null) - .map((branch) => ({ - name: branch.name, - current: branch.current, - isRemote: false, - isDefault: branch.name === defaultBranch, - worktreePath: worktreeMap.get(branch.name) ?? null, - })) - .toSorted((a, b) => { - const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; - const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; - if (aPriority !== bPriority) return aPriority - bPriority; - - const aLastCommit = branchLastCommit.get(a.name) ?? 0; - const bLastCommit = branchLastCommit.get(b.name) ?? 0; - if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; - return a.name.localeCompare(b.name); - }); - - const remoteBranches = - remoteBranchResult.code === 0 - ? remoteBranchResult.stdout - .split("\n") - .map(parseBranchLine) - .filter((branch): branch is { name: string; current: boolean } => branch !== null) - .map((branch) => { - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); - const remoteBranch: { - name: string; - current: boolean; - isRemote: boolean; - remoteName?: string; - isDefault: boolean; - worktreePath: string | null; - } = { - name: branch.name, - current: false, - isRemote: true, - isDefault: false, - worktreePath: null, - }; - if (parsedRemoteRef) { - remoteBranch.remoteName = parsedRemoteRef.remoteName; - } - return remoteBranch; - }) - .toSorted((a, b) => { - const aLastCommit = branchLastCommit.get(a.name) ?? 0; - const bLastCommit = branchLastCommit.get(b.name) ?? 0; - if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; - return a.name.localeCompare(b.name); - }) - : []; - - const branches = [...localBranches, ...remoteBranches]; - - return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; - }); - - const createWorktree: GitCoreShape["createWorktree"] = (input) => - Effect.gen(function* () { - const targetBranch = input.newBranch ?? input.branch; - const sanitizedBranch = targetBranch.replace(/\//g, "-"); - const repoName = path.basename(input.cwd); - const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); - const args = input.newBranch - ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] - : ["worktree", "add", worktreePath, input.branch]; - - yield* executeGit("GitCore.createWorktree", input.cwd, args, { - fallbackErrorMessage: "git worktree add failed", - }); - - return { - worktree: { - path: worktreePath, - branch: targetBranch, - }, - }; - }); - - const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = (input) => - Effect.gen(function* () { - const remoteName = yield* resolvePrimaryRemoteName(input.cwd); - yield* executeGit( - "GitCore.fetchPullRequestBranch", - input.cwd, - [ - "fetch", - "--quiet", - "--no-tags", - remoteName, - `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, - ], - { - fallbackErrorMessage: "git fetch pull request branch failed", - }, - ); - }).pipe(Effect.asVoid); - - const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = (input) => - Effect.gen(function* () { - yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ - "fetch", - "--quiet", - "--no-tags", - input.remoteName, - `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, - ]); - - const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); - const targetRef = `${input.remoteName}/${input.remoteBranch}`; - yield* runGit( - "GitCore.fetchRemoteBranch.materialize", - input.cwd, - localBranchAlreadyExists - ? ["branch", "--force", input.localBranch, targetRef] - : ["branch", input.localBranch, targetRef], - ); - }).pipe(Effect.asVoid); - - const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => - runGit("GitCore.setBranchUpstream", input.cwd, [ - "branch", - "--set-upstream-to", - `${input.remoteName}/${input.remoteBranch}`, - input.branch, - ]); - - const removeWorktree: GitCoreShape["removeWorktree"] = (input) => - Effect.gen(function* () { - const args = ["worktree", "remove"]; - if (input.force) { - args.push("--force"); - } - args.push(input.path); - yield* executeGit("GitCore.removeWorktree", input.cwd, args, { - timeoutMs: 15_000, - fallbackErrorMessage: "git worktree remove failed", - }).pipe( - Effect.mapError((error) => - createGitCommandError( - "GitCore.removeWorktree", - input.cwd, - args, - `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, - error, ), - ), - ); - }); + ), + ); - const renameBranch: GitCoreShape["renameBranch"] = (input) => - Effect.gen(function* () { - if (input.oldBranch === input.newBranch) { - return { branch: input.newBranch }; - } - const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); + const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) => + Effect.gen(function* () { + if (relativePaths.length === 0) { + return relativePaths; + } - yield* executeGit( - "GitCore.renameBranch", - input.cwd, - ["branch", "-m", "--", input.oldBranch, targetBranch], + 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"], { - timeoutMs: 10_000, - fallbackErrorMessage: "git branch rename failed", + stdin: `${chunk.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, }, ); - return { branch: targetBranch }; - }); + 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", + ); + } - const createBranch: GitCoreShape["createBranch"] = (input) => - executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { + 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())), + ); + const localBranchResult = yield* executeGit( + "GitCore.listBranches.branchNoColor", + input.cwd, + ["branch", "--no-color", "--no-column"], + { timeoutMs: 10_000, - fallbackErrorMessage: "git branch create failed", - }).pipe(Effect.asVoid); + allowNonZeroExit: true, + }, + ); - const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) => - Effect.gen(function* () { - const [localInputExists, remoteExists] = yield* Effect.all( - [ - executeGit( - "GitCore.checkoutBranch.localInputExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)), - executeGit( - "GitCore.checkoutBranch.remoteExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)), - ], - { concurrency: "unbounded" }, - ); + if (localBranchResult.code !== 0) { + const stderr = localBranchResult.stderr.trim(); + if (stderr.toLowerCase().includes("not a git repository")) { + return { branches: [], isRepo: false, hasOriginRemote: false }; + } + return yield* createGitCommandError( + "GitCore.listBranches", + input.cwd, + ["branch", "--no-color", "--no-column"], + stderr || "git branch failed", + ); + } - const localTrackingBranch = remoteExists - ? yield* executeGit( - "GitCore.checkoutBranch.localTrackingBranch", - input.cwd, - ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.map((result) => - result.code === 0 - ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) - : null, - ), - ) - : null; - - const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); - const localTrackedBranchTargetExists = - remoteExists && localTrackedBranchCandidate - ? yield* executeGit( - "GitCore.checkoutBranch.localTrackedBranchTargetExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)) - : false; - - const checkoutArgs = localInputExists - ? ["checkout", input.branch] - : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists - ? ["checkout", input.branch] - : remoteExists && !localTrackingBranch - ? ["checkout", "--track", input.branch] - : remoteExists && localTrackingBranch - ? ["checkout", localTrackingBranch] - : ["checkout", input.branch]; - - yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { - timeoutMs: 10_000, - fallbackErrorMessage: "git checkout failed", - }); - - // Refresh upstream refs in the background so checkout remains responsive. - yield* Effect.forkScoped( - refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), - ); - }); - - const initRepo: GitCoreShape["initRepo"] = (input) => - executeGit("GitCore.initRepo", input.cwd, ["init"], { + const remoteBranchResultEffect = executeGit( + "GitCore.listBranches.remoteBranches", + input.cwd, + ["branch", "--no-color", "--no-column", "--remotes"], + { timeoutMs: 10_000, - fallbackErrorMessage: "git init failed", - }).pipe(Effect.asVoid); + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); - const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => - runGitStdout("GitCore.listLocalBranchNames", cwd, [ - "branch", - "--list", - "--format=%(refname:short)", - ]).pipe( - Effect.map((stdout) => - stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0), - ), + const remoteNamesResultEffect = executeGit( + "GitCore.listBranches.remoteNames", + input.cwd, + ["remote"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); + + const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = + yield* Effect.all( + [ + executeGit( + "GitCore.listBranches.defaultRef", + input.cwd, + ["symbolic-ref", "refs/remotes/origin/HEAD"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ), + executeGit( + "GitCore.listBranches.worktreeList", + input.cwd, + ["worktree", "list", "--porcelain"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ), + remoteBranchResultEffect, + remoteNamesResultEffect, + branchRecencyPromise, + ], + { concurrency: "unbounded" }, ); - return { - execute, - status, - statusDetails, - prepareCommitContext, - commit, - pushCurrentBranch, - pullCurrentBranch, - readRangeContext, - readConfigValue, - listBranches, - createWorktree, - fetchPullRequestBranch, - ensureRemote, - fetchRemoteBranch, - setBranchUpstream, - removeWorktree, - renameBranch, - createBranch, - checkoutBranch, - initRepo, - listLocalBranchNames, - } satisfies GitCoreShape; + const remoteNames = + remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; + if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, + ); + } + if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, + ); + } + + const defaultBranch = + defaultRef.code === 0 + ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + : null; + + const worktreeMap = new Map(); + if (worktreeList.code === 0) { + let currentPath: string | null = null; + for (const line of worktreeList.stdout.split("\n")) { + if (line.startsWith("worktree ")) { + const candidatePath = line.slice("worktree ".length); + const exists = yield* fileSystem.stat(candidatePath).pipe( + Effect.map(() => true), + Effect.catch(() => Effect.succeed(false)), + ); + currentPath = exists ? candidatePath : null; + } else if (line.startsWith("branch refs/heads/") && currentPath) { + worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); + } else if (line === "") { + currentPath = null; + } + } + } + + const localBranches = localBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => ({ + name: branch.name, + current: branch.current, + isRemote: false, + isDefault: branch.name === defaultBranch, + worktreePath: worktreeMap.get(branch.name) ?? null, + })) + .toSorted((a, b) => { + const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; + const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; + if (aPriority !== bPriority) return aPriority - bPriority; + + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }); + + const remoteBranches = + remoteBranchResult.code === 0 + ? remoteBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => { + const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); + const remoteBranch: { + name: string; + current: boolean; + isRemote: boolean; + remoteName?: string; + isDefault: boolean; + worktreePath: string | null; + } = { + name: branch.name, + current: false, + isRemote: true, + isDefault: false, + worktreePath: null, + }; + if (parsedRemoteRef) { + remoteBranch.remoteName = parsedRemoteRef.remoteName; + } + return remoteBranch; + }) + .toSorted((a, b) => { + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }) + : []; + + const branches = [...localBranches, ...remoteBranches]; + + return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; }); + const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")( + function* (input) { + const targetBranch = input.newBranch ?? input.branch; + const sanitizedBranch = targetBranch.replace(/\//g, "-"); + const repoName = path.basename(input.cwd); + const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); + const args = input.newBranch + ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] + : ["worktree", "add", worktreePath, input.branch]; + + yield* executeGit("GitCore.createWorktree", input.cwd, args, { + fallbackErrorMessage: "git worktree add failed", + }); + + return { + worktree: { + path: worktreePath, + branch: targetBranch, + }, + }; + }, + ); + + const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = Effect.fn( + "fetchPullRequestBranch", + )(function* (input) { + const remoteName = yield* resolvePrimaryRemoteName(input.cwd); + yield* executeGit( + "GitCore.fetchPullRequestBranch", + input.cwd, + [ + "fetch", + "--quiet", + "--no-tags", + remoteName, + `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, + ], + { + fallbackErrorMessage: "git fetch pull request branch failed", + }, + ); + }); + + const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = Effect.fn("fetchRemoteBranch")( + function* (input) { + yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ + "fetch", + "--quiet", + "--no-tags", + input.remoteName, + `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, + ]); + + const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); + const targetRef = `${input.remoteName}/${input.remoteBranch}`; + yield* runGit( + "GitCore.fetchRemoteBranch.materialize", + input.cwd, + localBranchAlreadyExists + ? ["branch", "--force", input.localBranch, targetRef] + : ["branch", input.localBranch, targetRef], + ); + }, + ); + + const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => + runGit("GitCore.setBranchUpstream", input.cwd, [ + "branch", + "--set-upstream-to", + `${input.remoteName}/${input.remoteBranch}`, + input.branch, + ]); + + const removeWorktree: GitCoreShape["removeWorktree"] = Effect.fn("removeWorktree")( + function* (input) { + const args = ["worktree", "remove"]; + if (input.force) { + args.push("--force"); + } + args.push(input.path); + yield* executeGit("GitCore.removeWorktree", input.cwd, args, { + timeoutMs: 15_000, + fallbackErrorMessage: "git worktree remove failed", + }).pipe( + Effect.mapError((error) => + createGitCommandError( + "GitCore.removeWorktree", + input.cwd, + args, + `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, + error, + ), + ), + ); + }, + ); + + const renameBranch: GitCoreShape["renameBranch"] = Effect.fn("renameBranch")(function* (input) { + if (input.oldBranch === input.newBranch) { + return { branch: input.newBranch }; + } + const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); + + yield* executeGit( + "GitCore.renameBranch", + input.cwd, + ["branch", "-m", "--", input.oldBranch, targetBranch], + { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch rename failed", + }, + ); + + return { branch: targetBranch }; + }); + + const createBranch: GitCoreShape["createBranch"] = (input) => + executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch create failed", + }).pipe(Effect.asVoid); + + const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")( + function* (input) { + const [localInputExists, remoteExists] = yield* Effect.all( + [ + executeGit( + "GitCore.checkoutBranch.localInputExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + executeGit( + "GitCore.checkoutBranch.remoteExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + ], + { concurrency: "unbounded" }, + ); + + const localTrackingBranch = remoteExists + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackingBranch", + input.cwd, + ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.map((result) => + result.code === 0 + ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) + : null, + ), + ) + : null; + + const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); + const localTrackedBranchTargetExists = + remoteExists && localTrackedBranchCandidate + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackedBranchTargetExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)) + : false; + + const checkoutArgs = localInputExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch + ? ["checkout", "--track", input.branch] + : remoteExists && localTrackingBranch + ? ["checkout", localTrackingBranch] + : ["checkout", input.branch]; + + yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { + timeoutMs: 10_000, + fallbackErrorMessage: "git checkout failed", + }); + + // Refresh upstream refs in the background so checkout remains responsive. + yield* refreshCheckedOutBranchUpstream(input.cwd).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkDetach({ startImmediately: true }), + ); + }, + ); + + const initRepo: GitCoreShape["initRepo"] = (input) => + executeGit("GitCore.initRepo", input.cwd, ["init"], { + timeoutMs: 10_000, + fallbackErrorMessage: "git init failed", + }).pipe(Effect.asVoid); + + const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => + runGitStdout("GitCore.listLocalBranchNames", cwd, [ + "branch", + "--list", + "--no-column", + "--format=%(refname:short)", + ]).pipe( + Effect.map((stdout) => + stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0), + ), + ); + + return { + execute, + status, + statusDetails, + prepareCommitContext, + commit, + pushCurrentBranch, + pullCurrentBranch, + readRangeContext, + readConfigValue, + isInsideWorkTree, + listWorkspaceFiles, + filterIgnoredPaths, + listBranches, + createWorktree, + fetchPullRequestBranch, + ensureRemote, + fetchRemoteBranch, + setBranchUpstream, + removeWorktree, + renameBranch, + createBranch, + checkoutBranch, + initRepo, + listLocalBranchNames, + } satisfies GitCoreShape; +}); + export const GitCoreLive = Layer.effect(GitCore, makeGitCore()); 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 57d6853c4a..e05fc30875 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -6,9 +6,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { expect } from "vitest"; -import type { GitActionProgressEvent } from "@t3tools/contracts"; +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, @@ -49,6 +49,7 @@ interface FakeGitTextGeneration { stagedSummary: string; stagedPatch: string; includeBranch?: boolean; + modelSelection: ModelSelection; }) => Effect.Effect< { subject: string; body: string; branch?: string | undefined }, TextGenerationError @@ -60,11 +61,18 @@ interface FakeGitTextGeneration { commitSummary: string; diffSummary: string; diffPatch: string; + modelSelection: ModelSelection; }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>; generateBranchName: (input: { cwd: string; message: string; + modelSelection: ModelSelection; }) => Effect.Effect<{ branch: string }, TextGenerationError>; + generateThreadTitle: (input: { + cwd: string; + message: string; + modelSelection: ModelSelection; + }) => Effect.Effect<{ title: string }, TextGenerationError>; } type FakePullRequest = NonNullable; @@ -168,6 +176,10 @@ function createTextGeneration(overrides: Partial = {}): T Effect.succeed({ branch: "update-workflow", }), + generateThreadTitle: () => + Effect.succeed({ + title: "Update workflow", + }), ...overrides, }; @@ -205,6 +217,17 @@ function createTextGeneration(overrides: Partial = {}): T }), ), ), + generateThreadTitle: (input) => + implementation.generateThreadTitle(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), }; } @@ -502,7 +525,7 @@ function makeManager(input?: { serverSettingsLayer, ).pipe(Layer.provideMerge(NodeServices.layer)); - return makeGitManager.pipe( + return makeGitManager().pipe( Effect.provide(managerLayer), Effect.map((manager) => ({ manager, ghCalls })), ); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index 6fd86e1d58..f8445cf09a 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -1,15 +1,20 @@ import { randomUUID } from "node:crypto"; import { realpathSync } from "node:fs"; -import { Effect, FileSystem, Layer, Path } from "effect"; -import { GitActionProgressEvent, GitActionProgressPhase, ModelSelection } from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Option, Path, Ref } from "effect"; +import { + GitActionProgressEvent, + GitActionProgressPhase, + GitRunStackedActionResult, + ModelSelection, +} from "@t3tools/contracts"; import { resolveAutoFeatureBranchName, sanitizeBranchFragment, sanitizeFeatureBranchName, } from "@t3tools/shared/git"; -import { GitManagerError } from "../Errors.ts"; +import { GitManagerError } from "@t3tools/contracts"; import { GitManager, type GitActionProgressReporter, @@ -20,6 +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 "@t3tools/contracts"; const COMMIT_TIMEOUT_MS = 10 * 60_000; const MAX_PROGRESS_TEXT_LENGTH = 500; @@ -355,7 +361,7 @@ function toPullRequestHeadRemoteInfo(pr: { }; } -export const makeGitManager = Effect.gen(function* () { +export const makeGitManager = Effect.fn("makeGitManager")(function* () { const gitCore = yield* GitCore; const gitHubCli = yield* GitHubCli; const textGeneration = yield* TextGeneration; @@ -384,12 +390,12 @@ export const makeGitManager = Effect.gen(function* () { }; }; - const configurePullRequestHeadUpstream = ( - cwd: string, - pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, - localBranch = pullRequest.headBranch, - ) => - Effect.gen(function* () { + const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; if (repositoryNameWithOwner.length === 0) { return; @@ -417,7 +423,15 @@ export const makeGitManager = Effect.gen(function* () { remoteName, remoteBranch: pullRequest.headBranch, }); - }).pipe( + }, + ); + + const configurePullRequestHeadUpstream = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe( Effect.catch((error) => Effect.logWarning( `GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`, @@ -425,12 +439,12 @@ export const makeGitManager = Effect.gen(function* () { ), ); - const materializePullRequestHeadBranch = ( - cwd: string, - pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, - localBranch = pullRequest.headBranch, - ) => - Effect.gen(function* () { + const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; if (repositoryNameWithOwner.length === 0) { @@ -470,7 +484,15 @@ export const makeGitManager = Effect.gen(function* () { remoteName, remoteBranch: pullRequest.headBranch, }); - }).pipe( + }, + ); + + const materializePullRequestHeadBranch = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe( Effect.catch(() => gitCore.fetchPullRequestBranch({ cwd, @@ -487,208 +509,211 @@ export const makeGitManager = Effect.gen(function* () { const readConfigValueNullable = (cwd: string, key: string) => gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null))); - const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) => - Effect.gen(function* () { - if (!remoteName) { - return { - repositoryNameWithOwner: null, - ownerLogin: null, - }; - } - - const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`); - const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl); + const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( + cwd: string, + remoteName: string | null, + ) { + if (!remoteName) { return { - repositoryNameWithOwner, - ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner), + repositoryNameWithOwner: null, + ownerLogin: null, }; - }); + } - const resolveBranchHeadContext = ( + const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`); + const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl); + return { + repositoryNameWithOwner, + ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner), + }; + }); + + const resolveBranchHeadContext = Effect.fn("resolveBranchHeadContext")(function* ( cwd: string, details: { branch: string; upstreamRef: string | null }, - ) => - Effect.gen(function* () { - const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); - const headBranchFromUpstream = details.upstreamRef - ? extractBranchFromRef(details.upstreamRef) - : ""; - const headBranch = - headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; + ) { + const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); + const headBranchFromUpstream = details.upstreamRef + ? extractBranchFromRef(details.upstreamRef) + : ""; + const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; - const [remoteRepository, originRepository] = yield* Effect.all( - [ - resolveRemoteRepositoryContext(cwd, remoteName), - resolveRemoteRepositoryContext(cwd, "origin"), - ], - { concurrency: "unbounded" }, - ); + const [remoteRepository, originRepository] = yield* Effect.all( + [ + resolveRemoteRepositoryContext(cwd, remoteName), + resolveRemoteRepositoryContext(cwd, "origin"), + ], + { concurrency: "unbounded" }, + ); - const isCrossRepository = - remoteRepository.repositoryNameWithOwner !== null && - originRepository.repositoryNameWithOwner !== null - ? remoteRepository.repositoryNameWithOwner.toLowerCase() !== - originRepository.repositoryNameWithOwner.toLowerCase() - : remoteName !== null && - remoteName !== "origin" && - remoteRepository.repositoryNameWithOwner !== null; + const isCrossRepository = + remoteRepository.repositoryNameWithOwner !== null && + originRepository.repositoryNameWithOwner !== null + ? remoteRepository.repositoryNameWithOwner.toLowerCase() !== + originRepository.repositoryNameWithOwner.toLowerCase() + : remoteName !== null && + remoteName !== "origin" && + remoteRepository.repositoryNameWithOwner !== null; - const ownerHeadSelector = - remoteRepository.ownerLogin && headBranch.length > 0 - ? `${remoteRepository.ownerLogin}:${headBranch}` - : null; - const remoteAliasHeadSelector = - remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null; - const shouldProbeRemoteOwnedSelectors = - isCrossRepository || (remoteName !== null && remoteName !== "origin"); + const ownerHeadSelector = + remoteRepository.ownerLogin && headBranch.length > 0 + ? `${remoteRepository.ownerLogin}:${headBranch}` + : null; + const remoteAliasHeadSelector = + remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null; + const shouldProbeRemoteOwnedSelectors = + isCrossRepository || (remoteName !== null && remoteName !== "origin"); - const headSelectors: string[] = []; - if (isCrossRepository && shouldProbeRemoteOwnedSelectors) { - appendUnique(headSelectors, ownerHeadSelector); - appendUnique( - headSelectors, - remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, - ); - } - appendUnique(headSelectors, details.branch); - appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); - if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { - appendUnique(headSelectors, ownerHeadSelector); - appendUnique( - headSelectors, - remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, - ); - } - - return { - localBranch: details.branch, - headBranch, + const headSelectors: string[] = []; + if (isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( headSelectors, - preferredHeadSelector: - ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch, - remoteName, - headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner, - headRepositoryOwnerLogin: remoteRepository.ownerLogin, - isCrossRepository, - } satisfies BranchHeadContext; - }); + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } + appendUnique(headSelectors, details.branch); + appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); + if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( + headSelectors, + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } - const findOpenPr = (cwd: string, headSelectors: ReadonlyArray) => - Effect.gen(function* () { - for (const headSelector of headSelectors) { - const pullRequests = yield* gitHubCli.listOpenPullRequests({ - cwd, - headSelector, - limit: 1, - }); + return { + localBranch: details.branch, + headBranch, + headSelectors, + preferredHeadSelector: + ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch, + remoteName, + headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner, + headRepositoryOwnerLogin: remoteRepository.ownerLogin, + isCrossRepository, + } satisfies BranchHeadContext; + }); - const [firstPullRequest] = pullRequests; - if (firstPullRequest) { - return { - number: firstPullRequest.number, - title: firstPullRequest.title, - url: firstPullRequest.url, - baseRefName: firstPullRequest.baseRefName, - headRefName: firstPullRequest.headRefName, - state: "open", - updatedAt: null, - } satisfies PullRequestInfo; - } - } - - return null; - }); - - const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) => - Effect.gen(function* () { - const headContext = yield* resolveBranchHeadContext(cwd, details); - const parsedByNumber = new Map(); - - for (const headSelector of headContext.headSelectors) { - const stdout = yield* gitHubCli - .execute({ - cwd, - args: [ - "pr", - "list", - "--head", - headSelector, - "--state", - "all", - "--limit", - "20", - "--json", - "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", - ], - }) - .pipe(Effect.map((result) => result.stdout)); - - const raw = stdout.trim(); - if (raw.length === 0) { - continue; - } - - const parsedJson = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => - gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), - }); - - for (const pr of parsePullRequestList(parsedJson)) { - parsedByNumber.set(pr.number, pr); - } - } - - const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => { - const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; - const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; - return right - left; + const findOpenPr = Effect.fn("findOpenPr")(function* ( + cwd: string, + headSelectors: ReadonlyArray, + ) { + for (const headSelector of headSelectors) { + const pullRequests = yield* gitHubCli.listOpenPullRequests({ + cwd, + headSelector, + limit: 1, }); - const latestOpenPr = parsed.find((pr) => pr.state === "open"); - if (latestOpenPr) { - return latestOpenPr; + const [firstPullRequest] = pullRequests; + if (firstPullRequest) { + return { + number: firstPullRequest.number, + title: firstPullRequest.title, + url: firstPullRequest.url, + baseRefName: firstPullRequest.baseRefName, + headRefName: firstPullRequest.headRefName, + state: "open", + updatedAt: null, + } satisfies PullRequestInfo; } - return parsed[0] ?? null; + } + + return null; + }); + + const findLatestPr = Effect.fn("findLatestPr")(function* ( + cwd: string, + details: { branch: string; upstreamRef: string | null }, + ) { + const headContext = yield* resolveBranchHeadContext(cwd, details); + const parsedByNumber = new Map(); + + for (const headSelector of headContext.headSelectors) { + const stdout = yield* gitHubCli + .execute({ + cwd, + args: [ + "pr", + "list", + "--head", + headSelector, + "--state", + "all", + "--limit", + "20", + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", + ], + }) + .pipe(Effect.map((result) => result.stdout)); + + const raw = stdout.trim(); + if (raw.length === 0) { + continue; + } + + const parsedJson = yield* Effect.try({ + try: () => JSON.parse(raw) as unknown, + catch: (cause) => + gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), + }); + + for (const pr of parsePullRequestList(parsedJson)) { + parsedByNumber.set(pr.number, pr); + } + } + + const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => { + const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; + const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; + return right - left; }); - const resolveBaseBranch = ( + const latestOpenPr = parsed.find((pr) => pr.state === "open"); + if (latestOpenPr) { + return latestOpenPr; + } + return parsed[0] ?? null; + }); + + const resolveBaseBranch = Effect.fn("resolveBaseBranch")(function* ( cwd: string, branch: string, upstreamRef: string | null, headContext: Pick, - ) => - Effect.gen(function* () { - const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); - if (configured) return configured; + ) { + const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); + if (configured) return configured; - if (upstreamRef && !headContext.isCrossRepository) { - const upstreamBranch = extractBranchFromRef(upstreamRef); - if (upstreamBranch.length > 0 && upstreamBranch !== branch) { - return upstreamBranch; - } + if (upstreamRef && !headContext.isCrossRepository) { + const upstreamBranch = extractBranchFromRef(upstreamRef); + if (upstreamBranch.length > 0 && upstreamBranch !== branch) { + return upstreamBranch; } + } - const defaultFromGh = yield* gitHubCli - .getDefaultBranch({ cwd }) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (defaultFromGh) { - return defaultFromGh; - } + const defaultFromGh = yield* gitHubCli + .getDefaultBranch({ cwd }) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (defaultFromGh) { + return defaultFromGh; + } - return "main"; - }); + return "main"; + }); - const resolveCommitAndBranchSuggestion = (input: { - cwd: string; - branch: string | null; - commitMessage?: string; - /** When true, also produce a semantic feature branch name. */ - includeBranch?: boolean; - filePaths?: readonly string[]; - modelSelection: ModelSelection; - }) => - Effect.gen(function* () { + const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")( + function* (input: { + cwd: string; + branch: string | null; + commitMessage?: string; + /** When true, also produce a semantic feature branch name. */ + includeBranch?: boolean; + filePaths?: readonly string[]; + modelSelection: ModelSelection; + }) { const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths); if (!context) { return null; @@ -723,9 +748,10 @@ export const makeGitManager = Effect.gen(function* () { ...(generated.branch !== undefined ? { branch: generated.branch } : {}), commitMessage: formatCommitMessage(generated.subject, generated.body), }; - }); + }, + ); - const runCommitStep = ( + const runCommitStep = Effect.fn("runCommitStep")(function* ( modelSelection: ModelSelection, cwd: string, action: "commit" | "commit_push" | "commit_push_pr", @@ -735,196 +761,198 @@ export const makeGitManager = Effect.gen(function* () { filePaths?: readonly string[], progressReporter?: GitActionProgressReporter, actionId?: string, - ) => - Effect.gen(function* () { - const emit = (event: GitActionProgressPayload) => - progressReporter && actionId - ? progressReporter.publish({ - actionId, - cwd, - action, - ...event, - } as GitActionProgressEvent) - : Effect.void; + ) { + const emit = (event: GitActionProgressPayload) => + progressReporter && actionId + ? progressReporter.publish({ + actionId, + cwd, + action, + ...event, + } as GitActionProgressEvent) + : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; - if (!suggestion) { - const needsGeneration = !commitMessage?.trim(); - if (needsGeneration) { - yield* emit({ - kind: "phase_started", - phase: "commit", - label: "Generating commit message...", - }); - } - suggestion = yield* resolveCommitAndBranchSuggestion({ - cwd, - branch, - ...(commitMessage ? { commitMessage } : {}), - ...(filePaths ? { filePaths } : {}), - modelSelection, + let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + if (!suggestion) { + const needsGeneration = !commitMessage?.trim(); + if (needsGeneration) { + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Generating commit message...", }); } - if (!suggestion) { - return { status: "skipped_no_changes" as const }; - } - - yield* emit({ - kind: "phase_started", - phase: "commit", - label: "Committing...", + suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + modelSelection, }); + } + if (!suggestion) { + return { status: "skipped_no_changes" as const }; + } - let currentHookName: string | null = null; - const commitProgress = - progressReporter && actionId - ? { - onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => { - const sanitized = sanitizeProgressText(text); - if (!sanitized) { - return Effect.void; - } - return emit({ - kind: "hook_output", - hookName: currentHookName, - stream, - text: sanitized, - }); - }, - onHookStarted: (hookName: string) => { - currentHookName = hookName; - return emit({ - kind: "hook_started", - hookName, - }); - }, - onHookFinished: ({ + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Committing...", + }); + + let currentHookName: string | null = null; + const commitProgress = + progressReporter && actionId + ? { + onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => { + const sanitized = sanitizeProgressText(text); + if (!sanitized) { + return Effect.void; + } + return emit({ + kind: "hook_output", + hookName: currentHookName, + stream, + text: sanitized, + }); + }, + onHookStarted: (hookName: string) => { + currentHookName = hookName; + return emit({ + kind: "hook_started", + hookName, + }); + }, + onHookFinished: ({ + hookName, + exitCode, + durationMs, + }: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => { + if (currentHookName === hookName) { + currentHookName = null; + } + return emit({ + kind: "hook_finished", hookName, exitCode, durationMs, - }: { - hookName: string; - exitCode: number | null; - durationMs: number | null; - }) => { - if (currentHookName === hookName) { - currentHookName = null; - } - return emit({ - kind: "hook_finished", - hookName, - exitCode, - durationMs, - }); - }, - } - : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - ...(commitProgress ? { progress: commitProgress } : {}), + }); + }, + } + : null; + const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + ...(commitProgress ? { progress: commitProgress } : {}), + }); + if (currentHookName !== null) { + yield* emit({ + kind: "hook_finished", + hookName: currentHookName, + exitCode: 0, + durationMs: null, }); - if (currentHookName !== null) { - yield* emit({ - kind: "hook_finished", - hookName: currentHookName, - exitCode: 0, - durationMs: null, - }); - currentHookName = null; - } - return { - status: "created" as const, - commitSha, - subject: suggestion.subject, - }; + currentHookName = null; + } + return { + status: "created" as const, + commitSha, + subject: suggestion.subject, + }; + }); + + const runPrStep = Effect.fn("runPrStep")(function* ( + modelSelection: ModelSelection, + cwd: string, + fallbackBranch: string | null, + ) { + const details = yield* gitCore.statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* gitManagerError( + "runPrStep", + "Cannot create a pull request from detached HEAD.", + ); + } + if (!details.hasUpstream) { + return yield* gitManagerError( + "runPrStep", + "Current branch has not been pushed. Push before creating a PR.", + ); + } + + const headContext = yield* resolveBranchHeadContext(cwd, { + branch, + upstreamRef: details.upstreamRef, }); - const runPrStep = (modelSelection: ModelSelection, cwd: string, fallbackBranch: string | null) => - Effect.gen(function* () { - const details = yield* gitCore.statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { - return yield* gitManagerError( - "runPrStep", - "Cannot create a pull request from detached HEAD.", - ); - } - if (!details.hasUpstream) { - return yield* gitManagerError( - "runPrStep", - "Current branch has not been pushed. Push before creating a PR.", - ); - } + const existing = yield* findOpenPr(cwd, headContext.headSelectors); + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } - const headContext = yield* resolveBranchHeadContext(cwd, { - branch, - upstreamRef: details.upstreamRef, - }); + const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); + const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); - const existing = yield* findOpenPr(cwd, headContext.headSelectors); - if (existing) { - return { - status: "opened_existing" as const, - url: existing.url, - number: existing.number, - baseBranch: existing.baseRefName, - headBranch: existing.headRefName, - title: existing.title, - }; - } + const generated = yield* textGeneration.generatePrContent({ + cwd, + baseBranch, + headBranch: headContext.headBranch, + commitSummary: limitContext(rangeContext.commitSummary, 20_000), + diffSummary: limitContext(rangeContext.diffSummary, 20_000), + diffPatch: limitContext(rangeContext.diffPatch, 60_000), + modelSelection, + }); - const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); - const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); - - const generated = yield* textGeneration.generatePrContent({ + const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`); + yield* fileSystem + .writeFileString(bodyFile, generated.body) + .pipe( + Effect.mapError((cause) => + gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), + ), + ); + yield* gitHubCli + .createPullRequest({ cwd, baseBranch, - headBranch: headContext.headBranch, - commitSummary: limitContext(rangeContext.commitSummary, 20_000), - diffSummary: limitContext(rangeContext.diffSummary, 20_000), - diffPatch: limitContext(rangeContext.diffPatch, 60_000), - modelSelection, - }); - - const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`); - yield* fileSystem - .writeFileString(bodyFile, generated.body) - .pipe( - Effect.mapError((cause) => - gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), - ), - ); - yield* gitHubCli - .createPullRequest({ - cwd, - baseBranch, - headSelector: headContext.preferredHeadSelector, - title: generated.title, - bodyFile, - }) - .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); - - const created = yield* findOpenPr(cwd, headContext.headSelectors); - if (!created) { - return { - status: "created" as const, - baseBranch, - headBranch: headContext.headBranch, - title: generated.title, - }; - } + headSelector: headContext.preferredHeadSelector, + title: generated.title, + bodyFile, + }) + .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); + const created = yield* findOpenPr(cwd, headContext.headSelectors); + if (!created) { return { status: "created" as const, - url: created.url, - number: created.number, - baseBranch: created.baseRefName, - headBranch: created.headRefName, - title: created.title, + baseBranch, + headBranch: headContext.headBranch, + title: generated.title, }; - }); + } - const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) { + return { + status: "created" as const, + url: created.url, + number: created.number, + baseBranch: created.baseRefName, + headBranch: created.headRefName, + title: created.title, + }; + }); + + const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) { const details = yield* gitCore.statusDetails(input.cwd); const pr = @@ -949,7 +977,7 @@ export const makeGitManager = Effect.gen(function* () { }; }); - const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced( + const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")( function* (input) { const pullRequest = yield* gitHubCli .getPullRequest({ @@ -962,185 +990,185 @@ export const makeGitManager = Effect.gen(function* () { }, ); - const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced( - function* (input) { - const normalizedReference = normalizePullRequestReference(input.reference); - const rootWorktreePath = canonicalizeExistingPath(input.cwd); - const pullRequestSummary = yield* gitHubCli.getPullRequest({ + const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn( + "preparePullRequestThread", + )(function* (input) { + const normalizedReference = normalizePullRequestReference(input.reference); + const rootWorktreePath = canonicalizeExistingPath(input.cwd); + const pullRequestSummary = yield* gitHubCli.getPullRequest({ + cwd: input.cwd, + reference: normalizedReference, + }); + const pullRequest = toResolvedPullRequest(pullRequestSummary); + + if (input.mode === "local") { + yield* gitHubCli.checkoutPullRequest({ cwd: input.cwd, reference: normalizedReference, + force: true, }); - const pullRequest = toResolvedPullRequest(pullRequestSummary); - - if (input.mode === "local") { - yield* gitHubCli.checkoutPullRequest({ - cwd: input.cwd, - reference: normalizedReference, - force: true, - }); - const details = yield* gitCore.statusDetails(input.cwd); - yield* configurePullRequestHeadUpstream( - input.cwd, - { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - }, - details.branch ?? pullRequest.headBranch, - ); - return { - pullRequest, - branch: details.branch ?? pullRequest.headBranch, - worktreePath: null, - }; - } - - const ensureExistingWorktreeUpstream = (worktreePath: string) => - Effect.gen(function* () { - const details = yield* gitCore.statusDetails(worktreePath); - yield* configurePullRequestHeadUpstream( - worktreePath, - { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - }, - details.branch ?? pullRequest.headBranch, - ); - }); - - const pullRequestWithRemoteInfo = { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - } as const; - const localPullRequestBranch = - resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo); - - const findLocalHeadBranch = (cwd: string) => - gitCore.listBranches({ cwd }).pipe( - Effect.map((result) => { - const localBranch = result.branches.find( - (branch) => !branch.isRemote && branch.name === localPullRequestBranch, - ); - if (localBranch) { - return localBranch; - } - if (localPullRequestBranch === pullRequest.headBranch) { - return null; - } - return ( - result.branches.find( - (branch) => - !branch.isRemote && - branch.name === pullRequest.headBranch && - branch.worktreePath !== null && - canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath, - ) ?? null - ); - }), - ); - - const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd); - const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath - ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath) - : null; - if ( - existingBranchBeforeFetch?.worktreePath && - existingBranchBeforeFetchPath !== rootWorktreePath - ) { - yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath); - return { - pullRequest, - branch: localPullRequestBranch, - worktreePath: existingBranchBeforeFetch.worktreePath, - }; - } - if (existingBranchBeforeFetchPath === rootWorktreePath) { - return yield* gitManagerError( - "preparePullRequestThread", - "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", - ); - } - - yield* materializePullRequestHeadBranch( + const details = yield* gitCore.statusDetails(input.cwd); + yield* configurePullRequestHeadUpstream( input.cwd, - pullRequestWithRemoteInfo, - localPullRequestBranch, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, ); - - const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd); - const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath - ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath) - : null; - if ( - existingBranchAfterFetch?.worktreePath && - existingBranchAfterFetchPath !== rootWorktreePath - ) { - yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath); - return { - pullRequest, - branch: localPullRequestBranch, - worktreePath: existingBranchAfterFetch.worktreePath, - }; - } - if (existingBranchAfterFetchPath === rootWorktreePath) { - return yield* gitManagerError( - "preparePullRequestThread", - "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", - ); - } - - const worktree = yield* gitCore.createWorktree({ - cwd: input.cwd, - branch: localPullRequestBranch, - path: null, - }); - yield* ensureExistingWorktreeUpstream(worktree.worktree.path); - return { pullRequest, - branch: worktree.worktree.branch, - worktreePath: worktree.worktree.path, + branch: details.branch ?? pullRequest.headBranch, + worktreePath: null, }; - }, - ); + } - const runFeatureBranchStep = ( + const ensureExistingWorktreeUpstream = Effect.fn("ensureExistingWorktreeUpstream")(function* ( + worktreePath: string, + ) { + const details = yield* gitCore.statusDetails(worktreePath); + yield* configurePullRequestHeadUpstream( + worktreePath, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, + ); + }); + + const pullRequestWithRemoteInfo = { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + } as const; + const localPullRequestBranch = + resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo); + + const findLocalHeadBranch = (cwd: string) => + gitCore.listBranches({ cwd }).pipe( + Effect.map((result) => { + const localBranch = result.branches.find( + (branch) => !branch.isRemote && branch.name === localPullRequestBranch, + ); + if (localBranch) { + return localBranch; + } + if (localPullRequestBranch === pullRequest.headBranch) { + return null; + } + return ( + result.branches.find( + (branch) => + !branch.isRemote && + branch.name === pullRequest.headBranch && + branch.worktreePath !== null && + canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath, + ) ?? null + ); + }), + ); + + const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath) + : null; + if ( + existingBranchBeforeFetch?.worktreePath && + existingBranchBeforeFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchBeforeFetch.worktreePath, + }; + } + if (existingBranchBeforeFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + yield* materializePullRequestHeadBranch( + input.cwd, + pullRequestWithRemoteInfo, + localPullRequestBranch, + ); + + const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath) + : null; + if ( + existingBranchAfterFetch?.worktreePath && + existingBranchAfterFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchAfterFetch.worktreePath, + }; + } + if (existingBranchAfterFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + const worktree = yield* gitCore.createWorktree({ + cwd: input.cwd, + branch: localPullRequestBranch, + path: null, + }); + yield* ensureExistingWorktreeUpstream(worktree.worktree.path); + + return { + pullRequest, + branch: worktree.worktree.branch, + worktreePath: worktree.worktree.path, + }; + }); + + const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* ( modelSelection: ModelSelection, cwd: string, branch: string | null, commitMessage?: string, filePaths?: readonly string[], - ) => - Effect.gen(function* () { - const suggestion = yield* resolveCommitAndBranchSuggestion({ - cwd, - branch, - ...(commitMessage ? { commitMessage } : {}), - ...(filePaths ? { filePaths } : {}), - includeBranch: true, - modelSelection, - }); - if (!suggestion) { - return yield* gitManagerError( - "runFeatureBranchStep", - "Cannot create a feature branch because there are no changes to commit.", - ); - } - - const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject); - const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd); - const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch); - - yield* gitCore.createBranch({ cwd, branch: resolvedBranch }); - yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch })); - - return { - branchStep: { status: "created" as const, name: resolvedBranch }, - resolvedCommitMessage: suggestion.commitMessage, - resolvedCommitSuggestion: suggestion, - }; + ) { + const suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + includeBranch: true, + modelSelection, }); + if (!suggestion) { + return yield* gitManagerError( + "runFeatureBranchStep", + "Cannot create a feature branch because there are no changes to commit.", + ); + } - const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced( + const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject); + const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd); + const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch); + + yield* gitCore.createBranch({ cwd, branch: resolvedBranch }); + yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch })); + + return { + branchStep: { status: "created" as const, name: resolvedBranch }, + resolvedCommitMessage: suggestion.commitMessage, + resolvedCommitSuggestion: suggestion, + }; + }); + + const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")( function* (input, options) { const progress = createProgressEmitter(input, options); const phases: GitActionProgressPhase[] = [ @@ -1149,9 +1177,12 @@ export const makeGitManager = Effect.gen(function* () { ...(input.action !== "commit" ? (["push"] as const) : []), ...(input.action === "commit_push_pr" ? (["pr"] as const) : []), ]; - let currentPhase: GitActionProgressPhase | null = null; + const currentPhase = yield* Ref.make>(Option.none()); - const runAction = Effect.gen(function* () { + const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return< + GitRunStackedActionResult, + GitManagerServiceError + > { yield* progress.emit({ kind: "action_started", phases, @@ -1183,7 +1214,7 @@ export const makeGitManager = Effect.gen(function* () { ); if (input.featureBranch) { - currentPhase = "branch"; + yield* Ref.set(currentPhase, Option.some("branch")); yield* progress.emit({ kind: "phase_started", phase: "branch", @@ -1205,7 +1236,7 @@ export const makeGitManager = Effect.gen(function* () { const currentBranch = branchStep.name ?? initialStatus.branch; - currentPhase = "commit"; + yield* Ref.set(currentPhase, Option.some("commit")); const commit = yield* runCommitStep( modelSelection, input.cwd, @@ -1226,12 +1257,8 @@ export const makeGitManager = Effect.gen(function* () { label: "Pushing...", }) .pipe( - Effect.flatMap(() => - Effect.gen(function* () { - currentPhase = "push"; - return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch); - }), - ), + Effect.tap(() => Ref.set(currentPhase, Option.some("push"))), + Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)), ) : { status: "skipped_not_requested" as const }; @@ -1243,12 +1270,8 @@ export const makeGitManager = Effect.gen(function* () { label: "Creating PR...", }) .pipe( - Effect.flatMap(() => - Effect.gen(function* () { - currentPhase = "pr"; - return yield* runPrStep(modelSelection, input.cwd, currentBranch); - }), - ), + Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))), + Effect.flatMap(() => runPrStep(modelSelection, input.cwd, currentBranch)), ) : { status: "skipped_not_requested" as const }; @@ -1266,15 +1289,15 @@ export const makeGitManager = Effect.gen(function* () { return result; }); - return yield* runAction.pipe( - Effect.catch((error) => - progress - .emit({ + return yield* runAction().pipe( + Effect.tapError((error) => + Effect.flatMap(Ref.get(currentPhase), (phase) => + progress.emit({ kind: "action_failed", - phase: currentPhase, + phase: Option.getOrNull(phase), message: error.message, - }) - .pipe(Effect.flatMap(() => Effect.fail(error))), + }), + ), ), ); }, @@ -1288,4 +1311,4 @@ export const makeGitManager = Effect.gen(function* () { } satisfies GitManagerShape; }); -export const GitManagerLive = Layer.effect(GitManager, makeGitManager); +export const GitManagerLive = Layer.effect(GitManager, makeGitManager()); diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts index 7915131385..dee12a3e0e 100644 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ b/apps/server/src/git/Layers/RoutingTextGeneration.ts @@ -47,6 +47,7 @@ const makeRoutingTextGeneration = Effect.gen(function* () { route(input.modelSelection.provider).generateCommitMessage(input), generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input), generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input), + generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input), } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/git/Prompts.test.ts index 23c3eca557..d8d079c0cf 100644 --- a/apps/server/src/git/Prompts.test.ts +++ b/apps/server/src/git/Prompts.test.ts @@ -4,9 +4,10 @@ import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "./Prompts.ts"; -import { normalizeCliError } from "./Utils.ts"; -import { TextGenerationError } from "./Errors.ts"; +import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts"; +import { TextGenerationError } from "@t3tools/contracts"; describe("buildCommitMessagePrompt", () => { it("includes staged patch and summary in the prompt", () => { @@ -103,6 +104,48 @@ describe("buildBranchNamePrompt", () => { }); }); +describe("buildThreadTitlePrompt", () => { + it("includes the user message in the prompt", () => { + const result = buildThreadTitlePrompt({ + message: "Investigate reconnect regressions after session restore", + }); + + expect(result.prompt).toContain("User message:"); + expect(result.prompt).toContain("Investigate reconnect regressions after session restore"); + expect(result.prompt).not.toContain("Attachment metadata:"); + }); + + it("includes attachment metadata when attachments are provided", () => { + const result = buildThreadTitlePrompt({ + message: "Name this thread from the screenshot", + attachments: [ + { + type: "image" as const, + id: "att-456", + name: "thread.png", + mimeType: "image/png", + sizeBytes: 67890, + }, + ], + }); + + expect(result.prompt).toContain("Attachment metadata:"); + expect(result.prompt).toContain("thread.png"); + expect(result.prompt).toContain("image/png"); + expect(result.prompt).toContain("67890 bytes"); + }); +}); + +describe("sanitizeThreadTitle", () => { + it("truncates long titles with the shared sidebar-safe limit", () => { + expect( + sanitizeThreadTitle( + ' "Reconnect failures after restart because the session state does not recover" ', + ), + ).toBe("Reconnect failures after restart because the se..."); + }); +}); + describe("normalizeCliError", () => { it("detects 'Command not found' and includes CLI name in the message", () => { const error = normalizeCliError( diff --git a/apps/server/src/git/Prompts.ts b/apps/server/src/git/Prompts.ts index 2eacf370eb..4092358825 100644 --- a/apps/server/src/git/Prompts.ts +++ b/apps/server/src/git/Prompts.ts @@ -119,19 +119,24 @@ export interface BranchNamePromptInput { attachments?: ReadonlyArray | undefined; } -export function buildBranchNamePrompt(input: BranchNamePromptInput) { +interface PromptFromMessageInput { + instruction: string; + responseShape: string; + rules: ReadonlyArray; + message: string; + attachments?: ReadonlyArray | undefined; +} + +function buildPromptFromMessage(input: PromptFromMessageInput): string { const attachmentLines = (input.attachments ?? []).map( (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`, ); const promptSections = [ - "You generate concise git branch names.", - "Return a JSON object with key: branch.", + input.instruction, + input.responseShape, "Rules:", - "- Branch should describe the requested work from the user message.", - "- Keep it short and specific (2-6 words).", - "- Use plain words only, no issue prefixes and no punctuation-heavy text.", - "- If images are attached, use them as primary context for visual/UI issues.", + ...input.rules.map((rule) => `- ${rule}`), "", "User message:", limitSection(input.message, 8_000), @@ -144,10 +149,54 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) { ); } - const prompt = promptSections.join("\n"); + return promptSections.join("\n"); +} + +export function buildBranchNamePrompt(input: BranchNamePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You generate concise git branch names.", + responseShape: "Return a JSON object with key: branch.", + rules: [ + "Branch should describe the requested work from the user message.", + "Keep it short and specific (2-6 words).", + "Use plain words only, no issue prefixes and no punctuation-heavy text.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); const outputSchema = Schema.Struct({ branch: Schema.String, }); return { prompt, outputSchema }; } + +// --------------------------------------------------------------------------- +// Thread title +// --------------------------------------------------------------------------- + +export interface ThreadTitlePromptInput { + message: string; + attachments?: ReadonlyArray | undefined; +} + +export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You write concise thread titles for coding conversations.", + responseShape: "Return a JSON object with key: title.", + rules: [ + "Title should summarize the user's request, not restate it verbatim.", + "Keep it short and specific (3-8 words).", + "Avoid quotes, filler, prefixes, and trailing punctuation.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); + const outputSchema = Schema.Struct({ + title: Schema.String, + }); + + return { prompt, outputSchema }; +} diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index b74c526897..d7a28d1763 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -22,16 +22,18 @@ 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; readonly maxOutputBytes?: number; + readonly truncateOutputAtMaxBytes?: boolean; readonly progress?: ExecuteGitProgress; } @@ -39,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 { @@ -92,6 +96,11 @@ export interface GitRangeContext { diffPatch: string; } +export interface GitListWorkspaceFilesResult { + readonly paths: ReadonlyArray; + readonly truncated: boolean; +} + export interface GitRenameBranchInput { cwd: string; oldBranch: string; @@ -189,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 e9f2230f43..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"; @@ -61,12 +61,25 @@ export interface BranchNameGenerationResult { branch: string; } +export interface ThreadTitleGenerationInput { + cwd: string; + message: string; + attachments?: ReadonlyArray | undefined; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface ThreadTitleGenerationResult { + title: string; +} + export interface TextGenerationService { generateCommitMessage( input: CommitMessageGenerationInput, ): Promise; generatePrContent(input: PrContentGenerationInput): Promise; generateBranchName(input: BranchNameGenerationInput): Promise; + generateThreadTitle(input: ThreadTitleGenerationInput): Promise; } /** @@ -93,6 +106,13 @@ export interface TextGenerationShape { readonly generateBranchName: ( input: BranchNameGenerationInput, ) => Effect.Effect; + + /** + * Generate a concise thread title from a user's first message. + */ + readonly generateThreadTitle: ( + input: ThreadTitleGenerationInput, + ) => Effect.Effect; } /** diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index eb208deccb..4a7931c74b 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"; @@ -53,6 +53,27 @@ export function sanitizePrTitle(raw: string): string { return "Update project changes"; } +/** Normalise a raw thread title to a compact single-line sidebar-safe label. */ +export function sanitizeThreadTitle(raw: string): string { + const normalized = raw + .trim() + .split(/\r?\n/g)[0] + ?.trim() + .replace(/^['"`]+|['"`]+$/g, "") + .trim() + .replace(/\s+/g, " "); + + if (!normalized || normalized.trim().length === 0) { + return "New thread"; + } + + if (normalized.length <= 50) { + return normalized; + } + + return `${normalized.slice(0, 47).trimEnd()}...`; +} + /** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */ function cliLabel(cliName: string): string { const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1); 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 846c3778b0..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 = () => { @@ -165,6 +165,19 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(makeKeybindingsLayer())), ); + it.effect("ships configurable thread navigation defaults", () => + Effect.sync(() => { + const defaultsByCommand = new Map( + DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const), + ); + + assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+["); + assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]"); + assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1"); + assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9"); + }), + ); + it.effect("uses defaults in runtime when config is malformed without overriding file", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 58363d2138..086d795c0c 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -9,12 +9,14 @@ import { KeybindingRule, KeybindingsConfig, + KeybindingsConfigError, KeybindingShortcut, KeybindingWhenNode, MAX_KEYBINDINGS_COUNT, MAX_WHEN_EXPRESSION_DEPTH, ResolvedKeybindingRule, ResolvedKeybindingsConfig, + THREAD_JUMP_KEYBINDING_COMMANDS, type ServerConfigIssue, } from "@t3tools/contracts"; import { Mutable } from "effect/Types"; @@ -45,19 +47,6 @@ import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config"; import { 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" } @@ -76,6 +65,12 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+o", command: "editor.openFavorite" }, + { key: "mod+shift+[", command: "thread.previous" }, + { key: "mod+shift+]", command: "thread.next" }, + ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({ + key: `mod+${index + 1}`, + command, + })), ]; function normalizeKeyToken(token: string): string { 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 c644b4778e..0000000000 --- a/apps/server/src/main.test.ts +++ /dev/null @@ -1,396 +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); -let resolvedConfig: ServerConfigShape | null = null; -const serverStart = Effect.acquireRelease( - Effect.gen(function* () { - resolvedConfig = yield* ServerConfig; - start(); - return {} as unknown as Http.Server; - }), - () => Effect.sync(() => stop()), -); -const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred)); - -// Shared service layer used by this CLI test suite. -const testLayer = Layer.mergeAll( - Layer.succeed(CliConfig, { - cwd: "/tmp/t3-test-workspace", - fixPath: Effect.void, - resolveStaticDir: Effect.undefined, - } satisfies CliConfigShape), - Layer.succeed(NetService, { - canListenOnHost: () => Effect.succeed(true), - isPortAvailableOnLoopback: () => Effect.succeed(true), - reserveLoopbackPort: () => Effect.succeed(0), - findAvailablePort, - }), - Layer.succeed(Server, { - start: serverStart, - stopSignal: Effect.void, - } satisfies ServerShape), - Layer.succeed(Open, { - openBrowser: (_target: string) => Effect.void, - openInEditor: () => Effect.void, - } satisfies OpenShape), - 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); - 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("records a startup heartbeat with thread/project counts", () => - Effect.gen(function* () { - const recordTelemetry = vi.fn( - (_event: string, _properties?: Readonly>) => Effect.void, - ); - const getSnapshot = vi.fn(() => - Effect.succeed({ - snapshotSequence: 2, - projects: [{} as OrchestrationReadModel["projects"][number]], - threads: [ - {} as OrchestrationReadModel["threads"][number], - {} as OrchestrationReadModel["threads"][number], - ], - updatedAt: new Date(1).toISOString(), - } satisfies OrchestrationReadModel), - ); - - yield* recordStartupHeartbeat.pipe( - Effect.provideService(ProjectionSnapshotQuery, { - getSnapshot, - }), - Effect.provideService(AnalyticsService, { - record: recordTelemetry, - flush: Effect.void, - }), - ); - - assert.deepEqual(recordTelemetry.mock.calls[0], [ - "server.boot.heartbeat", - { - threadCount: 2, - projectCount: 1, - }, - ]); - }), - ); - - it.effect("does not start server for invalid --mode values", () => - Effect.gen(function* () { - yield* runCli(["--mode", "invalid"]); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for invalid --dev-url values", () => - Effect.gen(function* () { - yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void)); - - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); - - it.effect("does not start server for out-of-range --port values", () => - Effect.gen(function* () { - yield* runCli(["--port", "70000"]); - - // effect/unstable/cli renders help/errors for parse failures and returns success. - assert.equal(start.mock.calls.length, 0); - assert.equal(stop.mock.calls.length, 0); - }), - ); -}); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts deleted file mode 100644 index 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.test.ts b/apps/server/src/open.test.ts index 649e88462c..947a60ac2a 100644 --- a/apps/server/src/open.test.ts +++ b/apps/server/src/open.test.ts @@ -40,6 +40,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { args: ["/tmp/workspace"], }); + const vscodeInsidersLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLaunch, { + command: "code-insiders", + args: ["/tmp/workspace"], + }); + + const vscodiumLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLaunch, { + command: "codium", + args: ["/tmp/workspace"], + }); + const zedLaunch = yield* resolveEditorLaunch( { cwd: "/tmp/workspace", editor: "zed" }, "darwin", @@ -80,6 +98,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], }); + const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLineAndColumn, { + command: "code-insiders", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodiumLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLineAndColumn, { + command: "codium", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + const zedLineAndColumn = yield* resolveEditorLaunch( { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" }, "darwin", @@ -220,13 +256,14 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { const path = yield* Path.Path; const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n"); yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ"); const editors = resolveAvailableEditors("win32", { PATH: dir, PATHEXT: ".COM;.EXE;.BAT;.CMD", }); - assert.deepEqual(editors, ["cursor", "file-manager"]); + assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]); }), ); }); diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts index e7238c04b2..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; @@ -39,10 +36,8 @@ interface CommandAvailabilityOptions { const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/; -function shouldUseGotoFlag(editorId: EditorId, target: string): boolean { - return ( - (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target) - ); +function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean { + return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target); } function fileManagerCommandForPlatform(platform: NodeJS.Platform): string { @@ -213,7 +208,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* ( } if (editorDef.command) { - return shouldUseGotoFlag(editorDef.id, input.cwd) + return shouldUseGotoFlag(editorDef, input.cwd) ? { command: editorDef.command, args: ["--goto", input.cwd] } : { command: editorDef.command, args: [input.cwd] }; } diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 69360ebf6a..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), ); @@ -271,7 +276,7 @@ describe("CheckpointReactor", () => { const reactor = await runtime.runPromise(Effect.service(CheckpointReactor)); const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(reactor.drain); const createdAt = new Date().toISOString(); @@ -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 e4a673342c..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) { @@ -766,7 +767,7 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processInputSafely); - const start: CheckpointReactorShape["start"] = Effect.gen(function* () { + const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () { yield* Effect.forkScoped( Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { if ( diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index a1cbfa002d..6aa889991e 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -120,6 +120,73 @@ describe("OrchestrationEngine", () => { await system.dispose(); }); + it("archives and unarchives threads through orchestration commands", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-archive-create"), + projectId: asProjectId("project-archive"), + title: "Project Archive", + workspaceRoot: "/tmp/project-archive", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-archive-create"), + threadId: ThreadId.makeUnsafe("thread-archive"), + projectId: asProjectId("project-archive"), + title: "Archive me", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.archive", + commandId: CommandId.makeUnsafe("cmd-thread-archive"), + threadId: ThreadId.makeUnsafe("thread-archive"), + }), + ); + expect( + (await system.run(engine.getReadModel())).threads.find( + (thread) => thread.id === "thread-archive", + )?.archivedAt, + ).not.toBeNull(); + + await system.run( + engine.dispatch({ + type: "thread.unarchive", + commandId: CommandId.makeUnsafe("cmd-thread-unarchive"), + threadId: ThreadId.makeUnsafe("thread-archive"), + }), + ); + expect( + (await system.run(engine.getReadModel())).threads.find( + (thread) => thread.id === "thread-archive", + )?.archivedAt, + ).toBeNull(); + + await system.dispose(); + }); + it("replays append-only events from sequence", async () => { const system = await createOrchestrationSystem(); const { engine } = system; 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/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts index 1514bef595..d60f0cf722 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -24,25 +24,28 @@ describe("OrchestrationReactor", () => { Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe( Layer.provideMerge( Layer.succeed(ProviderRuntimeIngestionService, { - start: Effect.sync(() => { + start: () => { started.push("provider-runtime-ingestion"); - }), + return Effect.void; + }, drain: Effect.void, }), ), Layer.provideMerge( Layer.succeed(ProviderCommandReactor, { - start: Effect.sync(() => { + start: () => { started.push("provider-command-reactor"); - }), + return Effect.void; + }, drain: Effect.void, }), ), Layer.provideMerge( Layer.succeed(CheckpointReactor, { - start: Effect.sync(() => { + start: () => { started.push("checkpoint-reactor"); - }), + return Effect.void; + }, drain: Effect.void, }), ), @@ -51,7 +54,7 @@ describe("OrchestrationReactor", () => { const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor)); const scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); expect(started).toEqual([ "provider-runtime-ingestion", diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts index 1e498885a0..99d30c57a2 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -13,10 +13,10 @@ export const makeOrchestrationReactor = Effect.gen(function* () { const providerCommandReactor = yield* ProviderCommandReactor; const checkpointReactor = yield* CheckpointReactor; - const start: OrchestrationReactorShape["start"] = Effect.gen(function* () { - yield* providerRuntimeIngestion.start; - yield* providerCommandReactor.start; - yield* checkpointReactor.start; + const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { + yield* providerRuntimeIngestion.start(); + yield* providerCommandReactor.start(); + yield* checkpointReactor.start(); }); return { diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index ce68d654ef..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"; @@ -77,7 +76,7 @@ interface AttachmentSideEffects { readonly prunedThreadRelativePaths: Map>; } -const materializeAttachmentsForProjection = Effect.fn( +const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")( (input: { readonly attachments: ReadonlyArray }) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments), ); @@ -238,124 +237,145 @@ function collectThreadAttachmentRelativePaths( return relativePaths; } -const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) { +const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* ( + sideEffects: AttachmentSideEffects, +) { const serverConfig = yield* Effect.service(ServerConfig); const fileSystem = yield* Effect.service(FileSystem.FileSystem); const path = yield* Effect.service(Path.Path); const attachmentsRootDir = serverConfig.attachmentsDir; + const readAttachmentRootEntries = fileSystem + .readDirectory(attachmentsRootDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - sideEffects.deletedThreadIds, - (threadId) => - Effect.gen(function* () { - const threadSegment = toSafeThreadAttachmentSegment(threadId); - if (!threadSegment) { - yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", { - threadId, - }); - return; - } - const entries = yield* fileSystem - .readDirectory(attachmentsRootDir, { recursive: false }) - .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - entries, - (entry) => - Effect.gen(function* () { - const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); - if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) { - return; - } - const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry); - if (!attachmentId) { - return; - } - const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); - if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { - return; - } - yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), { - force: true, - }); - }), - { concurrency: 1 }, - ); - }), - { concurrency: 1 }, + const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")( + function* (threadSegment: string, entry: string) { + const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), { + force: true, + }); + }, ); + const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* ( + threadId: string, + ) { + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", { + threadId, + }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry), + { + concurrency: 1, + }, + ); + }); + + const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* ( + threadSegment: string, + keptThreadRelativePaths: Set, + entry: string, + ) { + const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (relativePath.length === 0 || relativePath.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(relativePath); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + + const absolutePath = path.join(attachmentsRootDir, relativePath); + const fileInfo = yield* fileSystem + .stat(absolutePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return; + } + + if (!keptThreadRelativePaths.has(relativePath)) { + yield* fileSystem.remove(absolutePath, { force: true }); + } + }); + + const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* ( + threadId: string, + keptThreadRelativePaths: Set, + ) { + if (sideEffects.deletedThreadIds.has(threadId)) { + return; + } + + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry), + { concurrency: 1 }, + ); + }); + + yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, { + concurrency: 1, + }); + yield* Effect.forEach( sideEffects.prunedThreadRelativePaths.entries(), - ([threadId, keptThreadRelativePaths]) => { - if (sideEffects.deletedThreadIds.has(threadId)) { - return Effect.void; - } - return Effect.gen(function* () { - const threadSegment = toSafeThreadAttachmentSegment(threadId); - if (!threadSegment) { - yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId }); - return; - } - const entries = yield* fileSystem - .readDirectory(attachmentsRootDir, { recursive: false }) - .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - entries, - (entry) => - Effect.gen(function* () { - const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); - if (relativePath.length === 0 || relativePath.includes("/")) { - return; - } - const attachmentId = parseAttachmentIdFromRelativePath(relativePath); - if (!attachmentId) { - return; - } - const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); - if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { - return; - } - - const absolutePath = path.join(attachmentsRootDir, relativePath); - const fileInfo = yield* fileSystem - .stat(absolutePath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - return; - } - - if (!keptThreadRelativePaths.has(relativePath)) { - yield* fileSystem.remove(absolutePath, { force: true }); - } - }), - { concurrency: 1 }, - ); - }); - }, + ([threadId, keptThreadRelativePaths]) => + pruneThreadAttachments(threadId, keptThreadRelativePaths), { concurrency: 1 }, ); }); -const makeOrchestrationProjectionPipeline = Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const eventStore = yield* OrchestrationEventStore; - const projectionStateRepository = yield* ProjectionStateRepository; - const projectionProjectRepository = yield* ProjectionProjectRepository; - const projectionThreadRepository = yield* ProjectionThreadRepository; - const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository; - const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository; - const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository; - const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository; - const projectionTurnRepository = yield* ProjectionTurnRepository; - const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository; +const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")( + function* () { + const sql = yield* SqlClient.SqlClient; + const eventStore = yield* OrchestrationEventStore; + const projectionStateRepository = yield* ProjectionStateRepository; + const projectionProjectRepository = yield* ProjectionProjectRepository; + const projectionThreadRepository = yield* ProjectionThreadRepository; + const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository; + const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository; + const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository; + const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository; + const projectionTurnRepository = yield* ProjectionTurnRepository; + const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; - const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) => - Effect.gen(function* () { + const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyProjectsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "project.created": yield* projectionProjectRepository.upsert({ @@ -412,8 +432,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) => - Effect.gen(function* () { + const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadsProjection", + )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.created": yield* projectionThreadRepository.upsert({ @@ -428,10 +449,41 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { latestTurnId: null, createdAt: event.payload.createdAt, updatedAt: event.payload.updatedAt, + archivedAt: null, deletedAt: null, }); return; + case "thread.archived": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + archivedAt: event.payload.archivedAt, + updatedAt: event.payload.updatedAt, + }); + return; + } + + case "thread.unarchived": { + const existingRow = yield* projectionThreadRepository.getById({ + threadId: event.payload.threadId, + }); + if (Option.isNone(existingRow)) { + return; + } + yield* projectionThreadRepository.upsert({ + ...existingRow.value, + archivedAt: null, + updatedAt: event.payload.updatedAt, + }); + return; + } + case "thread.meta-updated": { const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, @@ -566,11 +618,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadMessagesProjection: ProjectorDefinition["apply"] = ( - event, - attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadMessagesProjection", + )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.message-sent": { const existingRows = yield* projectionThreadMessageRepository.listByThreadId({ @@ -643,11 +693,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadProposedPlansProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.proposed-plan-upserted": yield* projectionThreadProposedPlanRepository.upsert({ @@ -696,11 +744,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadActivitiesProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.activity-appended": yield* projectionThreadActivityRepository.upsert({ @@ -750,11 +796,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadSessionsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadSessionsProjection", + )(function* (event, _attachmentSideEffects) { if (event.type !== "thread.session-set") { return; } @@ -769,11 +813,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { }); }); - const applyThreadTurnsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadTurnsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.turn-start-requested": { yield* projectionTurnRepository.replacePendingTurnStart({ @@ -1027,13 +1069,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void; + const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void; - const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyPendingApprovalsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.activity-appended": { const requestId = @@ -1119,47 +1159,49 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const projectors: ReadonlyArray = [ - { - name: ORCHESTRATION_PROJECTOR_NAMES.projects, - apply: applyProjectsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, - apply: applyThreadMessagesProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, - apply: applyThreadProposedPlansProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities, - apply: applyThreadActivitiesProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions, - apply: applyThreadSessionsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns, - apply: applyThreadTurnsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints, - apply: applyCheckpointsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals, - apply: applyPendingApprovalsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threads, - apply: applyThreadsProjection, - }, - ]; + const projectors: ReadonlyArray = [ + { + name: ORCHESTRATION_PROJECTOR_NAMES.projects, + apply: applyProjectsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, + apply: applyThreadMessagesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, + apply: applyThreadProposedPlansProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities, + apply: applyThreadActivitiesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions, + apply: applyThreadSessionsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns, + apply: applyThreadTurnsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints, + apply: applyCheckpointsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals, + apply: applyPendingApprovalsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threads, + apply: applyThreadsProjection, + }, + ]; - const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) => - Effect.gen(function* () { + const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* ( + projector: ProjectorDefinition, + event: OrchestrationEvent, + ) { const attachmentSideEffects: AttachmentSideEffects = { deletedThreadIds: new Set(), prunedThreadRelativePaths: new Map>(), @@ -1189,65 +1231,65 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { ); }); - const bootstrapProjector = (projector: ProjectorDefinition) => - projectionStateRepository - .getByProjector({ - projector: projector.name, - }) - .pipe( - Effect.flatMap((stateRow) => - Stream.runForEach( - eventStore.readFromSequence( - Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0, + const bootstrapProjector = (projector: ProjectorDefinition) => + projectionStateRepository + .getByProjector({ + projector: projector.name, + }) + .pipe( + Effect.flatMap((stateRow) => + Stream.runForEach( + eventStore.readFromSequence( + Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0, + ), + (event) => runProjectorForEvent(projector, event), ), - (event) => runProjectorForEvent(projector, event), ), + ); + + const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => + Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), { + concurrency: 1, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ServerConfig, serverConfig), + Effect.asVoid, + Effect.catchTag("SqlError", (sqlError) => + Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)), ), ); - const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => - Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), { - concurrency: 1, - }).pipe( + const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach( + projectors, + bootstrapProjector, + { concurrency: 1 }, + ).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.provideService(ServerConfig, serverConfig), Effect.asVoid, + Effect.tap(() => + Effect.logDebug("orchestration projection pipeline bootstrapped").pipe( + Effect.annotateLogs({ projectors: projectors.length }), + ), + ), Effect.catchTag("SqlError", (sqlError) => - Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)), + Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)), ), ); - const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach( - projectors, - bootstrapProjector, - { concurrency: 1 }, - ).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(ServerConfig, serverConfig), - Effect.asVoid, - Effect.tap(() => - Effect.log("orchestration projection pipeline bootstrapped").pipe( - Effect.annotateLogs({ projectors: projectors.length }), - ), - ), - Effect.catchTag("SqlError", (sqlError) => - Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)), - ), - ); - - return { - bootstrap, - projectEvent, - } satisfies OrchestrationProjectionPipelineShape; -}); + return { + bootstrap, + projectEvent, + } satisfies OrchestrationProjectionPipelineShape; + }, +); export const OrchestrationProjectionPipelineLive = Layer.effect( OrchestrationProjectionPipeline, - makeOrchestrationProjectionPipeline, + makeOrchestrationProjectionPipeline(), ).pipe( - Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ProjectionProjectRepositoryLive), Layer.provideMerge(ProjectionThreadRepositoryLive), Layer.provideMerge(ProjectionThreadMessageRepositoryLive), diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 492ab0edc6..d09f3d1ab0 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -279,6 +279,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { }, createdAt: "2026-02-24T00:00:02.000Z", updatedAt: "2026-02-24T00:00:03.000Z", + archivedAt: null, deletedAt: null, messages: [ { diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 5dc19f0e7e..d9563b7f90 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -174,6 +174,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { latest_turn_id AS "latestTurnId", created_at AS "createdAt", updated_at AS "updatedAt", + archived_at AS "archivedAt", deleted_at AS "deletedAt" FROM projection_threads ORDER BY created_at ASC, thread_id ASC @@ -562,6 +563,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { latestTurn: latestTurnByThread.get(row.threadId) ?? null, createdAt: row.createdAt, updatedAt: row.updatedAt, + archivedAt: row.archivedAt, deletedAt: row.deletedAt, messages: messagesByThread.get(row.threadId) ?? [], proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 834ab9be9e..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"; @@ -176,7 +176,7 @@ describe("ProviderCommandReactor", () => { : "renamed-branch", }), ); - const generateBranchName = vi.fn(() => + const generateBranchName = vi.fn((_) => Effect.fail( new TextGenerationError({ operation: "generateBranchName", @@ -184,6 +184,14 @@ describe("ProviderCommandReactor", () => { }), ), ); + const generateThreadTitle = vi.fn((_) => + Effect.fail( + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "disabled in test harness", + }), + ), + ); const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; const service: ProviderServiceShape = { @@ -213,7 +221,10 @@ describe("ProviderCommandReactor", () => { Layer.provideMerge(Layer.succeed(ProviderService, service)), Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)), Layer.provideMerge( - Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape), + Layer.mock(TextGeneration, { + generateBranchName, + generateThreadTitle, + }), ), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)), @@ -224,7 +235,7 @@ describe("ProviderCommandReactor", () => { const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(reactor.drain); await Effect.runPromise( @@ -264,6 +275,7 @@ describe("ProviderCommandReactor", () => { stopSession, renameBranch, generateBranchName, + generateThreadTitle, stateDir, drain, }; @@ -308,6 +320,199 @@ describe("ProviderCommandReactor", () => { expect(thread?.session?.runtimeMode).toBe("approval-required"); }); + it("generates a thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" })); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({ + message: "Please investigate reconnect failures after restarting the session.", + }); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Generated title" + ); + }); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Generated title"); + }); + + it("does not overwrite an existing custom thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-custom"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: "Keep this custom title", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-preserve"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.generateThreadTitle).not.toHaveBeenCalled(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Keep this custom title"); + }); + + it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Fix reconnect spinner on resume"; + harness.generateThreadTitle.mockReturnValue( + Effect.succeed({ + title: "Reconnect spinner resume bug", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-formatted"), + role: "user", + text: "[effort:high]\\n\\nFix reconnect spinner on resume", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Reconnect spinner resume bug" + ); + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Reconnect spinner resume bug"); + }); + + it("generates a worktree branch name for the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-branch"), + threadId: ThreadId.makeUnsafe("thread-1"), + branch: "t3code/1234abcd", + worktreePath: "/tmp/provider-project-worktree", + }), + ); + + harness.generateBranchName.mockImplementation((input: unknown) => + Effect.succeed({ + branch: + typeof input === "object" && + input !== null && + "modelSelection" in input && + typeof input.modelSelection === "object" && + input.modelSelection !== null && + "model" in input.modelSelection && + typeof input.modelSelection.model === "string" + ? `feature/${input.modelSelection.model}` + : "feature/generated", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-branch-model"), + role: "user", + text: "Add a safer reconnect backoff.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateBranchName.mock.calls.length === 1); + expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({ + message: "Add a safer reconnect backoff.", + }); + }); + it("forwards codex model options through session start and turn send", async () => { const harness = await createHarness(); const now = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index f01499599a..8b4a291a8a 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -73,6 +73,19 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; const WORKTREE_BRANCH_PREFIX = "t3code"; const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`); +const DEFAULT_THREAD_TITLE = "New thread"; + +function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean { + const trimmedCurrentTitle = currentTitle.trim(); + if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) { + return true; + } + + const trimmedTitleSeed = titleSeed?.trim(); + return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0 + ? trimmedCurrentTitle === trimmedTitleSeed + : false; +} function isUnknownPendingApprovalRequestError(cause: Cause.Cause): boolean { const error = Cause.squash(cause); @@ -399,7 +412,6 @@ const make = Effect.gen(function* () { readonly threadId: ThreadId; readonly branch: string | null; readonly worktreePath: string | null; - readonly messageId: string; readonly messageText: string; readonly attachments?: ReadonlyArray; }) { @@ -410,16 +422,6 @@ const make = Effect.gen(function* () { return; } - const thread = yield* resolveThread(input.threadId); - if (!thread) { - return; - } - - const userMessages = thread.messages.filter((message) => message.role === "user"); - if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) { - return; - } - const oldBranch = input.branch; const cwd = input.worktreePath; const attachments = input.attachments ?? []; @@ -458,6 +460,49 @@ const make = Effect.gen(function* () { ); }); + const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + readonly titleSeed?: string; + }) { + const attachments = input.attachments ?? []; + yield* Effect.gen(function* () { + const { textGenerationModelSelection: modelSelection } = + yield* serverSettingsService.getSettings; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: input.cwd, + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; + + const thread = yield* resolveThread(input.threadId); + if (!thread) return; + if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { + return; + } + + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("thread-title-rename"), + threadId: input.threadId, + title: generated.title, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider command reactor failed to generate or rename thread title", { + threadId: input.threadId, + cwd: input.cwd, + cause: Cause.pretty(cause), + }), + ), + ); + }); + const processTurnStartRequested = Effect.fnUntraced(function* ( event: Extract, ) { @@ -484,14 +529,35 @@ const make = Effect.gen(function* () { return; } - yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ - threadId: event.payload.threadId, - branch: thread.branch, - worktreePath: thread.worktreePath, - messageId: message.id, - messageText: message.text, - ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), - }).pipe(Effect.forkScoped); + const isFirstUserMessageTurn = + thread.messages.filter((entry) => entry.role === "user").length === 1; + if (isFirstUserMessageTurn) { + const generationCwd = + resolveThreadWorkspaceCwd({ + thread, + projects: (yield* orchestrationEngine.getReadModel()).projects, + }) ?? process.cwd(); + const generationInput = { + messageText: message.text, + ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), + ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}), + }; + + yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ + threadId: event.payload.threadId, + branch: thread.branch, + worktreePath: thread.worktreePath, + ...generationInput, + }).pipe(Effect.forkScoped); + + if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) { + yield* maybeGenerateThreadTitleForFirstTurn({ + threadId: event.payload.threadId, + cwd: generationCwd, + ...generationInput, + }).pipe(Effect.forkScoped); + } + } yield* sendTurnForThread({ threadId: event.payload.threadId, @@ -706,22 +772,24 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processDomainEventSafely); - const start: ProviderCommandReactorShape["start"] = Effect.forkScoped( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () { + const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) { if ( - event.type !== "thread.runtime-mode-set" && - event.type !== "thread.turn-start-requested" && - event.type !== "thread.turn-interrupt-requested" && - event.type !== "thread.approval-response-requested" && - event.type !== "thread.user-input-response-requested" && - event.type !== "thread.session-stop-requested" + event.type === "thread.runtime-mode-set" || + event.type === "thread.turn-start-requested" || + event.type === "thread.turn-interrupt-requested" || + event.type === "thread.approval-response-requested" || + event.type === "thread.user-input-response-requested" || + event.type === "thread.session-stop-requested" ) { - return Effect.void; + return yield* worker.enqueue(event); } + }); - return worker.enqueue(event); - }), - ).pipe(Effect.asVoid); + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent), + ); + }); return { start, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 0fab6ce271..e1eb69b78a 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -4,7 +4,6 @@ import path from "node:path"; import type { OrchestrationReadModel, - ProviderKind, ProviderRuntimeEvent, ProviderSession, } from "@t3tools/contracts"; @@ -25,6 +24,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; +import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; import { ProviderService, @@ -56,7 +56,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); type LegacyProviderRuntimeEvent = { readonly type: string; readonly eventId: EventId; - readonly provider: ProviderKind; + readonly provider: ProviderRuntimeEvent["provider"]; readonly createdAt: string; readonly threadId: ThreadId; readonly turnId?: string | undefined; @@ -66,6 +66,23 @@ type LegacyProviderRuntimeEvent = { readonly [key: string]: unknown; }; +type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & { + readonly type: "turn.completed"; + readonly payload?: undefined; + readonly status: "completed" | "failed" | "interrupted" | "cancelled"; + readonly errorMessage?: string | undefined; +}; + +function isLegacyTurnCompletedEvent( + event: LegacyProviderRuntimeEvent, +): event is LegacyTurnCompletedEvent { + return ( + event.type === "turn.completed" && + event.payload === undefined && + typeof event.status === "string" + ); +} + function createProviderServiceHarness() { const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const runtimeSessions: ProviderSession[] = []; @@ -93,8 +110,23 @@ function createProviderServiceHarness() { runtimeSessions.push(session); }; + const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => { + if (isLegacyTurnCompletedEvent(event)) { + const normalized: Extract = { + ...(event as Omit, "payload">), + payload: { + state: event.status, + ...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}), + }, + }; + return normalized; + } + + return event as ProviderRuntimeEvent; + }; + const emit = (event: LegacyProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); + Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event))); }; return { @@ -172,6 +204,7 @@ describe("ProviderRuntimeIngestion", () => { Layer.provide(SqlitePersistenceMemory), ); const layer = ProviderRuntimeIngestionLive.pipe( + Layer.provideMerge(ProjectionTurnRepositoryLive), Layer.provideMerge(orchestrationLayer), Layer.provideMerge(SqlitePersistenceMemory), Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), @@ -183,7 +216,7 @@ describe("ProviderRuntimeIngestion", () => { const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope))); + await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(ingestion.drain); const createdAt = new Date().toISOString(); @@ -1695,6 +1728,37 @@ describe("ProviderRuntimeIngestion", () => { expect(thread.session?.lastError).toBe("runtime exploded"); }); + it("records runtime.error activities from the typed payload message", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "runtime.error", + eventId: asEventId("evt-runtime-error-activity"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-runtime-error-activity"), + payload: { + message: "runtime activity exploded", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"), + ); + const activity = thread.activities.find( + (entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity", + ); + const activityPayload = + activity?.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : undefined; + + expect(activity?.kind).toBe("runtime.error"); + expect(activityPayload?.message).toBe("runtime activity exploded"); + }); + it("keeps the session running when a runtime.warning arrives during an active turn", async () => { const harness = await createHarness(); const now = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 7297dcb40b..693c30b57e 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -19,7 +19,6 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; -import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; import { isGitRepository } from "../../git/Utils.ts"; import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; @@ -99,10 +98,6 @@ function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId return `plan:${threadId}:event:${event.eventId}`; } -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - function toCanonicalJsonValue(value: unknown): CanonicalJsonValue | undefined { if (value === undefined) { return undefined; @@ -122,14 +117,6 @@ function buildContextWindowActivityPayload( return event.payload.usage; } -function runtimePayloadRecord(event: ProviderRuntimeEvent): Record | undefined { - const payload = (event as { payload?: unknown }).payload; - if (!payload || typeof payload !== "object") { - return undefined; - } - return payload as Record; -} - function normalizeRuntimeTurnState( value: string | undefined, ): "completed" | "failed" | "interrupted" | "cancelled" { @@ -144,23 +131,6 @@ function normalizeRuntimeTurnState( } } -function runtimeTurnState( - event: ProviderRuntimeEvent, -): "completed" | "failed" | "interrupted" | "cancelled" { - const payloadState = asString(runtimePayloadRecord(event)?.state); - return normalizeRuntimeTurnState(payloadState); -} - -function runtimeTurnErrorMessage(event: ProviderRuntimeEvent): string | undefined { - const payloadErrorMessage = asString(runtimePayloadRecord(event)?.errorMessage); - return payloadErrorMessage; -} - -function runtimeErrorMessageFromEvent(event: ProviderRuntimeEvent): string | undefined { - const payloadMessage = asString(runtimePayloadRecord(event)?.message); - return payloadMessage; -} - function orchestrationSessionStatusFromRuntimeState( state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error", ): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" { @@ -264,10 +234,6 @@ function runtimeEventToActivities( } case "runtime.error": { - const message = runtimeErrorMessageFromEvent(event); - if (!message) { - return []; - } return [ { id: event.eventId, @@ -276,7 +242,7 @@ function runtimeEventToActivities( kind: "runtime.error", summary: "Runtime error", payload: { - message: truncateDetail(message), + message: truncateDetail(event.payload.message), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -548,7 +514,7 @@ function runtimeEventToActivities( return []; } -const make = Effect.gen(function* () { +const make = Effect.fn("make")(function* () { const orchestrationEngine = yield* OrchestrationEngineService; const providerService = yield* ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; @@ -635,8 +601,8 @@ const make = Effect.gen(function* () { const appendBufferedAssistantText = (messageId: MessageId, delta: string) => Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( - Effect.flatMap((existingText) => - Effect.gen(function* () { + Effect.flatMap( + Effect.fn("appendBufferedAssistantText")(function* (existingText) { const nextText = Option.match(existingText, { onNone: () => delta, onSome: (text) => `${text}${delta}`, @@ -692,7 +658,7 @@ const make = Effect.gen(function* () { const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId); - const finalizeAssistantMessage = (input: { + const finalizeAssistantMessage = Effect.fn("finalizeAssistantMessage")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; messageId: MessageId; @@ -701,40 +667,39 @@ const make = Effect.gen(function* () { commandTag: string; finalDeltaCommandTag: string; fallbackText?: string; - }) => - Effect.gen(function* () { - const bufferedText = yield* takeBufferedAssistantText(input.messageId); - const text = - bufferedText.length > 0 - ? bufferedText - : (input.fallbackText?.trim().length ?? 0) > 0 - ? input.fallbackText! - : ""; - - if (text.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: providerCommandId(input.event, input.finalDeltaCommandTag), - threadId: input.threadId, - messageId: input.messageId, - delta: text, - ...(input.turnId ? { turnId: input.turnId } : {}), - createdAt: input.createdAt, - }); - } + }) { + const bufferedText = yield* takeBufferedAssistantText(input.messageId); + const text = + bufferedText.length > 0 + ? bufferedText + : (input.fallbackText?.trim().length ?? 0) > 0 + ? input.fallbackText! + : ""; + if (text.length > 0) { yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.complete", - commandId: providerCommandId(input.event, input.commandTag), + type: "thread.message.assistant.delta", + commandId: providerCommandId(input.event, input.finalDeltaCommandTag), threadId: input.threadId, messageId: input.messageId, + delta: text, ...(input.turnId ? { turnId: input.turnId } : {}), createdAt: input.createdAt, }); - yield* clearAssistantMessageState(input.messageId); - }); + } - const upsertProposedPlan = (input: { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.complete", + commandId: providerCommandId(input.event, input.commandTag), + threadId: input.threadId, + messageId: input.messageId, + ...(input.turnId ? { turnId: input.turnId } : {}), + createdAt: input.createdAt, + }); + yield* clearAssistantMessageState(input.messageId); + }); + + const upsertProposedPlan = Effect.fn("upsertProposedPlan")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; threadProposedPlans: ReadonlyArray<{ @@ -748,32 +713,31 @@ const make = Effect.gen(function* () { planMarkdown: string | undefined; createdAt: string; updatedAt: string; - }) => - Effect.gen(function* () { - const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); - if (!planMarkdown) { - return; - } + }) { + const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); + if (!planMarkdown) { + return; + } - const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId); - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: providerCommandId(input.event, "proposed-plan-upsert"), - threadId: input.threadId, - proposedPlan: { - id: input.planId, - turnId: input.turnId ?? null, - planMarkdown, - implementedAt: existingPlan?.implementedAt ?? null, - implementationThreadId: existingPlan?.implementationThreadId ?? null, - createdAt: existingPlan?.createdAt ?? input.createdAt, - updatedAt: input.updatedAt, - }, - createdAt: input.updatedAt, - }); + const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId); + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: providerCommandId(input.event, "proposed-plan-upsert"), + threadId: input.threadId, + proposedPlan: { + id: input.planId, + turnId: input.turnId ?? null, + planMarkdown, + implementedAt: existingPlan?.implementedAt ?? null, + implementationThreadId: existingPlan?.implementationThreadId ?? null, + createdAt: existingPlan?.createdAt ?? input.createdAt, + updatedAt: input.updatedAt, + }, + createdAt: input.updatedAt, }); + }); - const finalizeBufferedProposedPlan = (input: { + const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; threadProposedPlans: ReadonlyArray<{ @@ -786,66 +750,65 @@ const make = Effect.gen(function* () { turnId?: TurnId; fallbackMarkdown?: string; updatedAt: string; - }) => - Effect.gen(function* () { - const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); - const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); - const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); - const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; - if (!planMarkdown) { - return; - } + }) { + const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); + const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); + const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); + const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; + if (!planMarkdown) { + return; + } - yield* upsertProposedPlan({ - event: input.event, - threadId: input.threadId, - threadProposedPlans: input.threadProposedPlans, - planId: input.planId, - ...(input.turnId ? { turnId: input.turnId } : {}), - planMarkdown, - createdAt: - bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 - ? bufferedPlan.createdAt - : input.updatedAt, - updatedAt: input.updatedAt, - }); - yield* clearBufferedProposedPlan(input.planId); + yield* upsertProposedPlan({ + event: input.event, + threadId: input.threadId, + threadProposedPlans: input.threadProposedPlans, + planId: input.planId, + ...(input.turnId ? { turnId: input.turnId } : {}), + planMarkdown, + createdAt: + bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 + ? bufferedPlan.createdAt + : input.updatedAt, + updatedAt: input.updatedAt, }); + yield* clearBufferedProposedPlan(input.planId); + }); - const clearTurnStateForSession = (threadId: ThreadId) => - Effect.gen(function* () { - const prefix = `${threadId}:`; - const proposedPlanPrefix = `plan:${threadId}:`; - const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); - const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); - yield* Effect.forEach( - turnKeys, - (key) => - Effect.gen(function* () { - if (!key.startsWith(prefix)) { - return; - } + const clearTurnStateForSession = Effect.fn("clearTurnStateForSession")(function* ( + threadId: ThreadId, + ) { + const prefix = `${threadId}:`; + const proposedPlanPrefix = `plan:${threadId}:`; + const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); + const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); + yield* Effect.forEach( + turnKeys, + Effect.fn(function* (key) { + if (!key.startsWith(prefix)) { + return; + } - const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); - if (Option.isSome(messageIds)) { - yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { - concurrency: 1, - }).pipe(Effect.asVoid); - } + const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); + if (Option.isSome(messageIds)) { + yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { + concurrency: 1, + }).pipe(Effect.asVoid); + } - yield* Cache.invalidate(turnMessageIdsByTurnKey, key); - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* Effect.forEach( - proposedPlanKeys, - (key) => - key.startsWith(proposedPlanPrefix) - ? Cache.invalidate(bufferedProposedPlanById, key) - : Effect.void, - { concurrency: 1 }, - ).pipe(Effect.asVoid); - }); + yield* Cache.invalidate(turnMessageIdsByTurnKey, key); + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* Effect.forEach( + proposedPlanKeys, + (key) => + key.startsWith(proposedPlanPrefix) + ? Cache.invalidate(bufferedProposedPlanById, key) + : Effect.void, + { concurrency: 1 }, + ).pipe(Effect.asVoid); + }); const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* ( threadId: ThreadId, @@ -920,356 +883,355 @@ const make = Effect.gen(function* () { }); }); - const processRuntimeEvent = (event: ProviderRuntimeEvent) => - Effect.gen(function* () { - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) return; + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) return; - const now = event.createdAt; - const eventTurnId = toTurnId(event.turnId); - const activeTurnId = thread.session?.activeTurnId ?? null; + const now = event.createdAt; + const eventTurnId = toTurnId(event.turnId); + const activeTurnId = thread.session?.activeTurnId ?? null; - const conflictsWithActiveTurn = - activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); - const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; + const conflictsWithActiveTurn = + activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); + const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; - const shouldApplyThreadLifecycle = (() => { - if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { + const shouldApplyThreadLifecycle = (() => { + if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { + return true; + } + switch (event.type) { + case "session.exited": return true; - } + case "session.started": + case "thread.started": + return true; + case "turn.started": + return !conflictsWithActiveTurn; + case "turn.completed": + if (conflictsWithActiveTurn || missingTurnForActiveTurn) { + return false; + } + // Only the active turn may close the lifecycle state. + if (activeTurnId !== null && eventTurnId !== undefined) { + return sameId(activeTurnId, eventTurnId); + } + // If no active turn is tracked, accept completion scoped to this thread. + return true; + default: + return true; + } + })(); + const acceptedTurnStartedSourcePlan = + event.type === "turn.started" && shouldApplyThreadLifecycle + ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) + : null; + + if ( + event.type === "session.started" || + event.type === "session.state.changed" || + event.type === "session.exited" || + event.type === "thread.started" || + event.type === "turn.started" || + event.type === "turn.completed" + ) { + const nextActiveTurnId = + event.type === "turn.started" + ? (eventTurnId ?? null) + : event.type === "turn.completed" || event.type === "session.exited" + ? null + : activeTurnId; + const status = (() => { switch (event.type) { + case "session.state.changed": + return orchestrationSessionStatusFromRuntimeState(event.payload.state); + case "turn.started": + return "running"; case "session.exited": - return true; + return "stopped"; + case "turn.completed": + return normalizeRuntimeTurnState(event.payload.state) === "failed" ? "error" : "ready"; case "session.started": case "thread.started": - return true; - case "turn.started": - return !conflictsWithActiveTurn; - case "turn.completed": - if (conflictsWithActiveTurn || missingTurnForActiveTurn) { - return false; - } - // Only the active turn may close the lifecycle state. - if (activeTurnId !== null && eventTurnId !== undefined) { - return sameId(activeTurnId, eventTurnId); - } - // If no active turn is tracked, accept completion scoped to this thread. - return true; - default: - return true; + // Provider thread/session start notifications can arrive during an + // active turn; preserve turn-running state in that case. + return activeTurnId !== null ? "running" : "ready"; } })(); - const acceptedTurnStartedSourcePlan = - event.type === "turn.started" && shouldApplyThreadLifecycle - ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) - : null; - - if ( - event.type === "session.started" || - event.type === "session.state.changed" || - event.type === "session.exited" || - event.type === "thread.started" || - event.type === "turn.started" || - event.type === "turn.completed" - ) { - const nextActiveTurnId = - event.type === "turn.started" - ? (eventTurnId ?? null) - : event.type === "turn.completed" || event.type === "session.exited" + const lastError = + event.type === "session.state.changed" && event.payload.state === "error" + ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") + : event.type === "turn.completed" && + normalizeRuntimeTurnState(event.payload.state) === "failed" + ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") + : status === "ready" ? null - : activeTurnId; - const status = (() => { - switch (event.type) { - case "session.state.changed": - return orchestrationSessionStatusFromRuntimeState(event.payload.state); - case "turn.started": - return "running"; - case "session.exited": - return "stopped"; - case "turn.completed": - return runtimeTurnState(event) === "failed" ? "error" : "ready"; - case "session.started": - case "thread.started": - // Provider thread/session start notifications can arrive during an - // active turn; preserve turn-running state in that case. - return activeTurnId !== null ? "running" : "ready"; - } - })(); - const lastError = - event.type === "session.state.changed" && event.payload.state === "error" - ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") - : event.type === "turn.completed" && runtimeTurnState(event) === "failed" - ? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed") - : status === "ready" - ? null - : (thread.session?.lastError ?? null); + : (thread.session?.lastError ?? null); - if (shouldApplyThreadLifecycle) { - if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { - yield* markSourceProposedPlanImplemented( - acceptedTurnStartedSourcePlan.sourceThreadId, - acceptedTurnStartedSourcePlan.sourcePlanId, - thread.id, - now, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning( - "provider runtime ingestion failed to mark source proposed plan", - { - eventId: event.eventId, - eventType: event.type, - cause: Cause.pretty(cause), - }, - ), - ), - ); - } - - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: providerCommandId(event, "thread-session-set"), - threadId: thread.id, - session: { - threadId: thread.id, - status, - providerName: event.provider, - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: nextActiveTurnId, - lastError, - updatedAt: now, - }, - createdAt: now, - }); + if (shouldApplyThreadLifecycle) { + if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { + yield* markSourceProposedPlanImplemented( + acceptedTurnStartedSourcePlan.sourceThreadId, + acceptedTurnStartedSourcePlan.sourcePlanId, + thread.id, + now, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider runtime ingestion failed to mark source proposed plan", { + eventId: event.eventId, + eventType: event.type, + cause: Cause.pretty(cause), + }), + ), + ); } + + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "thread-session-set"), + threadId: thread.id, + session: { + threadId: thread.id, + status, + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: nextActiveTurnId, + lastError, + updatedAt: now, + }, + createdAt: now, + }); + } + } + + const assistantDelta = + event.type === "content.delta" && event.payload.streamKind === "assistant_text" + ? event.payload.delta + : undefined; + const proposedPlanDelta = + event.type === "turn.proposed.delta" ? event.payload.delta : undefined; + + if (assistantDelta && assistantDelta.length > 0) { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const turnId = toTurnId(event.turnId); + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); } - const assistantDelta = - event.type === "content.delta" && event.payload.streamKind === "assistant_text" - ? event.payload.delta - : undefined; - const proposedPlanDelta = - event.type === "turn.proposed.delta" ? event.payload.delta : undefined; - - if (assistantDelta && assistantDelta.length > 0) { - const assistantMessageId = MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ); - const turnId = toTurnId(event.turnId); - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), - ); - if (assistantDeliveryMode === "buffered") { - const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); - if (spillChunk.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: providerCommandId(event, "assistant-delta-buffer-spill"), - threadId: thread.id, - messageId: assistantMessageId, - delta: spillChunk, - ...(turnId ? { turnId } : {}), - createdAt: now, - }); - } - } else { + const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), + ); + if (assistantDeliveryMode === "buffered") { + const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); + if (spillChunk.length > 0) { yield* orchestrationEngine.dispatch({ type: "thread.message.assistant.delta", - commandId: providerCommandId(event, "assistant-delta"), + commandId: providerCommandId(event, "assistant-delta-buffer-spill"), threadId: thread.id, messageId: assistantMessageId, - delta: assistantDelta, + delta: spillChunk, ...(turnId ? { turnId } : {}), createdAt: now, }); } - } - - if (proposedPlanDelta && proposedPlanDelta.length > 0) { - const planId = proposedPlanIdFromEvent(event, thread.id); - yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); - } - - const assistantCompletion = - event.type === "item.completed" && event.payload.itemType === "assistant_message" - ? { - messageId: MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ), - fallbackText: event.payload.detail, - } - : undefined; - const proposedPlanCompletion = - event.type === "turn.proposed.completed" - ? { - planId: proposedPlanIdFromEvent(event, thread.id), - turnId: toTurnId(event.turnId), - planMarkdown: event.payload.planMarkdown, - } - : undefined; - - if (assistantCompletion) { - const assistantMessageId = assistantCompletion.messageId; - const turnId = toTurnId(event.turnId); - const existingAssistantMessage = thread.messages.find( - (entry) => entry.id === assistantMessageId, - ); - const shouldApplyFallbackCompletionText = - !existingAssistantMessage || existingAssistantMessage.text.length === 0; - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - yield* finalizeAssistantMessage({ - event, + } else { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.delta", + commandId: providerCommandId(event, "assistant-delta"), threadId: thread.id, messageId: assistantMessageId, + delta: assistantDelta, ...(turnId ? { turnId } : {}), createdAt: now, - commandTag: "assistant-complete", - finalDeltaCommandTag: "assistant-delta-finalize", - ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText - ? { fallbackText: assistantCompletion.fallbackText } - : {}), }); + } + } - if (turnId) { - yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); - } + if (proposedPlanDelta && proposedPlanDelta.length > 0) { + const planId = proposedPlanIdFromEvent(event, thread.id); + yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); + } + + const assistantCompletion = + event.type === "item.completed" && event.payload.itemType === "assistant_message" + ? { + messageId: MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ), + fallbackText: event.payload.detail, + } + : undefined; + const proposedPlanCompletion = + event.type === "turn.proposed.completed" + ? { + planId: proposedPlanIdFromEvent(event, thread.id), + turnId: toTurnId(event.turnId), + planMarkdown: event.payload.planMarkdown, + } + : undefined; + + if (assistantCompletion) { + const assistantMessageId = assistantCompletion.messageId; + const turnId = toTurnId(event.turnId); + const existingAssistantMessage = thread.messages.find( + (entry) => entry.id === assistantMessageId, + ); + const shouldApplyFallbackCompletionText = + !existingAssistantMessage || existingAssistantMessage.text.length === 0; + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); } - if (proposedPlanCompletion) { + yield* finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + ...(turnId ? { turnId } : {}), + createdAt: now, + commandTag: "assistant-complete", + finalDeltaCommandTag: "assistant-delta-finalize", + ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText + ? { fallbackText: assistantCompletion.fallbackText } + : {}), + }); + + if (turnId) { + yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); + } + } + + if (proposedPlanCompletion) { + yield* finalizeBufferedProposedPlan({ + event, + threadId: thread.id, + threadProposedPlans: thread.proposedPlans, + planId: proposedPlanCompletion.planId, + ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), + fallbackMarkdown: proposedPlanCompletion.planMarkdown, + updatedAt: now, + }); + } + + if (event.type === "turn.completed") { + const turnId = toTurnId(event.turnId); + if (turnId) { + const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); + yield* Effect.forEach( + assistantMessageIds, + (assistantMessageId) => + finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + turnId, + createdAt: now, + commandTag: "assistant-complete-finalize", + finalDeltaCommandTag: "assistant-delta-finalize-fallback", + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + yield* finalizeBufferedProposedPlan({ event, threadId: thread.id, threadProposedPlans: thread.proposedPlans, - planId: proposedPlanCompletion.planId, - ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), - fallbackMarkdown: proposedPlanCompletion.planMarkdown, + planId: proposedPlanIdForTurn(thread.id, turnId), + turnId, updatedAt: now, }); } + } - if (event.type === "turn.completed") { - const turnId = toTurnId(event.turnId); - if (turnId) { - const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); - yield* Effect.forEach( - assistantMessageIds, - (assistantMessageId) => - finalizeAssistantMessage({ - event, - threadId: thread.id, - messageId: assistantMessageId, - turnId, - createdAt: now, - commandTag: "assistant-complete-finalize", - finalDeltaCommandTag: "assistant-delta-finalize-fallback", - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + if (event.type === "session.exited") { + yield* clearTurnStateForSession(thread.id); + } - yield* finalizeBufferedProposedPlan({ - event, + if (event.type === "runtime.error") { + const runtimeErrorMessage = event.payload.message; + + const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD + ? true + : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); + + if (shouldApplyRuntimeError) { + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "runtime-error-session-set"), + threadId: thread.id, + session: { threadId: thread.id, - threadProposedPlans: thread.proposedPlans, - planId: proposedPlanIdForTurn(thread.id, turnId), - turnId, + status: "error", + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: eventTurnId ?? null, + lastError: runtimeErrorMessage, updatedAt: now, - }); - } + }, + createdAt: now, + }); } + } - if (event.type === "session.exited") { - yield* clearTurnStateForSession(thread.id); - } + if (event.type === "thread.metadata.updated" && event.payload.name) { + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: providerCommandId(event, "thread-meta-update"), + threadId: thread.id, + title: event.payload.name, + }); + } - if (event.type === "runtime.error") { - const runtimeErrorMessage = runtimeErrorMessageFromEvent(event) ?? "Provider runtime error"; - - const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD - ? true - : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); - - if (shouldApplyRuntimeError) { + if (event.type === "turn.diff.updated") { + const turnId = toTurnId(event.turnId); + if (turnId && (yield* isGitRepoForThread(thread.id))) { + // Skip if a checkpoint already exists for this turn. A real + // (non-placeholder) capture from CheckpointReactor should not + // be clobbered, and dispatching a duplicate placeholder for the + // same turnId would produce an unstable checkpointTurnCount. + if (thread.checkpoints.some((c) => c.turnId === turnId)) { + // Already tracked; no-op. + } else { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const maxTurnCount = thread.checkpoints.reduce( + (max, c) => Math.max(max, c.checkpointTurnCount), + 0, + ); yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: providerCommandId(event, "runtime-error-session-set"), + type: "thread.turn.diff.complete", + commandId: providerCommandId(event, "thread-turn-diff-complete"), threadId: thread.id, - session: { - threadId: thread.id, - status: "error", - providerName: event.provider, - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: eventTurnId ?? null, - lastError: runtimeErrorMessage, - updatedAt: now, - }, + turnId, + completedAt: now, + checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), + status: "missing", + files: [], + assistantMessageId, + checkpointTurnCount: maxTurnCount + 1, createdAt: now, }); } } + } - if (event.type === "thread.metadata.updated" && event.payload.name) { - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: providerCommandId(event, "thread-meta-update"), - threadId: thread.id, - title: event.payload.name, - }); - } - - if (event.type === "turn.diff.updated") { - const turnId = toTurnId(event.turnId); - if (turnId && (yield* isGitRepoForThread(thread.id))) { - // Skip if a checkpoint already exists for this turn. A real - // (non-placeholder) capture from CheckpointReactor should not - // be clobbered, and dispatching a duplicate placeholder for the - // same turnId would produce an unstable checkpointTurnCount. - if (thread.checkpoints.some((c) => c.turnId === turnId)) { - // Already tracked; no-op. - } else { - const assistantMessageId = MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ); - const maxTurnCount = thread.checkpoints.reduce( - (max, c) => Math.max(max, c.checkpointTurnCount), - 0, - ); - yield* orchestrationEngine.dispatch({ - type: "thread.turn.diff.complete", - commandId: providerCommandId(event, "thread-turn-diff-complete"), - threadId: thread.id, - turnId, - completedAt: now, - checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), - status: "missing", - files: [], - assistantMessageId, - checkpointTurnCount: maxTurnCount + 1, - createdAt: now, - }); - } - } - } - - const activities = runtimeEventToActivities(event); - yield* Effect.forEach(activities, (activity) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: providerCommandId(event, "thread-activity-append"), - threadId: thread.id, - activity, - createdAt: activity.createdAt, - }), - ).pipe(Effect.asVoid); - }); + const activities = runtimeEventToActivities(event); + yield* Effect.forEach(activities, (activity) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: providerCommandId(event, "thread-activity-append"), + threadId: thread.id, + activity, + createdAt: activity.createdAt, + }), + ).pipe(Effect.asVoid); + }); const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void; @@ -1293,7 +1255,7 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processInputSafely); - const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () { + const start: ProviderRuntimeIngestionShape["start"] = Effect.fn("start")(function* () { yield* Effect.forkScoped( Stream.runForEach(providerService.streamEvents, (event) => worker.enqueue({ source: "runtime", event }), @@ -1315,7 +1277,4 @@ const make = Effect.gen(function* () { } satisfies ProviderRuntimeIngestionShape; }); -export const ProviderRuntimeIngestionLive = Layer.effect( - ProviderRuntimeIngestionService, - make, -).pipe(Layer.provide(ProjectionTurnRepositoryLive)); +export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make()); 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/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index c96385cad1..f7ebf69344 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -3,10 +3,12 @@ import { ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema, ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema, ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema, + ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema, ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema, ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema, ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema, ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema, + ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema, ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema, ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema, ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema, @@ -26,10 +28,12 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema; export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema; +export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema; export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema; export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema; export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema; export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema; +export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema; export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema; export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema; diff --git a/apps/server/src/orchestration/Services/CheckpointReactor.ts b/apps/server/src/orchestration/Services/CheckpointReactor.ts index 612bc22acb..539ac784cd 100644 --- a/apps/server/src/orchestration/Services/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Services/CheckpointReactor.ts @@ -22,7 +22,7 @@ export interface CheckpointReactorShape { * Consumes both orchestration-domain and provider-runtime events via an * internal queue. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/orchestration/Services/OrchestrationReactor.ts b/apps/server/src/orchestration/Services/OrchestrationReactor.ts index 258ef2d614..9b628eebda 100644 --- a/apps/server/src/orchestration/Services/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Services/OrchestrationReactor.ts @@ -19,7 +19,7 @@ export interface OrchestrationReactorShape { * The returned effect must be run in a scope so all worker fibers can be * finalized on shutdown. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; } /** diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts index 8f20571c15..8f96d8fb99 100644 --- a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts @@ -22,7 +22,7 @@ export interface ProviderCommandReactorShape { * Filters orchestration domain events to provider-intent types before * processing. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts index 2bbb157f10..f1b95762a2 100644 --- a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts @@ -22,7 +22,7 @@ export interface ProviderRuntimeIngestionShape { * Uses an internal queue and continues after non-interrupt failures by * logging warnings. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.ts index b07eb4234f..43d665a2c9 100644 --- a/apps/server/src/orchestration/commandInvariants.test.ts +++ b/apps/server/src/orchestration/commandInvariants.test.ts @@ -66,6 +66,7 @@ const readModel: OrchestrationReadModel = { worktreePath: null, createdAt: now, updatedAt: now, + archivedAt: null, latestTurn: null, messages: [], session: null, @@ -88,6 +89,7 @@ const readModel: OrchestrationReadModel = { worktreePath: null, createdAt: now, updatedAt: now, + archivedAt: null, latestTurn: null, messages: [], session: null, diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index 6acb9c82ba..009fdb190e 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -88,6 +88,44 @@ export function requireThread(input: { ); } +export function requireThreadArchived(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + return requireThread(input).pipe( + Effect.flatMap((thread) => + thread.archivedAt !== null + ? Effect.succeed(thread) + : Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' is not archived for command '${input.command.type}'.`, + ), + ), + ), + ); +} + +export function requireThreadNotArchived(input: { + readonly readModel: OrchestrationReadModel; + readonly command: OrchestrationCommand; + readonly threadId: ThreadId; +}): Effect.Effect { + return requireThread(input).pipe( + Effect.flatMap((thread) => + thread.archivedAt === null + ? Effect.succeed(thread) + : Effect.fail( + invariantError( + input.command.type, + `Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`, + ), + ), + ), + ); +} + export function requireThreadAbsent(input: { readonly readModel: OrchestrationReadModel; readonly command: OrchestrationCommand; diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index c4cfd2314b..22f5bcb280 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -10,11 +10,12 @@ import { requireProject, requireProjectAbsent, requireThread, + requireThreadArchived, requireThreadAbsent, + requireThreadNotArchived, } from "./commandInvariants.ts"; const nowIso = () => new Date().toISOString(); - const defaultMetadata: Omit = { eventId: crypto.randomUUID() as OrchestrationEvent["eventId"], aggregateKind: "thread", @@ -190,6 +191,51 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }; } + case "thread.archive": { + yield* requireThreadNotArchived({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.archived", + payload: { + threadId: command.threadId, + archivedAt: occurredAt, + updatedAt: occurredAt, + }, + }; + } + + case "thread.unarchive": { + yield* requireThreadArchived({ + readModel, + command, + threadId: command.threadId, + }); + const occurredAt = nowIso(); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt, + commandId: command.commandId, + }), + type: "thread.unarchived", + payload: { + threadId: command.threadId, + updatedAt: occurredAt, + }, + }; + } + case "thread.meta.update": { yield* requireThread({ readModel, @@ -329,6 +375,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.modelSelection !== undefined ? { modelSelection: command.modelSelection } : {}), + ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}), runtimeMode: targetThread.runtimeMode, interactionMode: targetThread.interactionMode, ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}), diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index fd95d028d8..13ae5e422f 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -87,6 +87,7 @@ describe("orchestration projector", () => { latestTurn: null, createdAt: now, updatedAt: now, + archivedAt: null, deletedAt: null, messages: [], proposedPlans: [], @@ -131,6 +132,78 @@ describe("orchestration projector", () => { ).rejects.toBeDefined(); }); + it("applies thread.archived and thread.unarchived events", async () => { + const now = new Date().toISOString(); + const later = new Date(Date.parse(now) + 1_000).toISOString(); + const created = await Effect.runPromise( + projectEvent( + createEmptyReadModel(now), + makeEvent({ + sequence: 1, + type: "thread.created", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: now, + commandId: "cmd-thread-create", + payload: { + threadId: "thread-1", + projectId: "project-1", + title: "demo", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: now, + updatedAt: now, + }, + }), + ), + ); + + const archived = await Effect.runPromise( + projectEvent( + created, + makeEvent({ + sequence: 2, + type: "thread.archived", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: later, + commandId: "cmd-thread-archive", + payload: { + threadId: "thread-1", + archivedAt: later, + updatedAt: later, + }, + }), + ), + ); + expect(archived.threads[0]?.archivedAt).toBe(later); + + const unarchived = await Effect.runPromise( + projectEvent( + archived, + makeEvent({ + sequence: 3, + type: "thread.unarchived", + aggregateKind: "thread", + aggregateId: "thread-1", + occurredAt: later, + commandId: "cmd-thread-unarchive", + payload: { + threadId: "thread-1", + updatedAt: later, + }, + }), + ), + ); + expect(unarchived.threads[0]?.archivedAt).toBeNull(); + }); + it("keeps projector forward-compatible for unhandled event types", async () => { const now = new Date().toISOString(); const model = createEmptyReadModel(now); @@ -472,7 +545,7 @@ describe("orchestration projector", () => { tone: "tool", kind: "tool.started", summary: "Edit file started", - payload: { toolKind: "command" }, + payload: { itemType: "command_execution" }, turnId: "turn-1", createdAt: "2026-02-23T10:00:02.750Z", }, @@ -546,7 +619,7 @@ describe("orchestration projector", () => { tone: "tool", kind: "tool.completed", summary: "Edit file complete", - payload: { toolKind: "command" }, + payload: { itemType: "command_execution" }, turnId: "turn-2", createdAt: "2026-02-23T10:00:04.750Z", }, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 05a660f753..deb8a6d44d 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -14,12 +14,14 @@ import { ProjectDeletedPayload, ProjectMetaUpdatedPayload, ThreadActivityAppendedPayload, + ThreadArchivedPayload, ThreadCreatedPayload, ThreadDeletedPayload, ThreadInteractionModeSetPayload, ThreadMetaUpdatedPayload, ThreadProposedPlanUpsertedPayload, ThreadRuntimeModeSetPayload, + ThreadUnarchivedPayload, ThreadRevertedPayload, ThreadSessionSetPayload, ThreadTurnDiffCompletedPayload, @@ -260,6 +262,7 @@ export function projectEvent( latestTurn: null, createdAt: payload.createdAt, updatedAt: payload.updatedAt, + archivedAt: null, deletedAt: null, messages: [], activities: [], @@ -289,6 +292,28 @@ export function projectEvent( })), ); + case "thread.archived": + return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + archivedAt: payload.archivedAt, + updatedAt: payload.updatedAt, + }), + })), + ); + + case "thread.unarchived": + return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe( + Effect.map((payload) => ({ + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + archivedAt: null, + updatedAt: payload.updatedAt, + }), + })), + ); + case "thread.meta-updated": return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe( Effect.map((payload) => ({ diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts new file mode 100644 index 0000000000..ca03ab5868 --- /dev/null +++ b/apps/server/src/os-jank.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from "vitest"; + +import { fixPath } from "./os-jank"; + +describe("fixPath", () => { + it("hydrates PATH on linux using the resolved login shell", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + }; + const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin"); + + fixPath({ + env, + platform: "linux", + readPath, + }); + + expect(readPath).toHaveBeenCalledWith("/bin/zsh"); + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + }); + + it("does nothing outside macOS and linux even when SHELL is set", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + }; + const readPath = vi.fn(() => "/usr/local/bin:/usr/bin"); + + fixPath({ + env, + platform: "win32", + readPath, + }); + + expect(readPath).not.toHaveBeenCalled(); + expect(env.PATH).toBe("C:\\Windows\\System32"); + }); +}); diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index 0721d0d9f8..c3629e8fde 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -1,15 +1,25 @@ import * as OS from "node:os"; import { Effect, Path } from "effect"; -import { readPathFromLoginShell } from "@t3tools/shared/shell"; +import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell"; -export function fixPath(): void { - if (process.platform !== "darwin") return; +export function fixPath( + options: { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; + readPath?: typeof readPathFromLoginShell; + } = {}, +): void { + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; + + const env = options.env ?? process.env; try { - const shell = process.env.SHELL ?? "/bin/zsh"; - const result = readPathFromLoginShell(shell); + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + const result = (options.readPath ?? readPathFromLoginShell)(shell); if (result) { - process.env.PATH = result; + env.PATH = result; } } catch { // Silently ignore — keep default PATH diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index 0ca13f2e97..b0e1774837 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -87,6 +87,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => { latestTurnId: null, createdAt: "2026-03-24T00:00:00.000Z", updatedAt: "2026-03-24T00:00:00.000Z", + archivedAt: null, deletedAt: null, }); diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 344f199092..48dd51fdca 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -39,6 +39,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { latest_turn_id, created_at, updated_at, + archived_at, deleted_at ) VALUES ( @@ -53,6 +54,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.latestTurnId}, ${row.createdAt}, ${row.updatedAt}, + ${row.archivedAt}, ${row.deletedAt} ) ON CONFLICT (thread_id) @@ -67,6 +69,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { latest_turn_id = excluded.latest_turn_id, created_at = excluded.created_at, updated_at = excluded.updated_at, + archived_at = excluded.archived_at, deleted_at = excluded.deleted_at `, }); @@ -88,6 +91,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { latest_turn_id AS "latestTurnId", created_at AS "createdAt", updated_at AS "updatedAt", + archived_at AS "archivedAt", deleted_at AS "deletedAt" FROM projection_threads WHERE thread_id = ${threadId} @@ -111,6 +115,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { latest_turn_id AS "latestTurnId", created_at AS "createdAt", updated_at AS "updatedAt", + archived_at AS "archivedAt", deleted_at AS "deletedAt" FROM projection_threads WHERE project_id = ${projectId} diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 7ee45514e5..c759665f06 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -29,6 +29,8 @@ import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts"; import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts"; import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts"; import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts"; +import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts"; +import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts"; /** * Migration loader with all migrations defined inline. @@ -57,6 +59,8 @@ export const migrationEntries = [ [14, "ProjectionThreadProposedPlanImplementation", Migration0014], [15, "ProjectionTurnsSourceProposedPlan", Migration0015], [16, "CanonicalizeModelSelections", Migration0016], + [17, "ProjectionThreadsArchivedAt", Migration0017], + [18, "ProjectionThreadsArchivedAtIndex", Migration0018], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts index 039a63d60b..d74e9fe08c 100644 --- a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts +++ b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts @@ -128,6 +128,20 @@ layer("016_CanonicalizeModelSelections", (it) => { '{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', '{}' ), + ( + 'event-project-created-null-model', + 'project', + 'project-3', + 1, + 'project.created', + '2026-01-01T00:00:00.000Z', + 'command-project-created-null-model', + NULL, + 'correlation-project-created-null-model', + 'user', + '{"projectId":"project-3","title":"Null Model Project","workspaceRoot":"/tmp/project-3","defaultModel":null,"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}', + '{}' + ), ( 'event-thread-created', 'thread', @@ -284,6 +298,16 @@ layer("016_CanonicalizeModelSelections", (it) => { }); assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), { + projectId: "project-3", + title: "Null Model Project", + workspaceRoot: "/tmp/project-3", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + + assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), { threadId: "thread-1", projectId: "project-1", title: "Thread", @@ -303,7 +327,7 @@ layer("016_CanonicalizeModelSelections", (it) => { updatedAt: "2026-01-01T00:00:00.000Z", }); - assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), { + assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), { threadId: "thread-2", projectId: "project-1", title: "Fallback Thread", @@ -322,7 +346,7 @@ layer("016_CanonicalizeModelSelections", (it) => { updatedAt: "2026-01-01T00:00:00.000Z", }); - assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), { + assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), { threadId: "thread-1", turnId: "turn-1", input: "hi", @@ -336,7 +360,7 @@ layer("016_CanonicalizeModelSelections", (it) => { deliveryMode: "buffered", }); - assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), { + assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), { threadId: "thread-3", projectId: "project-1", title: "Ancient Thread", diff --git a/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts new file mode 100644 index 0000000000..35d05f189b --- /dev/null +++ b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts @@ -0,0 +1,18 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + + if (columns.some((column) => column.name === "archived_at")) { + return; + } + + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN archived_at TEXT + `; +}); diff --git a/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts new file mode 100644 index 0000000000..b12ab1bcfb --- /dev/null +++ b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts @@ -0,0 +1,11 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at + ON projection_threads(project_id, archived_at) + `; +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts index 1d6e22d9b0..78dbe8a1a9 100644 --- a/apps/server/src/persistence/NodeSqliteClient.ts +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -20,7 +20,7 @@ import * as Stream from "effect/Stream"; import * as Reactivity from "effect/unstable/reactivity/Reactivity"; import * as Client from "effect/unstable/sql/SqlClient"; import type { Connection } from "effect/unstable/sql/SqlConnection"; -import { SqlError } from "effect/unstable/sql/SqlError"; +import { SqlError, classifySqliteError } from "effect/unstable/sql/SqlError"; import * as Statement from "effect/unstable/sql/Statement"; const ATTR_DB_SYSTEM_NAME = "db.system.name"; @@ -109,7 +109,13 @@ const makeWithDatabase = ( lookup: (sql: string) => Effect.try({ try: () => db.prepare(sql), - catch: (cause) => new SqlError({ cause, message: "Failed to prepare statement" }), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to prepare statement", + operation: "prepare", + }), + }), }), }); @@ -127,7 +133,14 @@ const makeWithDatabase = ( const result = statement.run(...(params as any)); return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []); } catch (cause) { - return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" })); + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), + ); } }); @@ -150,7 +163,13 @@ const makeWithDatabase = ( statement.run(...(params as any)); return []; }, - catch: (cause) => new SqlError({ cause, message: "Failed to execute statement" }), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), + }), }), (statement) => Effect.sync(() => { diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index cf4bd55a81..59505c1253 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -32,6 +32,7 @@ export const ProjectionThread = Schema.Struct({ latestTurnId: Schema.NullOr(TurnId), createdAt: IsoDateTime, updatedAt: IsoDateTime, + archivedAt: Schema.NullOr(IsoDateTime), deletedAt: Schema.NullOr(IsoDateTime), }); export type ProjectionThread = typeof ProjectionThread.Type; diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index cbf4b76063..5402612887 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -37,7 +37,7 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`); } -function isWindowsCommandNotFound(code: number | null, stderr: string): boolean { +export function isWindowsCommandNotFound(code: number | null, stderr: string): boolean { if (process.platform !== "win32") return false; if (code === 9009) return true; return /is not recognized as an internal or external command/i.test(stderr); 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 1036e8d4d2..9128f1717c 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; @@ -347,7 +350,7 @@ describe("ClaudeAdapterLive", () => { ); }); - it.effect("ignores unsupported max effort for Sonnet 4.6", () => { + it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => { const harness = makeHarness(); return Effect.gen(function* () { const adapter = yield* ClaudeAdapter; @@ -365,7 +368,7 @@ describe("ClaudeAdapterLive", () => { }); const createInput = harness.getLastCreateQueryInput(); - assert.equal(createInput?.options.effort, undefined); + assert.equal(createInput?.options.effort, "high"); }).pipe( Effect.provideService(Random.Random, makeDeterministicRandomService()), Effect.provide(harness.layer), @@ -532,7 +535,7 @@ describe("ClaudeAdapterLive", () => { }); const createInput = harness.getLastCreateQueryInput(); - assert.equal(createInput?.options.effort, undefined); + assert.equal(createInput?.options.effort, "high"); const promptText = yield* Effect.promise(() => readFirstPromptText(createInput)); assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases"); }).pipe( @@ -1106,10 +1109,13 @@ describe("ClaudeAdapterLive", () => { it.effect("closes the session when the Claude stream aborts after a turn starts", () => { const harness = makeHarness(); return Effect.gen(function* () { + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + const adapter = yield* ClaudeAdapter; const runtimeEvents: Array = []; - const runtimeEventsFiber = Effect.runFork( + const runtimeEventsFiber = runFork( Stream.runForEach(adapter.streamEvents, (event) => Effect.sync(() => { runtimeEvents.push(event); @@ -1202,9 +1208,12 @@ describe("ClaudeAdapterLive", () => { ); return Effect.gen(function* () { + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + const adapter = yield* ClaudeAdapter; - const runtimeEventsFiber = Effect.runFork( + const runtimeEventsFiber = runFork( Stream.runForEach(adapter.streamEvents, () => Effect.void), ); @@ -2386,6 +2395,85 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect( + "does not re-set the Claude model when the session already uses the same effective API model", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + const modelSelection = { + provider: "claudeAgent" as const, + model: "claude-opus-4-6", + }; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + modelSelection, + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection, + attachments: [], + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello again", + modelSelection, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, []); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }, + ); + + it.effect("re-sets the Claude model when the effective API model changes", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + + const session = yield* adapter.startSession({ + threadId: THREAD_ID, + provider: "claudeAgent", + runtimeMode: "full-access", + }); + + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { + contextWindow: "1m", + }, + }, + attachments: [], + }); + yield* adapter.sendTurn({ + threadId: session.threadId, + input: "hello again", + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + }, + attachments: [], + }); + + assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]", "claude-opus-4-6"]); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + it.effect("sets plan permission mode on sendTurn when interactionMode is plan", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index f12c40a004..482d9867a7 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -41,7 +41,12 @@ import { type UserInputQuestion, ClaudeCodeEffort, } from "@t3tools/contracts"; -import { hasEffortLevel, applyClaudePromptEffortPrefix, trimOrNull } from "@t3tools/shared/model"; +import { + applyClaudePromptEffortPrefix, + resolveApiModelId, + resolveEffort, + trimOrNull, +} from "@t3tools/shared/model"; import { Cause, DateTime, @@ -144,6 +149,7 @@ interface ClaudeSessionContext { streamFiber: Fiber.Fiber | undefined; readonly startedAt: string; readonly basePermissionMode: PermissionMode | undefined; + currentApiModelId: string | undefined; resumeSessionId: string | undefined; readonly pendingApprovals: Map; readonly pendingUserInputs: Map; @@ -507,16 +513,15 @@ const CLAUDE_SETTING_SOURCES = [ function buildPromptText(input: ProviderSendTurnInput): string { const rawEffort = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null; - const requestedEffort = trimOrNull(rawEffort); const claudeModel = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined; const caps = getClaudeModelCapabilities(claudeModel); + + // For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink"). + // resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly. + const trimmedEffort = trimOrNull(rawEffort); const promptEffort = - requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0 - ? "ultrathink" - : requestedEffort && hasEffortLevel(caps, requestedEffort) - ? requestedEffort - : null; + trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null; return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort); } @@ -529,7 +534,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; } @@ -548,69 +553,67 @@ function buildClaudeImageContentBlock(input: { }; } -function buildUserMessageEffect( +const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* ( input: ProviderSendTurnInput, dependencies: { readonly fileSystem: FileSystem.FileSystem; readonly attachmentsDir: string; }, -): Effect.Effect { - return Effect.gen(function* () { - const text = buildPromptText(input); - const sdkContent: Array> = []; +) { + const text = buildPromptText(input); + const sdkContent: Array> = []; - if (text.length > 0) { - sdkContent.push({ type: "text", text }); + if (text.length > 0) { + sdkContent.push({ type: "text", text }); + } + + for (const attachment of input.attachments ?? []) { + if (attachment.type !== "image") { + continue; } - for (const attachment of input.attachments ?? []) { - if (attachment.type !== "image") { - continue; - } - - if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/start", - detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`, - }); - } - - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: dependencies.attachmentsDir, - attachment, + if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`, }); - if (!attachmentPath) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/start", - detail: `Invalid attachment id '${attachment.id}'.`, - }); - } - - const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/start", - detail: toMessage(cause, "Failed to read attachment file."), - cause, - }), - ), - ); - - sdkContent.push( - buildClaudeImageContentBlock({ - mimeType: attachment.mimeType, - bytes, - }), - ); } - return buildUserMessage({ sdkContent }); - }); -} + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: dependencies.attachmentsDir, + attachment, + }); + if (!attachmentPath) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: `Invalid attachment id '${attachment.id}'.`, + }); + } + + const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/start", + detail: toMessage(cause, "Failed to read attachment file."), + cause, + }), + ), + ); + + sdkContent.push( + buildClaudeImageContentBlock({ + mimeType: attachment.mimeType, + bytes, + }), + ); + } + + return buildUserMessage({ sdkContent }); +}); function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus { if (result.subtype === "success") { @@ -1017,2055 +1020,2029 @@ function sdkNativeItemId(message: SDKMessage): string | undefined { return undefined; } -function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const serverConfig = yield* ServerConfig; - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { - stream: "native", - }) - : undefined); +const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( + options?: ClaudeAdapterLiveOptions, +) { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* ServerConfig; + const nativeEventLogger = + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { + stream: "native", + }) + : undefined); - const createQuery = - options?.createQuery ?? - ((input: { - readonly prompt: AsyncIterable; - readonly options: ClaudeQueryOptions; - }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime); + const createQuery = + options?.createQuery ?? + ((input: { + readonly prompt: AsyncIterable; + readonly options: ClaudeQueryOptions; + }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime); - const sessions = new Map(); - const runtimeEventQueue = yield* Queue.unbounded(); - const serverSettingsService = yield* ServerSettingsService; + const sessions = new Map(); + const runtimeEventQueue = yield* Queue.unbounded(); + const serverSettingsService = yield* ServerSettingsService; - const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id)); - const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); + const nowIso = Effect.map(DateTime.now, DateTime.formatIso); + const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id)); + const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso }); - const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid); + const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => + Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid); - const logNativeSdkMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (!nativeEventLogger) { - return; - } + const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (!nativeEventLogger) { + return; + } - const observedAt = new Date().toISOString(); - const itemId = sdkNativeItemId(message); + const observedAt = new Date().toISOString(); + const itemId = sdkNativeItemId(message); - yield* nativeEventLogger.write( - { - observedAt, - event: { - id: - "uuid" in message && typeof message.uuid === "string" - ? message.uuid - : crypto.randomUUID(), - kind: "notification", - provider: PROVIDER, - createdAt: observedAt, - method: sdkNativeMethod(message), - ...(typeof message.session_id === "string" - ? { providerThreadId: message.session_id } - : {}), - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}), - payload: message, - }, - }, - context.session.threadId, - ); - }); - - const snapshotThread = ( - context: ClaudeSessionContext, - ): Effect.Effect< + yield* nativeEventLogger.write( { - threadId: ThreadId; - turns: ReadonlyArray<{ - id: TurnId; - items: ReadonlyArray; - }>; - }, - ProviderAdapterValidationError - > => - Effect.gen(function* () { - const threadId = context.session.threadId; - if (!threadId) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "readThread", - issue: "Session thread id is not initialized yet.", - }); - } - return { - threadId, - turns: context.turns.map((turn) => ({ - id: turn.id, - items: [...turn.items], - })), - }; - }); - - const updateResumeCursor = (context: ClaudeSessionContext): Effect.Effect => - Effect.gen(function* () { - const threadId = context.session.threadId; - if (!threadId) return; - - const resumeCursor = { - threadId, - ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}), - ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}), - turnCount: context.turns.length, - }; - - context.session = { - ...context.session, - resumeCursor, - updatedAt: yield* nowIso, - }; - }); - - const ensureAssistantTextBlock = ( - context: ClaudeSessionContext, - blockIndex: number, - options?: { - readonly fallbackText?: string; - readonly streamClosed?: boolean; - }, - ): Effect.Effect< - | { - readonly blockIndex: number; - readonly block: AssistantTextBlockState; - } - | undefined - > => - Effect.gen(function* () { - const turnState = context.turnState; - if (!turnState) { - return undefined; - } - - const existing = turnState.assistantTextBlocks.get(blockIndex); - if (existing && !existing.completionEmitted) { - if (existing.fallbackText.length === 0 && options?.fallbackText) { - existing.fallbackText = options.fallbackText; - } - if (options?.streamClosed) { - existing.streamClosed = true; - } - return { blockIndex, block: existing }; - } - - const block: AssistantTextBlockState = { - itemId: yield* Random.nextUUIDv4, - blockIndex, - emittedTextDelta: false, - fallbackText: options?.fallbackText ?? "", - streamClosed: options?.streamClosed ?? false, - completionEmitted: false, - }; - turnState.assistantTextBlocks.set(blockIndex, block); - turnState.assistantTextBlockOrder.push(block); - return { blockIndex, block }; - }); - - const createSyntheticAssistantTextBlock = ( - context: ClaudeSessionContext, - fallbackText: string, - ): Effect.Effect< - | { - readonly blockIndex: number; - readonly block: AssistantTextBlockState; - } - | undefined - > => - Effect.gen(function* () { - const turnState = context.turnState; - if (!turnState) { - return undefined; - } - - const blockIndex = turnState.nextSyntheticAssistantBlockIndex; - turnState.nextSyntheticAssistantBlockIndex -= 1; - return yield* ensureAssistantTextBlock(context, blockIndex, { - fallbackText, - streamClosed: true, - }); - }); - - const completeAssistantTextBlock = ( - context: ClaudeSessionContext, - block: AssistantTextBlockState, - options?: { - readonly force?: boolean; - readonly rawMethod?: string; - readonly rawPayload?: unknown; - }, - ): Effect.Effect => - Effect.gen(function* () { - const turnState = context.turnState; - if (!turnState || block.completionEmitted) { - return; - } - - if (!options?.force && !block.streamClosed) { - return; - } - - if (!block.emittedTextDelta && block.fallbackText.length > 0) { - const deltaStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "content.delta", - eventId: deltaStamp.eventId, - provider: PROVIDER, - createdAt: deltaStamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, - itemId: asRuntimeItemId(block.itemId), - payload: { - streamKind: "assistant_text", - delta: block.fallbackText, - }, - providerRefs: nativeProviderRefs(context), - ...(options?.rawMethod || options?.rawPayload - ? { - raw: { - source: "claude.sdk.message" as const, - ...(options.rawMethod ? { method: options.rawMethod } : {}), - payload: options?.rawPayload, - }, - } - : {}), - }); - } - - block.completionEmitted = true; - if (turnState.assistantTextBlocks.get(block.blockIndex) === block) { - turnState.assistantTextBlocks.delete(block.blockIndex); - } - - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.completed", - eventId: stamp.eventId, + observedAt, + event: { + id: + "uuid" in message && typeof message.uuid === "string" + ? message.uuid + : crypto.randomUUID(), + kind: "notification", provider: PROVIDER, - createdAt: stamp.createdAt, - itemId: asRuntimeItemId(block.itemId), - threadId: context.session.threadId, - turnId: turnState.turnId, - payload: { - itemType: "assistant_message", - status: "completed", - title: "Assistant message", - ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}), - }, - providerRefs: nativeProviderRefs(context), - ...(options?.rawMethod || options?.rawPayload - ? { - raw: { - source: "claude.sdk.message" as const, - ...(options.rawMethod ? { method: options.rawMethod } : {}), - payload: options?.rawPayload, - }, - } + createdAt: observedAt, + method: sdkNativeMethod(message), + ...(typeof message.session_id === "string" + ? { providerThreadId: message.session_id } : {}), - }); - }); - - const backfillAssistantTextBlocksFromSnapshot = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - const turnState = context.turnState; - if (!turnState) { - return; - } - - const snapshotTextBlocks = extractAssistantTextBlocks(message); - if (snapshotTextBlocks.length === 0) { - return; - } - - const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({ - blockIndex: block.blockIndex, - block, - })); - - for (const [position, text] of snapshotTextBlocks.entries()) { - const existingEntry = orderedBlocks[position]; - const entry = - existingEntry ?? - (yield* createSyntheticAssistantTextBlock(context, text).pipe( - Effect.map((created) => { - if (!created) { - return undefined; - } - orderedBlocks.push(created); - return created; - }), - )); - if (!entry) { - continue; - } - - if (entry.block.fallbackText.length === 0) { - entry.block.fallbackText = text; - } - - if (entry.block.streamClosed && !entry.block.completionEmitted) { - yield* completeAssistantTextBlock(context, entry.block, { - rawMethod: "claude/assistant", - rawPayload: message, - }); - } - } - }); - - const ensureThreadId = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (typeof message.session_id !== "string" || message.session_id.length === 0) { - return; - } - const nextThreadId = message.session_id; - context.resumeSessionId = message.session_id; - yield* updateResumeCursor(context); - - if (context.lastThreadStartedId !== nextThreadId) { - context.lastThreadStartedId = nextThreadId; - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "thread.started", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - payload: { - providerThreadId: nextThreadId, - }, - providerRefs: {}, - raw: { - source: "claude.sdk.message", - method: "claude/thread/started", - payload: { - session_id: message.session_id, - }, - }, - }); - } - }); - - const emitRuntimeError = ( - context: ClaudeSessionContext, - message: string, - cause?: unknown, - ): Effect.Effect => - Effect.gen(function* () { - if (cause !== undefined) { - void cause; - } - const turnState = context.turnState; - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "runtime.error", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), - payload: { - message, - class: "provider_error", - ...(cause !== undefined ? { detail: cause } : {}), - }, - providerRefs: nativeProviderRefs(context), - }); - }); - - const emitRuntimeWarning = ( - context: ClaudeSessionContext, - message: string, - detail?: unknown, - ): Effect.Effect => - Effect.gen(function* () { - const turnState = context.turnState; - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "runtime.warning", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), - payload: { - message, - ...(detail !== undefined ? { detail } : {}), - }, - providerRefs: nativeProviderRefs(context), - }); - }); - - const emitProposedPlanCompleted = ( - context: ClaudeSessionContext, - input: { - readonly planMarkdown: string; - readonly toolUseId?: string | undefined; - readonly rawSource: "claude.sdk.message" | "claude.sdk.permission"; - readonly rawMethod: string; - readonly rawPayload: unknown; + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}), + payload: message, + }, }, - ): Effect.Effect => - Effect.gen(function* () { - const turnState = context.turnState; - const planMarkdown = input.planMarkdown.trim(); - if (!turnState || planMarkdown.length === 0) { - return; - } + context.session.threadId, + ); + }); - const captureKey = exitPlanCaptureKey({ - toolUseId: input.toolUseId, - planMarkdown, - }); - if (turnState.capturedProposedPlanKeys.has(captureKey)) { - return; - } - turnState.capturedProposedPlanKeys.add(captureKey); - - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.proposed.completed", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, - payload: { - planMarkdown, - }, - providerRefs: nativeProviderRefs(context, { - providerItemId: input.toolUseId, - }), - raw: { - source: input.rawSource, - method: input.rawMethod, - payload: input.rawPayload, - }, - }); + const snapshotThread = Effect.fn("snapshotThread")(function* (context: ClaudeSessionContext) { + const threadId = context.session.threadId; + if (!threadId) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "readThread", + issue: "Session thread id is not initialized yet.", }); + } + return { + threadId, + turns: context.turns.map((turn) => ({ + id: turn.id, + items: [...turn.items], + })), + }; + }); - const completeTurn = ( - context: ClaudeSessionContext, - status: ProviderRuntimeTurnStatus, - errorMessage?: string, - result?: SDKResultMessage, - ): Effect.Effect => - Effect.gen(function* () { - const resultUsage = - result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined; - const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage); - if (resultContextWindow !== undefined) { - context.lastKnownContextWindow = resultContextWindow; - } + const updateResumeCursor = Effect.fn("updateResumeCursor")(function* ( + context: ClaudeSessionContext, + ) { + const threadId = context.session.threadId; + if (!threadId) return; - // The SDK result.usage contains *accumulated* totals across all API calls - // (input_tokens, cache_read_input_tokens, etc. summed over every request). - // This does NOT represent the current context window size. - // Instead, use the last known context-window-accurate usage from task_progress - // events and treat the accumulated total as totalProcessedTokens. - const accumulatedSnapshot = normalizeClaudeTokenUsage( - resultUsage, - resultContextWindow ?? context.lastKnownContextWindow, - ); - const lastGoodUsage = context.lastKnownTokenUsage; - const maxTokens = resultContextWindow ?? context.lastKnownContextWindow; - const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage + const resumeCursor = { + threadId, + ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}), + ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}), + turnCount: context.turns.length, + }; + + context.session = { + ...context.session, + resumeCursor, + updatedAt: yield* nowIso, + }; + }); + + const ensureAssistantTextBlock = Effect.fn("ensureAssistantTextBlock")(function* ( + context: ClaudeSessionContext, + blockIndex: number, + options?: { + readonly fallbackText?: string; + readonly streamClosed?: boolean; + }, + ) { + const turnState = context.turnState; + if (!turnState) { + return undefined; + } + + const existing = turnState.assistantTextBlocks.get(blockIndex); + if (existing && !existing.completionEmitted) { + if (existing.fallbackText.length === 0 && options?.fallbackText) { + existing.fallbackText = options.fallbackText; + } + if (options?.streamClosed) { + existing.streamClosed = true; + } + return { blockIndex, block: existing }; + } + + const block: AssistantTextBlockState = { + itemId: yield* Random.nextUUIDv4, + blockIndex, + emittedTextDelta: false, + fallbackText: options?.fallbackText ?? "", + streamClosed: options?.streamClosed ?? false, + completionEmitted: false, + }; + turnState.assistantTextBlocks.set(blockIndex, block); + turnState.assistantTextBlockOrder.push(block); + return { blockIndex, block }; + }); + + const createSyntheticAssistantTextBlock = Effect.fn("createSyntheticAssistantTextBlock")( + function* (context: ClaudeSessionContext, fallbackText: string) { + const turnState = context.turnState; + if (!turnState) { + return undefined; + } + + const blockIndex = turnState.nextSyntheticAssistantBlockIndex; + turnState.nextSyntheticAssistantBlockIndex -= 1; + return yield* ensureAssistantTextBlock(context, blockIndex, { + fallbackText, + streamClosed: true, + }); + }, + ); + + const completeAssistantTextBlock = Effect.fn("completeAssistantTextBlock")(function* ( + context: ClaudeSessionContext, + block: AssistantTextBlockState, + options?: { + readonly force?: boolean; + readonly rawMethod?: string; + readonly rawPayload?: unknown; + }, + ) { + const turnState = context.turnState; + if (!turnState || block.completionEmitted) { + return; + } + + if (!options?.force && !block.streamClosed) { + return; + } + + if (!block.emittedTextDelta && block.fallbackText.length > 0) { + const deltaStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: deltaStamp.eventId, + provider: PROVIDER, + createdAt: deltaStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + itemId: asRuntimeItemId(block.itemId), + payload: { + streamKind: "assistant_text", + delta: block.fallbackText, + }, + providerRefs: nativeProviderRefs(context), + ...(options?.rawMethod || options?.rawPayload ? { - ...lastGoodUsage, - ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 - ? { maxTokens } - : {}), - ...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens - ? { totalProcessedTokens: accumulatedSnapshot.usedTokens } - : {}), - } - : accumulatedSnapshot; - - const turnState = context.turnState; - if (!turnState) { - if (usageSnapshot) { - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "thread.token-usage.updated", - eventId: usageStamp.eventId, - provider: PROVIDER, - createdAt: usageStamp.createdAt, - threadId: context.session.threadId, - payload: { - usage: usageSnapshot, + raw: { + source: "claude.sdk.message" as const, + ...(options.rawMethod ? { method: options.rawMethod } : {}), + payload: options?.rawPayload, }, - providerRefs: {}, - }); - } + } + : {}), + }); + } - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.completed", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - payload: { - state: status, - ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), - ...(usageSnapshot ? { usage: usageSnapshot } : {}), - ...(typeof result?.total_cost_usd === "number" - ? { totalCostUsd: result.total_cost_usd } - : {}), - ...(errorMessage ? { errorMessage } : {}), - }, - providerRefs: {}, - }); - return; - } + block.completionEmitted = true; + if (turnState.assistantTextBlocks.get(block.blockIndex) === block) { + turnState.assistantTextBlocks.delete(block.blockIndex); + } - for (const [index, tool] of context.inFlightTools.entries()) { - const toolStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.completed", - eventId: toolStamp.eventId, - provider: PROVIDER, - createdAt: toolStamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, - itemId: asRuntimeItemId(tool.itemId), - payload: { - itemType: tool.itemType, - status: status === "completed" ? "completed" : "failed", - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), - ...(canonicalToolLifecycleData({ - itemType: tool.itemType, - toolName: tool.toolName, - input: tool.input, - }) - ? { - data: canonicalToolLifecycleData({ - itemType: tool.itemType, - toolName: tool.toolName, - input: tool.input, - }), - } - : {}), - }, - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + itemId: asRuntimeItemId(block.itemId), + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + itemType: "assistant_message", + status: "completed", + title: "Assistant message", + ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}), + }, + providerRefs: nativeProviderRefs(context), + ...(options?.rawMethod || options?.rawPayload + ? { raw: { - source: "claude.sdk.message", - method: "claude/result", - payload: result ?? { status }, + source: "claude.sdk.message" as const, + ...(options.rawMethod ? { method: options.rawMethod } : {}), + payload: options?.rawPayload, }, - }); - context.inFlightTools.delete(index); - } - // Clear any remaining stale entries (e.g. from interrupted content blocks) - context.inFlightTools.clear(); + } + : {}), + }); + }); - for (const block of turnState.assistantTextBlockOrder) { - yield* completeAssistantTextBlock(context, block, { - force: true, - rawMethod: "claude/result", - rawPayload: result ?? { status }, - }); - } + const backfillAssistantTextBlocksFromSnapshot = Effect.fn( + "backfillAssistantTextBlocksFromSnapshot", + )(function* (context: ClaudeSessionContext, message: SDKMessage) { + const turnState = context.turnState; + if (!turnState) { + return; + } - context.turns.push({ - id: turnState.turnId, - items: [...turnState.items], + const snapshotTextBlocks = extractAssistantTextBlocks(message); + if (snapshotTextBlocks.length === 0) { + return; + } + + const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({ + blockIndex: block.blockIndex, + block, + })); + + for (const [position, text] of snapshotTextBlocks.entries()) { + const existingEntry = orderedBlocks[position]; + const entry = + existingEntry ?? + (yield* createSyntheticAssistantTextBlock(context, text).pipe( + Effect.map((created) => { + if (!created) { + return undefined; + } + orderedBlocks.push(created); + return created; + }), + )); + if (!entry) { + continue; + } + + if (entry.block.fallbackText.length === 0) { + entry.block.fallbackText = text; + } + + if (entry.block.streamClosed && !entry.block.completionEmitted) { + yield* completeAssistantTextBlock(context, entry.block, { + rawMethod: "claude/assistant", + rawPayload: message, }); + } + } + }); - if (usageSnapshot) { - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "thread.token-usage.updated", - eventId: usageStamp.eventId, - provider: PROVIDER, - createdAt: usageStamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, - payload: { - usage: usageSnapshot, - }, - providerRefs: nativeProviderRefs(context), - }); - } + const ensureThreadId = Effect.fn("ensureThreadId")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (typeof message.session_id !== "string" || message.session_id.length === 0) { + return; + } + const nextThreadId = message.session_id; + context.resumeSessionId = message.session_id; + yield* updateResumeCursor(context); - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.completed", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - turnId: turnState.turnId, + if (context.lastThreadStartedId !== nextThreadId) { + context.lastThreadStartedId = nextThreadId; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.started", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + providerThreadId: nextThreadId, + }, + providerRefs: {}, + raw: { + source: "claude.sdk.message", + method: "claude/thread/started", payload: { - state: status, - ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), - ...(usageSnapshot ? { usage: usageSnapshot } : {}), - ...(typeof result?.total_cost_usd === "number" - ? { totalCostUsd: result.total_cost_usd } - : {}), - ...(errorMessage ? { errorMessage } : {}), + session_id: message.session_id, }, - providerRefs: nativeProviderRefs(context), + }, + }); + } + }); + + const emitRuntimeError = Effect.fn("emitRuntimeError")(function* ( + context: ClaudeSessionContext, + message: string, + cause?: unknown, + ) { + if (cause !== undefined) { + void cause; + } + const turnState = context.turnState; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "runtime.error", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), + payload: { + message, + class: "provider_error", + ...(cause !== undefined ? { detail: cause } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + }); + + const emitRuntimeWarning = Effect.fn("emitRuntimeWarning")(function* ( + context: ClaudeSessionContext, + message: string, + detail?: unknown, + ) { + const turnState = context.turnState; + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "runtime.warning", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}), + payload: { + message, + ...(detail !== undefined ? { detail } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + }); + + const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* ( + context: ClaudeSessionContext, + input: { + readonly planMarkdown: string; + readonly toolUseId?: string | undefined; + readonly rawSource: "claude.sdk.message" | "claude.sdk.permission"; + readonly rawMethod: string; + readonly rawPayload: unknown; + }, + ) { + const turnState = context.turnState; + const planMarkdown = input.planMarkdown.trim(); + if (!turnState || planMarkdown.length === 0) { + return; + } + + const captureKey = exitPlanCaptureKey({ + toolUseId: input.toolUseId, + planMarkdown, + }); + if (turnState.capturedProposedPlanKeys.has(captureKey)) { + return; + } + turnState.capturedProposedPlanKeys.add(captureKey); + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.proposed.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + planMarkdown, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: input.toolUseId, + }), + raw: { + source: input.rawSource, + method: input.rawMethod, + payload: input.rawPayload, + }, + }); + }); + + const completeTurn = Effect.fn("completeTurn")(function* ( + context: ClaudeSessionContext, + status: ProviderRuntimeTurnStatus, + errorMessage?: string, + result?: SDKResultMessage, + ) { + const resultUsage = + result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined; + const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage); + if (resultContextWindow !== undefined) { + context.lastKnownContextWindow = resultContextWindow; + } + + // The SDK result.usage contains *accumulated* totals across all API calls + // (input_tokens, cache_read_input_tokens, etc. summed over every request). + // This does NOT represent the current context window size. + // Instead, use the last known context-window-accurate usage from task_progress + // events and treat the accumulated total as totalProcessedTokens. + const accumulatedSnapshot = normalizeClaudeTokenUsage( + resultUsage, + resultContextWindow ?? context.lastKnownContextWindow, + ); + const lastGoodUsage = context.lastKnownTokenUsage; + const maxTokens = resultContextWindow ?? context.lastKnownContextWindow; + const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage + ? { + ...lastGoodUsage, + ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0 + ? { maxTokens } + : {}), + ...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens + ? { totalProcessedTokens: accumulatedSnapshot.usedTokens } + : {}), + } + : accumulatedSnapshot; + + const turnState = context.turnState; + if (!turnState) { + if (usageSnapshot) { + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.token-usage.updated", + eventId: usageStamp.eventId, + provider: PROVIDER, + createdAt: usageStamp.createdAt, + threadId: context.session.threadId, + payload: { + usage: usageSnapshot, + }, + providerRefs: {}, }); + } - const updatedAt = yield* nowIso; - context.turnState = undefined; - context.session = { - ...context.session, - status: "ready", - activeTurnId: undefined, - updatedAt, - ...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}), - }; - yield* updateResumeCursor(context); + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + state: status, + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), + ...(usageSnapshot ? { usage: usageSnapshot } : {}), + ...(typeof result?.total_cost_usd === "number" + ? { totalCostUsd: result.total_cost_usd } + : {}), + ...(errorMessage ? { errorMessage } : {}), + }, + providerRefs: {}, }); + return; + } - const handleStreamEvent = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (message.type !== "stream_event") { - return; - } - - const { event } = message; - - if (event.type === "content_block_delta") { - if ( - (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") && - context.turnState - ) { - const deltaText = - event.delta.type === "text_delta" - ? event.delta.text - : typeof event.delta.thinking === "string" - ? event.delta.thinking - : ""; - if (deltaText.length === 0) { - return; - } - const streamKind = streamKindFromDeltaType(event.delta.type); - const assistantBlockEntry = - event.delta.type === "text_delta" - ? yield* ensureAssistantTextBlock(context, event.index) - : context.turnState.assistantTextBlocks.get(event.index) - ? { - blockIndex: event.index, - block: context.turnState.assistantTextBlocks.get( - event.index, - ) as AssistantTextBlockState, - } - : undefined; - if (assistantBlockEntry?.block && event.delta.type === "text_delta") { - assistantBlockEntry.block.emittedTextDelta = true; - } - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "content.delta", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - turnId: context.turnState.turnId, - ...(assistantBlockEntry?.block - ? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) } - : {}), - payload: { - streamKind, - delta: deltaText, - }, - providerRefs: nativeProviderRefs(context), - raw: { - source: "claude.sdk.message", - method: "claude/stream_event/content_block_delta", - payload: message, - }, - }); - return; - } - - if (event.delta.type === "input_json_delta") { - const tool = context.inFlightTools.get(event.index); - if (!tool || typeof event.delta.partial_json !== "string") { - return; - } - - const partialInputJson = tool.partialInputJson + event.delta.partial_json; - const parsedInput = tryParseJsonRecord(partialInputJson); - const detail = parsedInput - ? summarizeToolRequest(tool.toolName, parsedInput) - : tool.detail; - let nextTool: ToolInFlight = { - ...tool, - partialInputJson, - ...(parsedInput ? { input: parsedInput } : {}), - ...(detail ? { detail } : {}), - }; - - const nextFingerprint = - parsedInput && Object.keys(parsedInput).length > 0 - ? toolInputFingerprint(parsedInput) - : undefined; - context.inFlightTools.set(event.index, nextTool); - - if ( - !parsedInput || - !nextFingerprint || - tool.lastEmittedInputFingerprint === nextFingerprint - ) { - return; - } - - nextTool = { - ...nextTool, - lastEmittedInputFingerprint: nextFingerprint, - }; - context.inFlightTools.set(event.index, nextTool); - - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.updated", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - itemId: asRuntimeItemId(nextTool.itemId), - payload: { - itemType: nextTool.itemType, - status: "inProgress", - title: nextTool.title, - ...(nextTool.detail ? { detail: nextTool.detail } : {}), - ...(canonicalToolLifecycleData({ - itemType: nextTool.itemType, - toolName: nextTool.toolName, - input: nextTool.input, - }) - ? { - data: canonicalToolLifecycleData({ - itemType: nextTool.itemType, - toolName: nextTool.toolName, - input: nextTool.input, - }), - } - : {}), - }, - providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }), - raw: { - source: "claude.sdk.message", - method: "claude/stream_event/content_block_delta/input_json_delta", - payload: message, - }, - }); - } - return; - } - - if (event.type === "content_block_start") { - const { index, content_block: block } = event; - if (block.type === "text") { - yield* ensureAssistantTextBlock(context, index, { - fallbackText: extractContentBlockText(block), - }); - return; - } - if ( - block.type !== "tool_use" && - block.type !== "server_tool_use" && - block.type !== "mcp_tool_use" - ) { - return; - } - - const toolName = block.name; - const itemType = classifyToolItemType(toolName); - const toolInput = - typeof block.input === "object" && block.input !== null - ? (block.input as Record) - : {}; - const itemId = block.id; - const detail = summarizeToolRequest(toolName, toolInput); - const inputFingerprint = - Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined; - - const tool: ToolInFlight = { - itemId, - itemType, - toolName, - title: titleForTool(itemType), - detail, - input: toolInput, - partialInputJson: "", - ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}), - }; - context.inFlightTools.set(index, tool); - - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.started", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - itemId: asRuntimeItemId(tool.itemId), - payload: { - itemType: tool.itemType, - status: "inProgress", - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), - ...(canonicalToolLifecycleData({ - itemType: tool.itemType, - toolName: tool.toolName, - input: toolInput, - }) - ? { - data: canonicalToolLifecycleData({ - itemType: tool.itemType, - toolName: tool.toolName, - input: toolInput, - }), - } - : {}), - }, - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), - raw: { - source: "claude.sdk.message", - method: "claude/stream_event/content_block_start", - payload: message, - }, - }); - return; - } - - if (event.type === "content_block_stop") { - const { index } = event; - const assistantBlock = context.turnState?.assistantTextBlocks.get(index); - if (assistantBlock) { - assistantBlock.streamClosed = true; - yield* completeAssistantTextBlock(context, assistantBlock, { - rawMethod: "claude/stream_event/content_block_stop", - rawPayload: message, - }); - return; - } - const tool = context.inFlightTools.get(index); - if (!tool) { - return; - } - } - }); - - const handleUserMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (message.type !== "user") { - return; - } - - if (context.turnState) { - context.turnState.items.push(message.message); - } - - for (const toolResult of toolResultBlocksFromUserMessage(message)) { - const toolEntry = Array.from(context.inFlightTools.entries()).find( - ([, tool]) => tool.itemId === toolResult.toolUseId, - ); - if (!toolEntry) { - continue; - } - - const [index, tool] = toolEntry; - const itemStatus = toolResult.isError ? "failed" : "completed"; - const toolData = canonicalToolLifecycleData({ + for (const [index, tool] of context.inFlightTools.entries()) { + const toolStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: toolStamp.eventId, + provider: PROVIDER, + createdAt: toolStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: status === "completed" ? "completed" : "failed", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + ...(canonicalToolLifecycleData({ itemType: tool.itemType, toolName: tool.toolName, input: tool.input, - result: toolResult.block, - }); - - const updatedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.updated", - eventId: updatedStamp.eventId, - provider: PROVIDER, - createdAt: updatedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - itemId: asRuntimeItemId(tool.itemId), - payload: { - itemType: tool.itemType, - status: toolResult.isError ? "failed" : "inProgress", - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), - ...(toolData ? { data: toolData } : {}), - }, - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), - raw: { - source: "claude.sdk.message", - method: "claude/user", - payload: message, - }, - }); - - const streamKind = toolResultStreamKind(tool.itemType); - if (streamKind && toolResult.text.length > 0 && context.turnState) { - const deltaStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "content.delta", - eventId: deltaStamp.eventId, - provider: PROVIDER, - createdAt: deltaStamp.createdAt, - threadId: context.session.threadId, - turnId: context.turnState.turnId, - itemId: asRuntimeItemId(tool.itemId), - payload: { - streamKind, - delta: toolResult.text, - }, - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), - raw: { - source: "claude.sdk.message", - method: "claude/user", - payload: message, - }, - }); - } - - const completedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "item.completed", - eventId: completedStamp.eventId, - provider: PROVIDER, - createdAt: completedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - itemId: asRuntimeItemId(tool.itemId), - payload: { - itemType: tool.itemType, - status: itemStatus, - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), - ...(toolData ? { data: toolData } : {}), - }, - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), - raw: { - source: "claude.sdk.message", - method: "claude/user", - payload: message, - }, - }); - - context.inFlightTools.delete(index); - } + }) + ? { + data: canonicalToolLifecycleData({ + itemType: tool.itemType, + toolName: tool.toolName, + input: tool.input, + }), + } + : {}), + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/result", + payload: result ?? { status }, + }, }); + context.inFlightTools.delete(index); + } + // Clear any remaining stale entries (e.g. from interrupted content blocks) + context.inFlightTools.clear(); - const handleAssistantMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (message.type !== "assistant") { + for (const block of turnState.assistantTextBlockOrder) { + yield* completeAssistantTextBlock(context, block, { + force: true, + rawMethod: "claude/result", + rawPayload: result ?? { status }, + }); + } + + context.turns.push({ + id: turnState.turnId, + items: [...turnState.items], + }); + + if (usageSnapshot) { + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "thread.token-usage.updated", + eventId: usageStamp.eventId, + provider: PROVIDER, + createdAt: usageStamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + usage: usageSnapshot, + }, + providerRefs: nativeProviderRefs(context), + }); + } + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.completed", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: turnState.turnId, + payload: { + state: status, + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}), + ...(usageSnapshot ? { usage: usageSnapshot } : {}), + ...(typeof result?.total_cost_usd === "number" + ? { totalCostUsd: result.total_cost_usd } + : {}), + ...(errorMessage ? { errorMessage } : {}), + }, + providerRefs: nativeProviderRefs(context), + }); + + const updatedAt = yield* nowIso; + context.turnState = undefined; + context.session = { + ...context.session, + status: "ready", + activeTurnId: undefined, + updatedAt, + ...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}), + }; + yield* updateResumeCursor(context); + }); + + const handleStreamEvent = Effect.fn("handleStreamEvent")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "stream_event") { + return; + } + + const { event } = message; + + if (event.type === "content_block_delta") { + if ( + (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") && + context.turnState + ) { + const deltaText = + event.delta.type === "text_delta" + ? event.delta.text + : typeof event.delta.thinking === "string" + ? event.delta.thinking + : ""; + if (deltaText.length === 0) { + return; + } + const streamKind = streamKindFromDeltaType(event.delta.type); + const assistantBlockEntry = + event.delta.type === "text_delta" + ? yield* ensureAssistantTextBlock(context, event.index) + : context.turnState.assistantTextBlocks.get(event.index) + ? { + blockIndex: event.index, + block: context.turnState.assistantTextBlocks.get( + event.index, + ) as AssistantTextBlockState, + } + : undefined; + if (assistantBlockEntry?.block && event.delta.type === "text_delta") { + assistantBlockEntry.block.emittedTextDelta = true; + } + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + turnId: context.turnState.turnId, + ...(assistantBlockEntry?.block + ? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) } + : {}), + payload: { + streamKind, + delta: deltaText, + }, + providerRefs: nativeProviderRefs(context), + raw: { + source: "claude.sdk.message", + method: "claude/stream_event/content_block_delta", + payload: message, + }, + }); + return; + } + + if (event.delta.type === "input_json_delta") { + const tool = context.inFlightTools.get(event.index); + if (!tool || typeof event.delta.partial_json !== "string") { return; } - // Auto-start a synthetic turn for assistant messages that arrive without - // an active turn (e.g., background agent/subagent responses between user prompts). - if (!context.turnState) { - const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); - const startedAt = yield* nowIso; - context.turnState = { - turnId, - startedAt, - items: [], - assistantTextBlocks: new Map(), - assistantTextBlockOrder: [], - capturedProposedPlanKeys: new Set(), - nextSyntheticAssistantBlockIndex: -1, - }; - context.session = { - ...context.session, - status: "running", - activeTurnId: turnId, - updatedAt: startedAt, - }; - const turnStartedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "turn.started", - eventId: turnStartedStamp.eventId, - provider: PROVIDER, - createdAt: turnStartedStamp.createdAt, - threadId: context.session.threadId, - turnId, - payload: {}, - providerRefs: { - ...nativeProviderRefs(context), - providerTurnId: turnId, - }, - raw: { - source: "claude.sdk.message", - method: "claude/synthetic-turn-start", - payload: {}, - }, - }); - } + const partialInputJson = tool.partialInputJson + event.delta.partial_json; + const parsedInput = tryParseJsonRecord(partialInputJson); + const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail; + let nextTool: ToolInFlight = { + ...tool, + partialInputJson, + ...(parsedInput ? { input: parsedInput } : {}), + ...(detail ? { detail } : {}), + }; - const content = message.message?.content; - if (Array.isArray(content)) { - for (const block of content) { - if (!block || typeof block !== "object") { - continue; - } - const toolUse = block as { - type?: unknown; - id?: unknown; - name?: unknown; - input?: unknown; - }; - if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") { - continue; - } - const planMarkdown = extractExitPlanModePlan(toolUse.input); - if (!planMarkdown) { - continue; - } - yield* emitProposedPlanCompleted(context, { - planMarkdown, - toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined, - rawSource: "claude.sdk.message", - rawMethod: "claude/assistant", - rawPayload: message, - }); - } - } + const nextFingerprint = + parsedInput && Object.keys(parsedInput).length > 0 + ? toolInputFingerprint(parsedInput) + : undefined; + context.inFlightTools.set(event.index, nextTool); - if (context.turnState) { - context.turnState.items.push(message.message); - yield* backfillAssistantTextBlocksFromSnapshot(context, message); - } - - context.lastAssistantUuid = message.uuid; - yield* updateResumeCursor(context); - }); - - const handleResultMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (message.type !== "result") { + if ( + !parsedInput || + !nextFingerprint || + tool.lastEmittedInputFingerprint === nextFingerprint + ) { return; } - const status = turnStatusFromResult(message); - const errorMessage = message.subtype === "success" ? undefined : message.errors[0]; - - if (status === "failed") { - yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed."); - } - - yield* completeTurn(context, status, errorMessage, message); - }); - - const handleSystemMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - if (message.type !== "system") { - return; - } + nextTool = { + ...nextTool, + lastEmittedInputFingerprint: nextFingerprint, + }; + context.inFlightTools.set(event.index, nextTool); const stamp = yield* makeEventStamp(); - const base = { + yield* offerRuntimeEvent({ + type: "item.updated", eventId: stamp.eventId, provider: PROVIDER, createdAt: stamp.createdAt, threadId: context.session.threadId, ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - providerRefs: nativeProviderRefs(context), + itemId: asRuntimeItemId(nextTool.itemId), + payload: { + itemType: nextTool.itemType, + status: "inProgress", + title: nextTool.title, + ...(nextTool.detail ? { detail: nextTool.detail } : {}), + ...(canonicalToolLifecycleData({ + itemType: nextTool.itemType, + toolName: nextTool.toolName, + input: nextTool.input, + }) + ? { + data: canonicalToolLifecycleData({ + itemType: nextTool.itemType, + toolName: nextTool.toolName, + input: nextTool.input, + }), + } + : {}), + }, + providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }), raw: { - source: "claude.sdk.message" as const, - method: sdkNativeMethod(message), - messageType: `${message.type}:${message.subtype}`, + source: "claude.sdk.message", + method: "claude/stream_event/content_block_delta/input_json_delta", payload: message, }, - }; - - switch (message.subtype) { - case "status": - yield* offerRuntimeEvent({ - ...base, - type: "session.state.changed", - payload: { - state: message.status === "compacting" ? "waiting" : "running", - reason: `status:${message.status ?? "active"}`, - detail: message, - }, - }); - return; - case "compact_boundary": - yield* offerRuntimeEvent({ - ...base, - type: "thread.state.changed", - payload: { - state: "compacted", - detail: message, - }, - }); - return; - case "task_started": - yield* offerRuntimeEvent({ - ...base, - type: "task.started", - payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), - description: message.description, - ...(message.task_type ? { taskType: message.task_type } : {}), - }, - }); - return; - case "task_progress": { - const normalizedUsage = message.usage - ? normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow) - : undefined; - if (normalizedUsage) { - context.lastKnownTokenUsage = normalizedUsage; - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - ...base, - eventId: usageStamp.eventId, - createdAt: usageStamp.createdAt, - type: "thread.token-usage.updated", - payload: { - usage: normalizedUsage, - }, - }); - } - yield* offerRuntimeEvent({ - ...base, - type: "task.progress", - payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), - description: message.description, - ...(message.summary ? { summary: message.summary } : {}), - ...(normalizedUsage ? { usage: normalizedUsage } : {}), - ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}), - }, - }); - return; - } - case "task_notification": { - const normalizedUsage = message.usage - ? normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow) - : undefined; - if (normalizedUsage) { - context.lastKnownTokenUsage = normalizedUsage; - const usageStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - ...base, - eventId: usageStamp.eventId, - createdAt: usageStamp.createdAt, - type: "thread.token-usage.updated", - payload: { - usage: normalizedUsage, - }, - }); - } - yield* offerRuntimeEvent({ - ...base, - type: "task.completed", - payload: { - taskId: RuntimeTaskId.makeUnsafe(message.task_id), - status: message.status, - ...(message.summary ? { summary: message.summary } : {}), - ...(normalizedUsage ? { usage: normalizedUsage } : {}), - }, - }); - return; - } - default: - yield* emitRuntimeWarning( - context, - `Unhandled Claude system message subtype '${message.subtype}'.`, - message, - ); - return; - } - }); - - const handleSdkTelemetryMessage = ( - _context: ClaudeSessionContext, - _message: SDKMessage, - ): Effect.Effect => Effect.void; - - const handleSdkMessage = ( - context: ClaudeSessionContext, - message: SDKMessage, - ): Effect.Effect => - Effect.gen(function* () { - yield* logNativeSdkMessage(context, message); - yield* ensureThreadId(context, message); - - switch (message.type) { - case "stream_event": - yield* handleStreamEvent(context, message); - return; - case "user": - yield* handleUserMessage(context, message); - return; - case "assistant": - yield* handleAssistantMessage(context, message); - return; - case "result": - yield* handleResultMessage(context, message); - return; - case "system": - yield* handleSystemMessage(context, message); - return; - case "tool_progress": - case "tool_use_summary": - case "auth_status": - case "rate_limit_event": - yield* handleSdkTelemetryMessage(context, message); - return; - default: - yield* emitRuntimeWarning( - context, - `Unhandled Claude SDK message type '${message.type}'.`, - message, - ); - return; - } - }); - - const runSdkStream = (context: ClaudeSessionContext): Effect.Effect => - Stream.fromAsyncIterable(context.query, (cause) => - toError(cause, "Claude runtime stream failed."), - ).pipe( - Stream.takeWhile(() => !context.stopped), - Stream.runForEach((message) => handleSdkMessage(context, message)), - ); - - const handleStreamExit = ( - context: ClaudeSessionContext, - exit: Exit.Exit, - ): Effect.Effect => - Effect.gen(function* () { - if (context.stopped) { - return; - } - - if (Exit.isFailure(exit)) { - if (isClaudeInterruptedCause(exit.cause)) { - if (context.turnState) { - yield* completeTurn( - context, - "interrupted", - interruptionMessageFromClaudeCause(exit.cause), - ); - } - } else { - const message = messageFromClaudeStreamCause( - exit.cause, - "Claude runtime stream failed.", - ); - yield* emitRuntimeError(context, message, Cause.pretty(exit.cause)); - yield* completeTurn(context, "failed", message); - } - } else if (context.turnState) { - yield* completeTurn(context, "interrupted", "Claude runtime stream ended."); - } - - yield* stopSessionInternal(context, { - emitExitEvent: true, }); + } + return; + } + + if (event.type === "content_block_start") { + const { index, content_block: block } = event; + if (block.type === "text") { + yield* ensureAssistantTextBlock(context, index, { + fallbackText: extractContentBlockText(block), + }); + return; + } + if ( + block.type !== "tool_use" && + block.type !== "server_tool_use" && + block.type !== "mcp_tool_use" + ) { + return; + } + + const toolName = block.name; + const itemType = classifyToolItemType(toolName); + const toolInput = + typeof block.input === "object" && block.input !== null + ? (block.input as Record) + : {}; + const itemId = block.id; + const detail = summarizeToolRequest(toolName, toolInput); + const inputFingerprint = + Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined; + + const tool: ToolInFlight = { + itemId, + itemType, + toolName, + title: titleForTool(itemType), + detail, + input: toolInput, + partialInputJson: "", + ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}), + }; + context.inFlightTools.set(index, tool); + + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.started", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + ...(canonicalToolLifecycleData({ + itemType: tool.itemType, + toolName: tool.toolName, + input: toolInput, + }) + ? { + data: canonicalToolLifecycleData({ + itemType: tool.itemType, + toolName: tool.toolName, + input: toolInput, + }), + } + : {}), + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/stream_event/content_block_start", + payload: message, + }, + }); + return; + } + + if (event.type === "content_block_stop") { + const { index } = event; + const assistantBlock = context.turnState?.assistantTextBlocks.get(index); + if (assistantBlock) { + assistantBlock.streamClosed = true; + yield* completeAssistantTextBlock(context, assistantBlock, { + rawMethod: "claude/stream_event/content_block_stop", + rawPayload: message, + }); + return; + } + const tool = context.inFlightTools.get(index); + if (!tool) { + return; + } + } + }); + + const handleUserMessage = Effect.fn("handleUserMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "user") { + return; + } + + if (context.turnState) { + context.turnState.items.push(message.message); + } + + for (const toolResult of toolResultBlocksFromUserMessage(message)) { + const toolEntry = Array.from(context.inFlightTools.entries()).find( + ([, tool]) => tool.itemId === toolResult.toolUseId, + ); + if (!toolEntry) { + continue; + } + + const [index, tool] = toolEntry; + const itemStatus = toolResult.isError ? "failed" : "completed"; + const toolData = canonicalToolLifecycleData({ + itemType: tool.itemType, + toolName: tool.toolName, + input: tool.input, + result: toolResult.block, }); - const stopSessionInternal = ( - context: ClaudeSessionContext, - options?: { readonly emitExitEvent?: boolean }, - ): Effect.Effect => - Effect.gen(function* () { - if (context.stopped) return; + const updatedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.updated", + eventId: updatedStamp.eventId, + provider: PROVIDER, + createdAt: updatedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: toolResult.isError ? "failed" : "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + ...(toolData ? { data: toolData } : {}), + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); - context.stopped = true; + const streamKind = toolResultStreamKind(tool.itemType); + if (streamKind && toolResult.text.length > 0 && context.turnState) { + const deltaStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "content.delta", + eventId: deltaStamp.eventId, + provider: PROVIDER, + createdAt: deltaStamp.createdAt, + threadId: context.session.threadId, + turnId: context.turnState.turnId, + itemId: asRuntimeItemId(tool.itemId), + payload: { + streamKind, + delta: toolResult.text, + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); + } - for (const [requestId, pending] of context.pendingApprovals) { - yield* Deferred.succeed(pending.decision, "cancel"); - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "request.resolved", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - requestId: asRuntimeRequestId(requestId), - payload: { - requestType: pending.requestType, - decision: "cancel", - }, - providerRefs: nativeProviderRefs(context), - }); + const completedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "item.completed", + eventId: completedStamp.eventId, + provider: PROVIDER, + createdAt: completedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + itemId: asRuntimeItemId(tool.itemId), + payload: { + itemType: tool.itemType, + status: itemStatus, + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + ...(toolData ? { data: toolData } : {}), + }, + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }), + raw: { + source: "claude.sdk.message", + method: "claude/user", + payload: message, + }, + }); + + context.inFlightTools.delete(index); + } + }); + + const handleAssistantMessage = Effect.fn("handleAssistantMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "assistant") { + return; + } + + // Auto-start a synthetic turn for assistant messages that arrive without + // an active turn (e.g., background agent/subagent responses between user prompts). + if (!context.turnState) { + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); + const startedAt = yield* nowIso; + context.turnState = { + turnId, + startedAt, + items: [], + assistantTextBlocks: new Map(), + assistantTextBlockOrder: [], + capturedProposedPlanKeys: new Set(), + nextSyntheticAssistantBlockIndex: -1, + }; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt: startedAt, + }; + const turnStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.started", + eventId: turnStartedStamp.eventId, + provider: PROVIDER, + createdAt: turnStartedStamp.createdAt, + threadId: context.session.threadId, + turnId, + payload: {}, + providerRefs: { + ...nativeProviderRefs(context), + providerTurnId: turnId, + }, + raw: { + source: "claude.sdk.message", + method: "claude/synthetic-turn-start", + payload: {}, + }, + }); + } + + const content = message.message?.content; + if (Array.isArray(content)) { + for (const block of content) { + if (!block || typeof block !== "object") { + continue; } - context.pendingApprovals.clear(); - - if (context.turnState) { - yield* completeTurn(context, "interrupted", "Session stopped."); - } - - yield* Queue.shutdown(context.promptQueue); - - const streamFiber = context.streamFiber; - context.streamFiber = undefined; - if (streamFiber && streamFiber.pollUnsafe() === undefined) { - yield* Fiber.interrupt(streamFiber); - } - - // @effect-diagnostics-next-line tryCatchInEffectGen:off - try { - context.query.close(); - } catch (cause) { - yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause); - } - - const updatedAt = yield* nowIso; - context.session = { - ...context.session, - status: "closed", - activeTurnId: undefined, - updatedAt, + const toolUse = block as { + type?: unknown; + id?: unknown; + name?: unknown; + input?: unknown; }; - - if (options?.emitExitEvent !== false) { - const stamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "session.exited", - eventId: stamp.eventId, - provider: PROVIDER, - createdAt: stamp.createdAt, - threadId: context.session.threadId, - payload: { - reason: "Session stopped", - exitKind: "graceful", - }, - providerRefs: {}, - }); + if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") { + continue; } - - sessions.delete(context.session.threadId); - }); - - const requireSession = ( - threadId: ThreadId, - ): Effect.Effect => { - const context = sessions.get(threadId); - if (!context) { - return Effect.fail( - new ProviderAdapterSessionNotFoundError({ - provider: PROVIDER, - threadId, - }), - ); + const planMarkdown = extractExitPlanModePlan(toolUse.input); + if (!planMarkdown) { + continue; + } + yield* emitProposedPlanCompleted(context, { + planMarkdown, + toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined, + rawSource: "claude.sdk.message", + rawMethod: "claude/assistant", + rawPayload: message, + }); } - if (context.stopped || context.session.status === "closed") { - return Effect.fail( - new ProviderAdapterSessionClosedError({ - provider: PROVIDER, - threadId, - }), - ); - } - return Effect.succeed(context); + } + + if (context.turnState) { + context.turnState.items.push(message.message); + yield* backfillAssistantTextBlocksFromSnapshot(context, message); + } + + context.lastAssistantUuid = message.uuid; + yield* updateResumeCursor(context); + }); + + const handleResultMessage = Effect.fn("handleResultMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "result") { + return; + } + + const status = turnStatusFromResult(message); + const errorMessage = message.subtype === "success" ? undefined : message.errors[0]; + + if (status === "failed") { + yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed."); + } + + yield* completeTurn(context, status, errorMessage, message); + }); + + const handleSystemMessage = Effect.fn("handleSystemMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + if (message.type !== "system") { + return; + } + + const stamp = yield* makeEventStamp(); + const base = { + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + providerRefs: nativeProviderRefs(context), + raw: { + source: "claude.sdk.message" as const, + method: sdkNativeMethod(message), + messageType: `${message.type}:${message.subtype}`, + payload: message, + }, }; - const startSession: ClaudeAdapterShape["startSession"] = (input) => - Effect.gen(function* () { - if (input.provider !== undefined && input.provider !== PROVIDER) { - return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, - operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, - }); - } - - const startedAt = yield* nowIso; - const resumeState = readClaudeResumeState(input.resumeCursor); - const threadId = input.threadId; - const existingResumeSessionId = resumeState?.resume; - const newSessionId = - existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined; - const sessionId = existingResumeSessionId ?? newSessionId; - - const promptQueue = yield* Queue.unbounded(); - const prompt = Stream.fromQueue(promptQueue).pipe( - Stream.filter((item) => item.type === "message"), - Stream.map((item) => item.message), - Stream.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), - ), - Stream.toAsyncIterable, - ); - - const pendingApprovals = new Map(); - const pendingUserInputs = new Map(); - const inFlightTools = new Map(); - - const contextRef = yield* Ref.make(undefined); - - /** - * Handle AskUserQuestion tool calls by emitting a `user-input.requested` - * runtime event and waiting for the user to respond via `respondToUserInput`. - */ - const handleAskUserQuestion = ( - context: ClaudeSessionContext, - toolInput: Record, - callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string }, - ) => - Effect.gen(function* () { - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); - - // Parse questions from the SDK's AskUserQuestion input. - const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : []; - const questions: Array = rawQuestions.map( - (q: Record, idx: number) => ({ - id: typeof q.header === "string" ? q.header : `q-${idx}`, - header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`, - question: typeof q.question === "string" ? q.question : "", - options: Array.isArray(q.options) - ? q.options.map((opt: Record) => ({ - label: typeof opt.label === "string" ? opt.label : "", - description: typeof opt.description === "string" ? opt.description : "", - })) - : [], - multiSelect: typeof q.multiSelect === "boolean" ? q.multiSelect : false, - }), - ); - - const answersDeferred = yield* Deferred.make(); - let aborted = false; - const pendingInput: PendingUserInput = { - questions, - answers: answersDeferred, - }; - - // Emit user-input.requested so the UI can present the questions. - const requestedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "user-input.requested", - eventId: requestedStamp.eventId, - provider: PROVIDER, - createdAt: requestedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - requestId: asRuntimeRequestId(requestId), - payload: { questions }, - providerRefs: nativeProviderRefs(context, { - providerItemId: callbackOptions.toolUseID, - }), - raw: { - source: "claude.sdk.permission", - method: "canUseTool/AskUserQuestion", - payload: { toolName: "AskUserQuestion", input: toolInput }, - }, - }); - - pendingUserInputs.set(requestId, pendingInput); - - // Handle abort (e.g. turn interrupted while waiting for user input). - const onAbort = () => { - if (!pendingUserInputs.has(requestId)) { - return; - } - aborted = true; - pendingUserInputs.delete(requestId); - Effect.runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers)); - }; - callbackOptions.signal.addEventListener("abort", onAbort, { once: true }); - - // Block until the user provides answers. - const answers = yield* Deferred.await(answersDeferred); - pendingUserInputs.delete(requestId); - - // Emit user-input.resolved so the UI knows the interaction completed. - const resolvedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "user-input.resolved", - eventId: resolvedStamp.eventId, - provider: PROVIDER, - createdAt: resolvedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), - requestId: asRuntimeRequestId(requestId), - payload: { answers }, - providerRefs: nativeProviderRefs(context, { - providerItemId: callbackOptions.toolUseID, - }), - raw: { - source: "claude.sdk.permission", - method: "canUseTool/AskUserQuestion/resolved", - payload: { answers }, - }, - }); - - if (aborted) { - return { - behavior: "deny", - message: "User cancelled tool execution.", - } satisfies PermissionResult; - } - - // Return the answers to the SDK in the expected format: - // { questions: [...], answers: { questionText: selectedLabel } } - return { - behavior: "allow", - updatedInput: { - questions: toolInput.questions, - answers, - }, - } satisfies PermissionResult; - }); - - const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) => - Effect.runPromise( - Effect.gen(function* () { - const context = yield* Ref.get(contextRef); - if (!context) { - return { - behavior: "deny", - message: "Claude session context is unavailable.", - } satisfies PermissionResult; - } - - // Handle AskUserQuestion: surface clarifying questions to the - // user via the user-input runtime event channel, regardless of - // runtime mode (plan mode relies on this heavily). - if (toolName === "AskUserQuestion") { - return yield* handleAskUserQuestion(context, toolInput, callbackOptions); - } - - if (toolName === "ExitPlanMode") { - const planMarkdown = extractExitPlanModePlan(toolInput); - if (planMarkdown) { - yield* emitProposedPlanCompleted(context, { - planMarkdown, - toolUseId: callbackOptions.toolUseID, - rawSource: "claude.sdk.permission", - rawMethod: "canUseTool/ExitPlanMode", - rawPayload: { - toolName, - input: toolInput, - }, - }); - } - - return { - behavior: "deny", - message: - "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", - } satisfies PermissionResult; - } - - const runtimeMode = input.runtimeMode ?? "full-access"; - if (runtimeMode === "full-access") { - return { - behavior: "allow", - updatedInput: toolInput, - } satisfies PermissionResult; - } - - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); - const requestType = classifyRequestType(toolName); - const detail = summarizeToolRequest(toolName, toolInput); - const decisionDeferred = yield* Deferred.make(); - const pendingApproval: PendingApproval = { - requestType, - detail, - decision: decisionDeferred, - ...(callbackOptions.suggestions - ? { suggestions: callbackOptions.suggestions } - : {}), - }; - - const requestedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "request.opened", - eventId: requestedStamp.eventId, - provider: PROVIDER, - createdAt: requestedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState - ? { turnId: asCanonicalTurnId(context.turnState.turnId) } - : {}), - requestId: asRuntimeRequestId(requestId), - payload: { - requestType, - detail, - args: { - toolName, - input: toolInput, - ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}), - }, - }, - providerRefs: nativeProviderRefs(context, { - providerItemId: callbackOptions.toolUseID, - }), - raw: { - source: "claude.sdk.permission", - method: "canUseTool/request", - payload: { - toolName, - input: toolInput, - }, - }, - }); - - pendingApprovals.set(requestId, pendingApproval); - - const onAbort = () => { - if (!pendingApprovals.has(requestId)) { - return; - } - pendingApprovals.delete(requestId); - Effect.runFork(Deferred.succeed(decisionDeferred, "cancel")); - }; - - callbackOptions.signal.addEventListener("abort", onAbort, { - once: true, - }); - - const decision = yield* Deferred.await(decisionDeferred); - pendingApprovals.delete(requestId); - - const resolvedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "request.resolved", - eventId: resolvedStamp.eventId, - provider: PROVIDER, - createdAt: resolvedStamp.createdAt, - threadId: context.session.threadId, - ...(context.turnState - ? { turnId: asCanonicalTurnId(context.turnState.turnId) } - : {}), - requestId: asRuntimeRequestId(requestId), - payload: { - requestType, - decision, - }, - providerRefs: nativeProviderRefs(context, { - providerItemId: callbackOptions.toolUseID, - }), - raw: { - source: "claude.sdk.permission", - method: "canUseTool/decision", - payload: { - decision, - }, - }, - }); - - if (decision === "accept" || decision === "acceptForSession") { - return { - behavior: "allow", - updatedInput: toolInput, - ...(decision === "acceptForSession" && pendingApproval.suggestions - ? { updatedPermissions: [...pendingApproval.suggestions] } - : {}), - } satisfies PermissionResult; - } - - return { - behavior: "deny", - message: - decision === "cancel" - ? "User cancelled tool execution." - : "User declined tool execution.", - } satisfies PermissionResult; - }), - ); - - const claudeSettings = yield* serverSettingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.claudeAgent), - Effect.mapError( - (error) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId: input.threadId, - detail: error.message, - cause: error, - }), - ), - ); - const claudeBinaryPath = claudeSettings.binaryPath; - const modelSelection = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; - const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null); - const caps = getClaudeModelCapabilities(modelSelection?.model); - const effort = - requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null; - const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode; - const thinking = - typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle - ? modelSelection.options.thinking - : undefined; - const effectiveEffort = getEffectiveClaudeCodeEffort(effort); - const permissionMode = - input.runtimeMode === "full-access" ? "bypassPermissions" : undefined; - const settings = { - ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), - ...(fastMode ? { fastMode: true } : {}), - }; - - const queryOptions: ClaudeQueryOptions = { - ...(input.cwd ? { cwd: input.cwd } : {}), - ...(modelSelection?.model ? { model: modelSelection.model } : {}), - pathToClaudeCodeExecutable: claudeBinaryPath, - settingSources: [...CLAUDE_SETTING_SOURCES], - ...(effectiveEffort ? { effort: effectiveEffort } : {}), - ...(permissionMode ? { permissionMode } : {}), - ...(permissionMode === "bypassPermissions" - ? { allowDangerouslySkipPermissions: true } - : {}), - ...(Object.keys(settings).length > 0 ? { settings } : {}), - ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}), - ...(newSessionId ? { sessionId: newSessionId } : {}), - includePartialMessages: true, - canUseTool, - env: process.env, - ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}), - }; - - const queryRuntime = yield* Effect.try({ - try: () => - createQuery({ - prompt, - options: queryOptions, - }), - catch: (cause) => - new ProviderAdapterProcessError({ - provider: PROVIDER, - threadId, - detail: toMessage(cause, "Failed to start Claude runtime session."), - cause, - }), - }); - - const session: ProviderSession = { - threadId, - provider: PROVIDER, - status: "ready", - runtimeMode: input.runtimeMode, - ...(input.cwd ? { cwd: input.cwd } : {}), - ...(modelSelection?.model ? { model: modelSelection.model } : {}), - ...(threadId ? { threadId } : {}), - resumeCursor: { - ...(threadId ? { threadId } : {}), - ...(sessionId ? { resume: sessionId } : {}), - ...(resumeState?.resumeSessionAt - ? { resumeSessionAt: resumeState.resumeSessionAt } - : {}), - turnCount: resumeState?.turnCount ?? 0, - }, - createdAt: startedAt, - updatedAt: startedAt, - }; - - const context: ClaudeSessionContext = { - session, - promptQueue, - query: queryRuntime, - streamFiber: undefined, - startedAt, - basePermissionMode: permissionMode, - resumeSessionId: sessionId, - pendingApprovals, - pendingUserInputs, - turns: [], - inFlightTools, - turnState: undefined, - lastKnownContextWindow: undefined, - lastKnownTokenUsage: undefined, - lastAssistantUuid: resumeState?.resumeSessionAt, - lastThreadStartedId: undefined, - stopped: false, - }; - yield* Ref.set(contextRef, context); - sessions.set(threadId, context); - - const sessionStartedStamp = yield* makeEventStamp(); - yield* offerRuntimeEvent({ - type: "session.started", - eventId: sessionStartedStamp.eventId, - provider: PROVIDER, - createdAt: sessionStartedStamp.createdAt, - threadId, - payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {}, - providerRefs: {}, - }); - - const readyStamp = yield* makeEventStamp(); + switch (message.subtype) { + case "status": yield* offerRuntimeEvent({ + ...base, type: "session.state.changed", - eventId: readyStamp.eventId, - provider: PROVIDER, - createdAt: readyStamp.createdAt, - threadId, payload: { - state: "ready", + state: message.status === "compacting" ? "waiting" : "running", + reason: `status:${message.status ?? "active"}`, + detail: message, }, - providerRefs: {}, }); - - const streamFiber = Effect.runFork(runSdkStream(context)); - context.streamFiber = streamFiber; - streamFiber.addObserver((exit) => { - if (context.stopped) { - return; - } - if (context.streamFiber === streamFiber) { - context.streamFiber = undefined; - } - Effect.runFork(handleStreamExit(context, exit)); - }); - - return { - ...session, - }; - }); - - const sendTurn: ClaudeAdapterShape["sendTurn"] = (input) => - Effect.gen(function* () { - const context = yield* requireSession(input.threadId); - const modelSelection = - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; - - if (context.turnState) { - // Auto-close a stale synthetic turn (from background agent responses - // between user prompts) to prevent blocking the user's next turn. - yield* completeTurn(context, "completed"); - } - - if (modelSelection?.model) { - yield* Effect.tryPromise({ - try: () => context.query.setModel(modelSelection.model), - catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause), - }); - } - - // Apply interaction mode by switching the SDK's permission mode. - // "plan" maps directly to the SDK's "plan" permission mode; - // "default" restores the session's original permission mode. - // When interactionMode is absent we leave the current mode unchanged. - if (input.interactionMode === "plan") { - yield* Effect.tryPromise({ - try: () => context.query.setPermissionMode("plan"), - catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), - }); - } else if (input.interactionMode === "default") { - yield* Effect.tryPromise({ - try: () => - context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"), - catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), - }); - } - - const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); - const turnState: ClaudeTurnState = { - turnId, - startedAt: yield* nowIso, - items: [], - assistantTextBlocks: new Map(), - assistantTextBlockOrder: [], - capturedProposedPlanKeys: new Set(), - nextSyntheticAssistantBlockIndex: -1, - }; - - const updatedAt = yield* nowIso; - context.turnState = turnState; - context.session = { - ...context.session, - status: "running", - activeTurnId: turnId, - updatedAt, - }; - - const turnStartedStamp = yield* makeEventStamp(); + return; + case "compact_boundary": yield* offerRuntimeEvent({ - type: "turn.started", - eventId: turnStartedStamp.eventId, - provider: PROVIDER, - createdAt: turnStartedStamp.createdAt, - threadId: context.session.threadId, - turnId, - payload: modelSelection?.model ? { model: modelSelection.model } : {}, - providerRefs: {}, + ...base, + type: "thread.state.changed", + payload: { + state: "compacted", + detail: message, + }, }); - - const message = yield* buildUserMessageEffect(input, { - fileSystem, - attachmentsDir: serverConfig.attachmentsDir, + return; + case "task_started": + yield* offerRuntimeEvent({ + ...base, + type: "task.started", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + description: message.description, + ...(message.task_type ? { taskType: message.task_type } : {}), + }, }); - - yield* Queue.offer(context.promptQueue, { - type: "message", + return; + case "task_progress": + if (message.usage) { + const normalizedUsage = normalizeClaudeTokenUsage( + message.usage, + context.lastKnownContextWindow, + ); + if (normalizedUsage) { + context.lastKnownTokenUsage = normalizedUsage; + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + ...base, + eventId: usageStamp.eventId, + createdAt: usageStamp.createdAt, + type: "thread.token-usage.updated", + payload: { + usage: normalizedUsage, + }, + }); + } + } + yield* offerRuntimeEvent({ + ...base, + type: "task.progress", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + description: message.description, + ...(message.summary ? { summary: message.summary } : {}), + ...(message.usage + ? { usage: normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow) } + : {}), + ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}), + }, + }); + return; + case "task_notification": + if (message.usage) { + const normalizedUsage = normalizeClaudeTokenUsage( + message.usage, + context.lastKnownContextWindow, + ); + if (normalizedUsage) { + context.lastKnownTokenUsage = normalizedUsage; + const usageStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + ...base, + eventId: usageStamp.eventId, + createdAt: usageStamp.createdAt, + type: "thread.token-usage.updated", + payload: { + usage: normalizedUsage, + }, + }); + } + } + yield* offerRuntimeEvent({ + ...base, + type: "task.completed", + payload: { + taskId: RuntimeTaskId.makeUnsafe(message.task_id), + status: message.status, + ...(message.summary ? { summary: message.summary } : {}), + ...(message.usage + ? { usage: normalizeClaudeTokenUsage(message.usage, context.lastKnownContextWindow) } + : {}), + }, + }); + return; + default: + yield* emitRuntimeWarning( + context, + `Unhandled Claude system message subtype '${message.subtype}'.`, message, - }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause))); + ); + return; + } + }); - return { - threadId: context.session.threadId, - turnId, - ...(context.session.resumeCursor !== undefined - ? { resumeCursor: context.session.resumeCursor } - : {}), - }; - }); + const handleSdkTelemetryMessage = ( + _context: ClaudeSessionContext, + _message: SDKMessage, + ): Effect.Effect => Effect.void; - const interruptTurn: ClaudeAdapterShape["interruptTurn"] = (threadId, _turnId) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - yield* Effect.tryPromise({ - try: () => context.query.interrupt(), - catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), - }); - }); + const handleSdkMessage = Effect.fn("handleSdkMessage")(function* ( + context: ClaudeSessionContext, + message: SDKMessage, + ) { + yield* logNativeSdkMessage(context, message); + yield* ensureThreadId(context, message); - const readThread: ClaudeAdapterShape["readThread"] = (threadId) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - return yield* snapshotThread(context); - }); + switch (message.type) { + case "stream_event": + yield* handleStreamEvent(context, message); + return; + case "user": + yield* handleUserMessage(context, message); + return; + case "assistant": + yield* handleAssistantMessage(context, message); + return; + case "result": + yield* handleResultMessage(context, message); + return; + case "system": + yield* handleSystemMessage(context, message); + return; + case "tool_progress": + case "tool_use_summary": + case "auth_status": + case "rate_limit_event": + yield* handleSdkTelemetryMessage(context, message); + return; + default: + yield* emitRuntimeWarning( + context, + `Unhandled Claude SDK message type '${message.type}'.`, + message, + ); + return; + } + }); - const rollbackThread: ClaudeAdapterShape["rollbackThread"] = (threadId, numTurns) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - const nextLength = Math.max(0, context.turns.length - numTurns); - context.turns.splice(nextLength); - yield* updateResumeCursor(context); - return yield* snapshotThread(context); - }); - - const respondToRequest: ClaudeAdapterShape["respondToRequest"] = ( - threadId, - requestId, - decision, - ) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - const pending = context.pendingApprovals.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "item/requestApproval/decision", - detail: `Unknown pending approval request: ${requestId}`, - }); - } - - context.pendingApprovals.delete(requestId); - yield* Deferred.succeed(pending.decision, decision); - }); - - const respondToUserInput: ClaudeAdapterShape["respondToUserInput"] = ( - threadId, - requestId, - answers, - ) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - const pending = context.pendingUserInputs.get(requestId); - if (!pending) { - return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "item/tool/respondToUserInput", - detail: `Unknown pending user-input request: ${requestId}`, - }); - } - - context.pendingUserInputs.delete(requestId); - yield* Deferred.succeed(pending.answers, answers); - }); - - const stopSession: ClaudeAdapterShape["stopSession"] = (threadId) => - Effect.gen(function* () { - const context = yield* requireSession(threadId); - yield* stopSessionInternal(context, { - emitExitEvent: true, - }); - }); - - const listSessions: ClaudeAdapterShape["listSessions"] = () => - Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session }))); - - const hasSession: ClaudeAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => { - const context = sessions.get(threadId); - return context !== undefined && !context.stopped; - }); - - const stopAll: ClaudeAdapterShape["stopAll"] = () => - Effect.forEach( - sessions, - ([, context]) => - stopSessionInternal(context, { - emitExitEvent: true, - }), - { discard: true }, - ); - - yield* Effect.addFinalizer(() => - Effect.forEach( - sessions, - ([, context]) => - stopSessionInternal(context, { - emitExitEvent: false, - }), - { discard: true }, - ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))), + const runSdkStream = (context: ClaudeSessionContext): Effect.Effect => + Stream.fromAsyncIterable(context.query, (cause) => + toError(cause, "Claude runtime stream failed."), + ).pipe( + Stream.takeWhile(() => !context.stopped), + Stream.runForEach((message) => handleSdkMessage(context, message)), ); - return { - provider: PROVIDER, - capabilities: { - sessionModelSwitch: "in-session", - }, - startSession, - sendTurn, - interruptTurn, - readThread, - rollbackThread, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), - } satisfies ClaudeAdapterShape; + const handleStreamExit = Effect.fn("handleStreamExit")(function* ( + context: ClaudeSessionContext, + exit: Exit.Exit, + ) { + if (context.stopped) { + return; + } + + if (Exit.isFailure(exit)) { + if (isClaudeInterruptedCause(exit.cause)) { + if (context.turnState) { + yield* completeTurn( + context, + "interrupted", + interruptionMessageFromClaudeCause(exit.cause), + ); + } + } else { + const message = messageFromClaudeStreamCause(exit.cause, "Claude runtime stream failed."); + yield* emitRuntimeError(context, message, Cause.pretty(exit.cause)); + yield* completeTurn(context, "failed", message); + } + } else if (context.turnState) { + yield* completeTurn(context, "interrupted", "Claude runtime stream ended."); + } + + yield* stopSessionInternal(context, { + emitExitEvent: true, + }); }); -} + + const stopSessionInternal = Effect.fn("stopSessionInternal")(function* ( + context: ClaudeSessionContext, + options?: { readonly emitExitEvent?: boolean }, + ) { + if (context.stopped) return; + + context.stopped = true; + + for (const [requestId, pending] of context.pendingApprovals) { + yield* Deferred.succeed(pending.decision, "cancel"); + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.resolved", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType: pending.requestType, + decision: "cancel", + }, + providerRefs: nativeProviderRefs(context), + }); + } + context.pendingApprovals.clear(); + + if (context.turnState) { + yield* completeTurn(context, "interrupted", "Session stopped."); + } + + yield* Queue.shutdown(context.promptQueue); + + const streamFiber = context.streamFiber; + context.streamFiber = undefined; + if (streamFiber && streamFiber.pollUnsafe() === undefined) { + yield* Fiber.interrupt(streamFiber); + } + + // @effect-diagnostics-next-line tryCatchInEffectGen:off + try { + context.query.close(); + } catch (cause) { + yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause); + } + + const updatedAt = yield* nowIso; + context.session = { + ...context.session, + status: "closed", + activeTurnId: undefined, + updatedAt, + }; + + if (options?.emitExitEvent !== false) { + const stamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.exited", + eventId: stamp.eventId, + provider: PROVIDER, + createdAt: stamp.createdAt, + threadId: context.session.threadId, + payload: { + reason: "Session stopped", + exitKind: "graceful", + }, + providerRefs: {}, + }); + } + + sessions.delete(context.session.threadId); + }); + + const requireSession = ( + threadId: ThreadId, + ): Effect.Effect => { + const context = sessions.get(threadId); + if (!context) { + return Effect.fail( + new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + threadId, + }), + ); + } + if (context.stopped || context.session.status === "closed") { + return Effect.fail( + new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + threadId, + }), + ); + } + return Effect.succeed(context); + }; + + const startSession: ClaudeAdapterShape["startSession"] = Effect.fn("startSession")( + function* (input) { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const startedAt = yield* nowIso; + const resumeState = readClaudeResumeState(input.resumeCursor); + const threadId = input.threadId; + const existingResumeSessionId = resumeState?.resume; + const newSessionId = + existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined; + const sessionId = existingResumeSessionId ?? newSessionId; + + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + const runPromise = Effect.runPromiseWith(services); + + const promptQueue = yield* Queue.unbounded(); + const prompt = Stream.fromQueue(promptQueue).pipe( + Stream.filter((item) => item.type === "message"), + Stream.map((item) => item.message), + Stream.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), + ), + Stream.toAsyncIterable, + ); + + const pendingApprovals = new Map(); + const pendingUserInputs = new Map(); + const inFlightTools = new Map(); + + const contextRef = yield* Ref.make(undefined); + + /** + * Handle AskUserQuestion tool calls by emitting a `user-input.requested` + * runtime event and waiting for the user to respond via `respondToUserInput`. + */ + const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* ( + context: ClaudeSessionContext, + toolInput: Record, + callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string }, + ) { + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + + // Parse questions from the SDK's AskUserQuestion input. + const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : []; + const questions: Array = rawQuestions.map( + (q: Record, idx: number) => ({ + id: typeof q.header === "string" ? q.header : `q-${idx}`, + header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`, + question: typeof q.question === "string" ? q.question : "", + options: Array.isArray(q.options) + ? q.options.map((opt: Record) => ({ + label: typeof opt.label === "string" ? opt.label : "", + description: typeof opt.description === "string" ? opt.description : "", + })) + : [], + multiSelect: typeof q.multiSelect === "boolean" ? q.multiSelect : false, + }), + ); + + const answersDeferred = yield* Deferred.make(); + let aborted = false; + const pendingInput: PendingUserInput = { + questions, + answers: answersDeferred, + }; + + // Emit user-input.requested so the UI can present the questions. + const requestedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "user-input.requested", + eventId: requestedStamp.eventId, + provider: PROVIDER, + createdAt: requestedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { questions }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/AskUserQuestion", + payload: { toolName: "AskUserQuestion", input: toolInput }, + }, + }); + + pendingUserInputs.set(requestId, pendingInput); + + // Handle abort (e.g. turn interrupted while waiting for user input). + const onAbort = () => { + if (!pendingUserInputs.has(requestId)) { + return; + } + aborted = true; + pendingUserInputs.delete(requestId); + runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers)); + }; + callbackOptions.signal.addEventListener("abort", onAbort, { once: true }); + + // Block until the user provides answers. + const answers = yield* Deferred.await(answersDeferred); + pendingUserInputs.delete(requestId); + + // Emit user-input.resolved so the UI knows the interaction completed. + const resolvedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "user-input.resolved", + eventId: resolvedStamp.eventId, + provider: PROVIDER, + createdAt: resolvedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { answers }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/AskUserQuestion/resolved", + payload: { answers }, + }, + }); + + if (aborted) { + return { + behavior: "deny", + message: "User cancelled tool execution.", + } satisfies PermissionResult; + } + + // Return the answers to the SDK in the expected format: + // { questions: [...], answers: { questionText: selectedLabel } } + return { + behavior: "allow", + updatedInput: { + questions: toolInput.questions, + answers, + }, + } satisfies PermissionResult; + }); + + const canUseToolEffect = Effect.fn("canUseTool")(function* ( + toolName: Parameters[0], + toolInput: Parameters[1], + callbackOptions: Parameters[2], + ) { + const context = yield* Ref.get(contextRef); + if (!context) { + return { + behavior: "deny", + message: "Claude session context is unavailable.", + } satisfies PermissionResult; + } + + // Handle AskUserQuestion: surface clarifying questions to the + // user via the user-input runtime event channel, regardless of + // runtime mode (plan mode relies on this heavily). + if (toolName === "AskUserQuestion") { + return yield* handleAskUserQuestion(context, toolInput, callbackOptions); + } + + if (toolName === "ExitPlanMode") { + const planMarkdown = extractExitPlanModePlan(toolInput); + if (planMarkdown) { + yield* emitProposedPlanCompleted(context, { + planMarkdown, + toolUseId: callbackOptions.toolUseID, + rawSource: "claude.sdk.permission", + rawMethod: "canUseTool/ExitPlanMode", + rawPayload: { + toolName, + input: toolInput, + }, + }); + } + + return { + behavior: "deny", + message: + "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.", + } satisfies PermissionResult; + } + + const runtimeMode = input.runtimeMode ?? "full-access"; + if (runtimeMode === "full-access") { + return { + behavior: "allow", + updatedInput: toolInput, + } satisfies PermissionResult; + } + + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4); + const requestType = classifyRequestType(toolName); + const detail = summarizeToolRequest(toolName, toolInput); + const decisionDeferred = yield* Deferred.make(); + const pendingApproval: PendingApproval = { + requestType, + detail, + decision: decisionDeferred, + ...(callbackOptions.suggestions ? { suggestions: callbackOptions.suggestions } : {}), + }; + + const requestedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.opened", + eventId: requestedStamp.eventId, + provider: PROVIDER, + createdAt: requestedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType, + detail, + args: { + toolName, + input: toolInput, + ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}), + }, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/request", + payload: { + toolName, + input: toolInput, + }, + }, + }); + + pendingApprovals.set(requestId, pendingApproval); + + const onAbort = () => { + if (!pendingApprovals.has(requestId)) { + return; + } + pendingApprovals.delete(requestId); + runFork(Deferred.succeed(decisionDeferred, "cancel")); + }; + + callbackOptions.signal.addEventListener("abort", onAbort, { + once: true, + }); + + const decision = yield* Deferred.await(decisionDeferred); + pendingApprovals.delete(requestId); + + const resolvedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "request.resolved", + eventId: resolvedStamp.eventId, + provider: PROVIDER, + createdAt: resolvedStamp.createdAt, + threadId: context.session.threadId, + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}), + requestId: asRuntimeRequestId(requestId), + payload: { + requestType, + decision, + }, + providerRefs: nativeProviderRefs(context, { + providerItemId: callbackOptions.toolUseID, + }), + raw: { + source: "claude.sdk.permission", + method: "canUseTool/decision", + payload: { + decision, + }, + }, + }); + + if (decision === "accept" || decision === "acceptForSession") { + return { + behavior: "allow", + updatedInput: toolInput, + ...(decision === "acceptForSession" && pendingApproval.suggestions + ? { updatedPermissions: [...pendingApproval.suggestions] } + : {}), + } satisfies PermissionResult; + } + + return { + behavior: "deny", + message: + decision === "cancel" + ? "User cancelled tool execution." + : "User declined tool execution.", + } satisfies PermissionResult; + }); + + const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) => + runPromise(canUseToolEffect(toolName, toolInput, callbackOptions)); + + const claudeSettings = yield* serverSettingsService.getSettings.pipe( + Effect.map((settings) => settings.providers.claudeAgent), + Effect.mapError( + (error) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId: input.threadId, + detail: error.message, + cause: error, + }), + ), + ); + const claudeBinaryPath = claudeSettings.binaryPath; + const modelSelection = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + const caps = getClaudeModelCapabilities(modelSelection?.model); + const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined; + const effort = (resolveEffort(caps, modelSelection?.options?.effort) ?? + null) as ClaudeCodeEffort | null; + const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode; + const thinking = + typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle + ? modelSelection.options.thinking + : undefined; + const effectiveEffort = getEffectiveClaudeCodeEffort(effort); + const permissionMode = input.runtimeMode === "full-access" ? "bypassPermissions" : undefined; + const settings = { + ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), + ...(fastMode ? { fastMode: true } : {}), + }; + + const queryOptions: ClaudeQueryOptions = { + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(apiModelId ? { model: apiModelId } : {}), + pathToClaudeCodeExecutable: claudeBinaryPath, + settingSources: [...CLAUDE_SETTING_SOURCES], + ...(effectiveEffort ? { effort: effectiveEffort } : {}), + ...(permissionMode ? { permissionMode } : {}), + ...(permissionMode === "bypassPermissions" + ? { allowDangerouslySkipPermissions: true } + : {}), + ...(Object.keys(settings).length > 0 ? { settings } : {}), + ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}), + ...(newSessionId ? { sessionId: newSessionId } : {}), + includePartialMessages: true, + canUseTool, + env: process.env, + ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}), + }; + + const queryRuntime = yield* Effect.try({ + try: () => + createQuery({ + prompt, + options: queryOptions, + }), + catch: (cause) => + new ProviderAdapterProcessError({ + provider: PROVIDER, + threadId, + detail: toMessage(cause, "Failed to start Claude runtime session."), + cause, + }), + }); + + const session: ProviderSession = { + threadId, + provider: PROVIDER, + status: "ready", + runtimeMode: input.runtimeMode, + ...(input.cwd ? { cwd: input.cwd } : {}), + ...(modelSelection?.model ? { model: modelSelection.model } : {}), + ...(threadId ? { threadId } : {}), + resumeCursor: { + ...(threadId ? { threadId } : {}), + ...(sessionId ? { resume: sessionId } : {}), + ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}), + turnCount: resumeState?.turnCount ?? 0, + }, + createdAt: startedAt, + updatedAt: startedAt, + }; + + const context: ClaudeSessionContext = { + session, + promptQueue, + query: queryRuntime, + streamFiber: undefined, + startedAt, + basePermissionMode: permissionMode, + currentApiModelId: apiModelId, + resumeSessionId: sessionId, + pendingApprovals, + pendingUserInputs, + turns: [], + inFlightTools, + turnState: undefined, + lastKnownContextWindow: undefined, + lastKnownTokenUsage: undefined, + lastAssistantUuid: resumeState?.resumeSessionAt, + lastThreadStartedId: undefined, + stopped: false, + }; + yield* Ref.set(contextRef, context); + sessions.set(threadId, context); + + const sessionStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.started", + eventId: sessionStartedStamp.eventId, + provider: PROVIDER, + createdAt: sessionStartedStamp.createdAt, + threadId, + payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {}, + providerRefs: {}, + }); + + const readyStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "session.state.changed", + eventId: readyStamp.eventId, + provider: PROVIDER, + createdAt: readyStamp.createdAt, + threadId, + payload: { + state: "ready", + }, + providerRefs: {}, + }); + + let streamFiber: Fiber.Fiber; + streamFiber = runFork( + Effect.exit(runSdkStream(context)).pipe( + Effect.flatMap((exit) => { + if (context.stopped) { + return Effect.void; + } + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + return handleStreamExit(context, exit); + }), + ), + ); + context.streamFiber = streamFiber; + streamFiber.addObserver(() => { + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + }); + + return { + ...session, + }; + }, + ); + + const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { + const context = yield* requireSession(input.threadId); + const modelSelection = + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; + + if (context.turnState) { + // Auto-close a stale synthetic turn (from background agent responses + // between user prompts) to prevent blocking the user's next turn. + yield* completeTurn(context, "completed"); + } + + if (modelSelection?.model) { + const apiModelId = resolveApiModelId(modelSelection); + if (context.currentApiModelId !== apiModelId) { + yield* Effect.tryPromise({ + try: () => context.query.setModel(apiModelId), + catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause), + }); + context.currentApiModelId = apiModelId; + } + context.session = { + ...context.session, + model: modelSelection.model, + }; + } + + // Apply interaction mode by switching the SDK's permission mode. + // "plan" maps directly to the SDK's "plan" permission mode; + // "default" restores the session's original permission mode. + // When interactionMode is absent we leave the current mode unchanged. + if (input.interactionMode === "plan") { + yield* Effect.tryPromise({ + try: () => context.query.setPermissionMode("plan"), + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), + }); + } else if (input.interactionMode === "default") { + yield* Effect.tryPromise({ + try: () => + context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"), + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause), + }); + } + + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4); + const turnState: ClaudeTurnState = { + turnId, + startedAt: yield* nowIso, + items: [], + assistantTextBlocks: new Map(), + assistantTextBlockOrder: [], + capturedProposedPlanKeys: new Set(), + nextSyntheticAssistantBlockIndex: -1, + }; + + const updatedAt = yield* nowIso; + context.turnState = turnState; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt, + }; + + const turnStartedStamp = yield* makeEventStamp(); + yield* offerRuntimeEvent({ + type: "turn.started", + eventId: turnStartedStamp.eventId, + provider: PROVIDER, + createdAt: turnStartedStamp.createdAt, + threadId: context.session.threadId, + turnId, + payload: modelSelection?.model ? { model: modelSelection.model } : {}, + providerRefs: {}, + }); + + const message = yield* buildUserMessageEffect(input, { + fileSystem, + attachmentsDir: serverConfig.attachmentsDir, + }); + + yield* Queue.offer(context.promptQueue, { + type: "message", + message, + }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause))); + + return { + threadId: context.session.threadId, + turnId, + ...(context.session.resumeCursor !== undefined + ? { resumeCursor: context.session.resumeCursor } + : {}), + }; + }); + + const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")( + function* (threadId, _turnId) { + const context = yield* requireSession(threadId); + yield* Effect.tryPromise({ + try: () => context.query.interrupt(), + catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), + }); + }, + ); + + const readThread: ClaudeAdapterShape["readThread"] = Effect.fn("readThread")( + function* (threadId) { + const context = yield* requireSession(threadId); + return yield* snapshotThread(context); + }, + ); + + const rollbackThread: ClaudeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")( + function* (threadId, numTurns) { + const context = yield* requireSession(threadId); + const nextLength = Math.max(0, context.turns.length - numTurns); + context.turns.splice(nextLength); + yield* updateResumeCursor(context); + return yield* snapshotThread(context); + }, + ); + + const respondToRequest: ClaudeAdapterShape["respondToRequest"] = Effect.fn("respondToRequest")( + function* (threadId, requestId, decision) { + const context = yield* requireSession(threadId); + const pending = context.pendingApprovals.get(requestId); + if (!pending) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "item/requestApproval/decision", + detail: `Unknown pending approval request: ${requestId}`, + }); + } + + context.pendingApprovals.delete(requestId); + yield* Deferred.succeed(pending.decision, decision); + }, + ); + + const respondToUserInput: ClaudeAdapterShape["respondToUserInput"] = Effect.fn( + "respondToUserInput", + )(function* (threadId, requestId, answers) { + const context = yield* requireSession(threadId); + const pending = context.pendingUserInputs.get(requestId); + if (!pending) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "item/tool/respondToUserInput", + detail: `Unknown pending user-input request: ${requestId}`, + }); + } + + context.pendingUserInputs.delete(requestId); + yield* Deferred.succeed(pending.answers, answers); + }); + + const stopSession: ClaudeAdapterShape["stopSession"] = Effect.fn("stopSession")( + function* (threadId) { + const context = yield* requireSession(threadId); + yield* stopSessionInternal(context, { + emitExitEvent: true, + }); + }, + ); + + const listSessions: ClaudeAdapterShape["listSessions"] = () => + Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session }))); + + const hasSession: ClaudeAdapterShape["hasSession"] = (threadId) => + Effect.sync(() => { + const context = sessions.get(threadId); + return context !== undefined && !context.stopped; + }); + + const stopAll: ClaudeAdapterShape["stopAll"] = () => + Effect.forEach( + sessions, + ([, context]) => + stopSessionInternal(context, { + emitExitEvent: true, + }), + { discard: true }, + ); + + yield* Effect.addFinalizer(() => + Effect.forEach( + sessions, + ([, context]) => + stopSessionInternal(context, { + emitExitEvent: false, + }), + { discard: true }, + ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))), + ); + + return { + provider: PROVIDER, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + readThread, + rollbackThread, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + stopAll, + streamEvents: Stream.fromQueue(runtimeEventQueue), + } satisfies ClaudeAdapterShape; +}); export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter()); diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index e51f5096db..158a9ef25a 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -1,30 +1,31 @@ import type { ClaudeSettings, - ClaudeModelOptions, ModelCapabilities, ServerProvider, ServerProviderModel, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderState, } from "@t3tools/contracts"; -import { Effect, Equal, Layer, Option, Result, Stream } from "effect"; +import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { getDefaultEffort, hasEffortLevel, trimOrNull } from "@t3tools/shared/model"; +import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk"; import { buildServerProvider, - collectStreamAsString, DEFAULT_TIMEOUT_MS, detailFromResult, extractAuthBoolean, isCommandMissingCause, parseGenericCliVersion, providerModelsFromSettings, + spawnAndCollect, type CommandResult, } 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 = [ @@ -42,6 +43,10 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, }, @@ -58,6 +63,10 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, }, @@ -69,6 +78,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], } satisfies ModelCapabilities, }, @@ -81,40 +91,15 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], } ); } -export function normalizeClaudeModelOptions( - model: string | null | undefined, - modelOptions: ClaudeModelOptions | null | undefined, -): ClaudeModelOptions | undefined { - const caps = getClaudeModelCapabilities(model); - const defaultReasoningEffort = getDefaultEffort(caps); - const resolvedEffort = trimOrNull(modelOptions?.effort); - const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? ""); - const effort = - resolvedEffort && - !isPromptInjected && - hasEffortLevel(caps, resolvedEffort) && - resolvedEffort !== defaultReasoningEffort - ? resolvedEffort - : undefined; - const thinking = - caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined; - const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined; - const nextOptions: ClaudeModelOptions = { - ...(thinking === false ? { thinking: false } : {}), - ...(effort ? { effort } : {}), - ...(fastMode ? { fastMode: true } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} - export function parseClaudeAuthStatusFromOutput(result: CommandResult): { readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: Pick; readonly message?: string; } { const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); @@ -126,7 +111,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { ) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Claude Agent authentication status command is unavailable in this version of Claude.", }; @@ -141,7 +126,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { ) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Claude is not authenticated. Run `claude auth login` and try again.", }; } @@ -162,40 +147,288 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { })(); if (parsedAuth.auth === true) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } if (parsedAuth.auth === false) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Claude is not authenticated. Run `claude auth login` and try again.", }; } if (parsedAuth.attemptedJsonParse) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Could not verify Claude authentication status from JSON output (missing auth marker).", }; } if (result.code === 0) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } const detail = detailFromResult(result); return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: detail ? `Could not verify Claude authentication status. ${detail}` : "Could not verify Claude authentication status.", }; } +// ── Subscription type detection ───────────────────────────────────── +// +// The SDK probe returns typed `AccountInfo.subscriptionType` directly. +// This walker is a best-effort fallback for the `claude auth status` +// JSON output whose shape is not guaranteed. + +/** Keys that directly hold a subscription/plan identifier. */ +const SUBSCRIPTION_TYPE_KEYS = [ + "subscriptionType", + "subscription_type", + "plan", + "tier", + "planType", + "plan_type", +] as const; + +/** Keys whose value may be a nested object containing subscription info. */ +const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const; +const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const; +const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const; + +/** Lift an unknown value into `Option` if it is a non-empty string. */ +const asNonEmptyString = (v: unknown): Option.Option => + typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none(); + +/** Lift an unknown value into `Option` if it is a plain object. */ +const asRecord = (v: unknown): Option.Option> => + typeof v === "object" && v !== null && !globalThis.Array.isArray(v) + ? Option.some(v as Record) + : Option.none(); + +/** + * Walk an unknown parsed JSON value looking for a subscription/plan + * identifier, returning the first match as an `Option`. + */ +function findSubscriptionType(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findSubscriptionType)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + SUBSCRIPTION_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)), + ), + ); + }), + ); +} + +function findAuthMethod(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findAuthMethod)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + AUTH_METHOD_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)), + ), + ); + }), + ); +} + +/** + * Try to extract a subscription type from the `claude auth status` JSON + * output. This is a zero-cost operation on data we already have. + */ +const decodeUnknownJson = decodeJsonResult(Schema.Unknown); + +function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findSubscriptionType(parsed.success)); +} + +function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findAuthMethod(parsed.success)); +} + +// ── Dynamic model capability adjustment ───────────────────────────── + +/** Subscription types where the 1M context window is included in the plan. */ +const PREMIUM_SUBSCRIPTION_TYPES = new Set([ + "max", + "maxplan", + "max5", + "max20", + "enterprise", + "team", +]); + +function toTitleCaseWords(value: string): string { + return value + .split(/[\s_-]+/g) + .filter(Boolean) + .map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase()) + .join(" "); +} + +function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + + switch (normalized) { + case "max": + case "maxplan": + case "max5": + case "max20": + return "Max"; + case "enterprise": + return "Enterprise"; + case "team": + return "Team"; + case "pro": + return "Pro"; + case "free": + return "Free"; + default: + return toTitleCaseWords(subscriptionType!); + } +} + +function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined { + const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + if (normalized === "apikey") return "apiKey"; + return undefined; +} + +function claudeAuthMetadata(input: { + readonly subscriptionType: string | undefined; + readonly authMethod: string | undefined; +}): { readonly type: string; readonly label: string } | undefined { + if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") { + return { + type: "apiKey", + label: "Claude API Key", + }; + } + + if (input.subscriptionType) { + const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType); + return { + type: input.subscriptionType, + label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`, + }; + } + + return undefined; +} + +/** + * Adjust the built-in model list based on the user's detected subscription. + * + * - Premium tiers (Max, Enterprise, Team): 1M context becomes the default. + * - Other tiers (Pro, free, unknown): 200k context stays the default; + * 1M remains available as a manual option so users can still enable it. + */ +export function adjustModelsForSubscription( + baseModels: ReadonlyArray, + subscriptionType: string | undefined, +): ReadonlyArray { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) { + return baseModels; + } + + // Flip 1M to be the default for premium users + return baseModels.map((model) => { + const caps = model.capabilities; + if (!caps || caps.contextWindowOptions.length === 0) return model; + + return { + ...model, + capabilities: { + ...caps, + contextWindowOptions: caps.contextWindowOptions.map((opt) => + opt.value === "1m" + ? { value: opt.value, label: opt.label, isDefault: true as const } + : { value: opt.value, label: opt.label }, + ), + }, + }; + }); +} + +// ── SDK capability probe ──────────────────────────────────────────── + +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +/** + * Probe account information by spawning a lightweight Claude Agent SDK + * session and reading the initialization result. + * + * The prompt is never sent to the Anthropic API — we abort immediately + * after the local initialization phase completes. This gives us the + * user's subscription type without incurring any token cost. + * + * This is used as a fallback when `claude auth status` does not include + * subscription type information. + */ +const probeClaudeCapabilities = (binaryPath: string) => { + const abort = new AbortController(); + return Effect.tryPromise(async () => { + const q = claudeQuery({ + prompt: ".", + options: { + persistSession: false, + pathToClaudeCodeExecutable: binaryPath, + abortController: abort, + maxTurns: 0, + settingSources: [], + allowedTools: [], + stderr: () => {}, + }, + }); + const init = await q.initializationResult(); + return { subscriptionType: init.account?.subscriptionType }; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (!abort.signal.aborted) abort.abort(); + }), + ), + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); +}; + const runClaudeCommand = (args: ReadonlyArray) => Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( Effect.flatMap((service) => service.getSettings), Effect.map((settings) => settings.providers.claudeAgent), @@ -203,158 +436,84 @@ const runClaudeCommand = (args: ReadonlyArray) => const command = ChildProcess.make(claudeSettings.binaryPath, [...args], { shell: process.platform === "win32", }); + return yield* spawnAndCollect(claudeSettings.binaryPath, command); + }); - const child = yield* spawner.spawn(command); - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectStreamAsString(child.stdout), - collectStreamAsString(child.stderr), - child.exitCode.pipe(Effect.map(Number)), - ], - { concurrency: "unbounded" }, - ); +export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( + resolveSubscriptionType?: (binaryPath: string) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService +> { + const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.claudeAgent), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels); - return { stdout, stderr, code: exitCode } satisfies CommandResult; - }).pipe(Effect.scoped); + if (!claudeSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Claude is disabled in T3 Code settings.", + }, + }); + } -export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( - function* (): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService - > { - const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.claudeAgent), - ); - const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - claudeSettings.customModels, - ); + const versionProbe = yield* runClaudeCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); - if (!claudeSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - enabled: false, - checkedAt, - models, - probe: { - installed: false, - version: null, - status: "warning", - authStatus: "unknown", - message: "Claude is disabled in T3 Code settings.", - }, - }); - } + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Claude Agent CLI (`claude`) is not installed or not on PATH." + : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } - const versionProbe = yield* runClaudeCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: + "Claude Agent CLI is installed but failed to run. Timed out while running command.", + }, + }); + } - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - authStatus: "unknown", - message: isCommandMissingCause(error) - ? "Claude Agent CLI (`claude`) is not installed or not on PATH." - : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, - }, - }); - } - - if (Option.isNone(versionProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: null, - status: "error", - authStatus: "unknown", - message: - "Claude Agent CLI is installed but failed to run. Timed out while running command.", - }, - }); - } - - const version = versionProbe.success.value; - const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: detail - ? `Claude Agent CLI is installed but failed to run. ${detail}` - : "Claude Agent CLI is installed but failed to run.", - }, - }); - } - - const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - error instanceof Error - ? `Could not verify Claude authentication status: ${error.message}.` - : "Could not verify Claude authentication status.", - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - "Could not verify Claude authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); + const version = versionProbe.success.value; + const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); return buildServerProvider({ provider: PROVIDER, enabled: claudeSettings.enabled, @@ -363,13 +522,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( probe: { installed: true, version: parsedVersion, - status: parsed.status, - authStatus: parsed.authStatus, - ...(parsed.message ? { message: parsed.message } : {}), + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Claude Agent CLI is installed but failed to run. ${detail}` + : "Claude Agent CLI is installed but failed to run.", }, }); - }, -); + } + + // ── Auth check + subscription detection ──────────────────────────── + + const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + + // Determine subscription type from multiple sources (cheapest first): + // 1. `claude auth status` JSON output (may or may not contain it) + // 2. Cached SDK probe (spawns a Claude process on miss, reads + // `initializationResult()` for account metadata, then aborts + // immediately — no API tokens are consumed) + + let subscriptionType: string | undefined; + let authMethod: string | undefined; + + if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) { + subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value); + authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value); + } + + if (!subscriptionType && resolveSubscriptionType) { + subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath); + } + + const resolvedModels = adjustModelsForSubscription(models, subscriptionType); + + // ── Handle auth results (same logic as before, adjusted models) ── + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Claude authentication status: ${error.message}.` + : "Could not verify Claude authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Claude authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); + const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod }); + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authMetadata ? authMetadata : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); export const ClaudeProviderLive = Layer.effect( ClaudeProvider, @@ -377,7 +622,16 @@ export const ClaudeProviderLive = Layer.effect( const serverSettings = yield* ServerSettingsService; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const checkProvider = checkClaudeProviderStatus().pipe( + const subscriptionProbeCache = yield* Cache.make({ + capacity: 1, + timeToLive: Duration.minutes(5), + lookup: (binaryPath: string) => + probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)), + }); + + const checkProvider = checkClaudeProviderStatus((binaryPath) => + Cache.get(subscriptionProbeCache, binaryPath), + ).pipe( Effect.provideService(ServerSettingsService, serverSettings), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 97ed621c7b..b5eb873e85 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -474,6 +474,76 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); + it.effect("maps process stderr notifications to runtime.warning", () => + 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"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: "The filename or extension is too long. (os error 206)", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.warning"); + if (firstEvent.value.type !== "runtime.warning") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal( + firstEvent.value.payload.message, + "The filename or extension is too long. (os error 206)", + ); + }), + ); + + 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 074e4640a1..0bb5111dd0 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -21,6 +21,7 @@ import { ProviderItemId, ThreadId, TurnId, + ProviderSendTurnInput, } from "@t3tools/contracts"; import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect"; @@ -217,6 +218,13 @@ function buildCanonicalToolLifecycleData( return 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); @@ -1207,6 +1215,31 @@ function mapToRuntimeEvents( ]; } + if (event.method === "process/stderr") { + const message = event.message ?? "Codex process stderr"; + const isFatal = isFatalCodexProcessStderrMessage(message); + return [ + 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 } : {}), + }, + }, + ]; + } + if (event.method === "windows/worldWritableWarning") { return [ { @@ -1254,38 +1287,40 @@ function mapToRuntimeEvents( return []; } -const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const serverConfig = yield* Effect.service(ServerConfig); - const nativeEventLogger = - options?.nativeEventLogger ?? - (options?.nativeEventLogPath !== undefined - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { - stream: "native", - }) - : undefined); +const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( + options?: CodexAdapterLiveOptions, +) { + const fileSystem = yield* FileSystem.FileSystem; + const serverConfig = yield* Effect.service(ServerConfig); + const nativeEventLogger = + options?.nativeEventLogger ?? + (options?.nativeEventLogPath !== undefined + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { + stream: "native", + }) + : undefined); - const manager = yield* Effect.acquireRelease( - Effect.gen(function* () { - if (options?.manager) { - return options.manager; - } - const services = yield* Effect.services(); - return options?.makeManager?.(services) ?? new CodexAppServerManager(services); - }), - (manager) => - Effect.sync(() => { - try { - manager.stopAll(); - } catch { - // Finalizers should never fail and block shutdown. - } - }), - ); - const serverSettingsService = yield* ServerSettingsService; + const acquireManager = Effect.fn("acquireManager")(function* () { + if (options?.manager) { + return options.manager; + } + const services = yield* Effect.services(); + return options?.makeManager?.(services) ?? new CodexAppServerManager(services); + }); - const startSession: CodexAdapterShape["startSession"] = Effect.fn(function* (input) { + const manager = yield* Effect.acquireRelease(acquireManager(), (manager) => + Effect.sync(() => { + try { + manager.stopAll(); + } catch { + // Finalizers should never fail and block shutdown. + } + }), + ); + const serverSettingsService = yield* ServerSettingsService; + + const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")( + function* (input) { if (input.provider !== undefined && input.provider !== PROVIDER) { return yield* new ProviderAdapterValidationError({ provider: PROVIDER, @@ -1334,211 +1369,212 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => cause, }), }); + }, + ); + + const resolveAttachment = Effect.fn("resolveAttachment")(function* ( + input: ProviderSendTurnInput, + attachment: NonNullable[number], + ) { + const attachmentPath = resolveAttachmentPath({ + attachmentsDir: serverConfig.attachmentsDir, + attachment, }); - - const sendTurn: CodexAdapterShape["sendTurn"] = (input) => - Effect.gen(function* () { - const codexAttachments = yield* Effect.forEach( - input.attachments ?? [], - (attachment) => - Effect.gen(function* () { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - if (!attachmentPath) { - return yield* toRequestError( - input.threadId, - "turn/start", - new Error(`Invalid attachment id '${attachment.id}'.`), - ); - } - const bytes = yield* fileSystem.readFile(attachmentPath).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterRequestError({ - provider: PROVIDER, - method: "turn/start", - detail: toMessage(cause, "Failed to read attachment file."), - cause, - }), - ), - ); - return { - type: "image" as const, - url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`, - }; - }), - { concurrency: 1 }, - ); - - return yield* Effect.tryPromise({ - try: () => { - const managerInput = { - threadId: input.threadId, - ...(input.input !== undefined ? { input: input.input } : {}), - ...(input.modelSelection?.provider === "codex" - ? { model: input.modelSelection.model } - : {}), - ...(input.modelSelection?.provider === "codex" && - input.modelSelection.options?.reasoningEffort !== undefined - ? { effort: input.modelSelection.options.reasoningEffort } - : {}), - ...(input.modelSelection?.provider === "codex" && - input.modelSelection.options?.fastMode - ? { serviceTier: "fast" } - : {}), - ...(input.interactionMode !== undefined - ? { interactionMode: input.interactionMode } - : {}), - ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), - }; - return manager.sendTurn(managerInput); - }, - catch: (cause) => toRequestError(input.threadId, "turn/start", cause), - }).pipe( - Effect.map((result) => ({ - ...result, - threadId: input.threadId, - })), - ); - }); - - const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) => - Effect.tryPromise({ - try: () => manager.interruptTurn(threadId, turnId), - catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), - }); - - const readThread: CodexAdapterShape["readThread"] = (threadId) => - Effect.tryPromise({ - try: () => manager.readThread(threadId), - catch: (cause) => toRequestError(threadId, "thread/read", cause), - }).pipe( - Effect.map((snapshot) => ({ - threadId, - turns: snapshot.turns, - })), + if (!attachmentPath) { + return yield* toRequestError( + input.threadId, + "turn/start", + new Error(`Invalid attachment id '${attachment.id}'.`), ); - - const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => { - if (!Number.isInteger(numTurns) || numTurns < 1) { - return Effect.fail( - new ProviderAdapterValidationError({ + } + const bytes = yield* fileSystem.readFile(attachmentPath).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterRequestError({ provider: PROVIDER, - operation: "rollbackThread", - issue: "numTurns must be an integer >= 1.", + method: "turn/start", + detail: toMessage(cause, "Failed to read attachment file."), + cause, }), - ); - } - - return Effect.tryPromise({ - try: () => manager.rollbackThread(threadId, numTurns), - catch: (cause) => toRequestError(threadId, "thread/rollback", cause), - }).pipe( - Effect.map((snapshot) => ({ - threadId, - turns: snapshot.turns, - })), - ); + ), + ); + return { + type: "image" as const, + url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`, }; + }); - const respondToRequest: CodexAdapterShape["respondToRequest"] = ( - threadId, - requestId, - decision, - ) => - Effect.tryPromise({ - try: () => manager.respondToRequest(threadId, requestId, decision), - catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause), - }); - - const respondToUserInput: CodexAdapterShape["respondToUserInput"] = ( - threadId, - requestId, - answers, - ) => - Effect.tryPromise({ - try: () => manager.respondToUserInput(threadId, requestId, answers), - catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause), - }); - - const stopSession: CodexAdapterShape["stopSession"] = (threadId) => - Effect.sync(() => { - manager.stopSession(threadId); - }); - - const listSessions: CodexAdapterShape["listSessions"] = () => - Effect.sync(() => manager.listSessions()); - - const hasSession: CodexAdapterShape["hasSession"] = (threadId) => - Effect.sync(() => manager.hasSession(threadId)); - - const stopAll: CodexAdapterShape["stopAll"] = () => - Effect.sync(() => { - manager.stopAll(); - }); - - const runtimeEventQueue = yield* Queue.unbounded(); - - yield* Effect.acquireRelease( - Effect.gen(function* () { - const writeNativeEvent = (event: ProviderEvent) => - Effect.gen(function* () { - if (!nativeEventLogger) { - return; - } - yield* nativeEventLogger.write(event, event.threadId); - }); - - const services = yield* Effect.services(); - const listener = (event: ProviderEvent) => - Effect.gen(function* () { - yield* writeNativeEvent(event); - const runtimeEvents = mapToRuntimeEvents(event, event.threadId); - if (runtimeEvents.length === 0) { - yield* Effect.logDebug("ignoring unhandled Codex provider event", { - method: event.method, - threadId: event.threadId, - turnId: event.turnId, - itemId: event.itemId, - }); - return; - } - yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); - }).pipe(Effect.runPromiseWith(services)); - manager.on("event", listener); - return listener; - }), - (listener) => - Effect.gen(function* () { - yield* Effect.sync(() => { - manager.off("event", listener); - }); - yield* Queue.shutdown(runtimeEventQueue); - }), + const sendTurn: CodexAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) { + const codexAttachments = yield* Effect.forEach( + input.attachments ?? [], + (attachment) => resolveAttachment(input, attachment), + { concurrency: 1 }, ); - return { - provider: PROVIDER, - capabilities: { - sessionModelSwitch: "in-session", + return yield* Effect.tryPromise({ + try: () => { + const managerInput = { + threadId: input.threadId, + ...(input.input !== undefined ? { input: input.input } : {}), + ...(input.modelSelection?.provider === "codex" + ? { model: input.modelSelection.model } + : {}), + ...(input.modelSelection?.provider === "codex" && + input.modelSelection.options?.reasoningEffort !== undefined + ? { effort: input.modelSelection.options.reasoningEffort } + : {}), + ...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode + ? { serviceTier: "fast" } + : {}), + ...(input.interactionMode !== undefined + ? { interactionMode: input.interactionMode } + : {}), + ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}), + }; + return manager.sendTurn(managerInput); }, - startSession, - sendTurn, - interruptTurn, - readThread, - rollbackThread, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), - } satisfies CodexAdapterShape; + catch: (cause) => toRequestError(input.threadId, "turn/start", cause), + }).pipe( + Effect.map((result) => ({ + ...result, + threadId: input.threadId, + })), + ); }); + const interruptTurn: CodexAdapterShape["interruptTurn"] = (threadId, turnId) => + Effect.tryPromise({ + try: () => manager.interruptTurn(threadId, turnId), + catch: (cause) => toRequestError(threadId, "turn/interrupt", cause), + }); + + const readThread: CodexAdapterShape["readThread"] = (threadId) => + Effect.tryPromise({ + try: () => manager.readThread(threadId), + catch: (cause) => toRequestError(threadId, "thread/read", cause), + }).pipe( + Effect.map((snapshot) => ({ + threadId, + turns: snapshot.turns, + })), + ); + + const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => { + if (!Number.isInteger(numTurns) || numTurns < 1) { + return Effect.fail( + new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "rollbackThread", + issue: "numTurns must be an integer >= 1.", + }), + ); + } + + return Effect.tryPromise({ + try: () => manager.rollbackThread(threadId, numTurns), + catch: (cause) => toRequestError(threadId, "thread/rollback", cause), + }).pipe( + Effect.map((snapshot) => ({ + threadId, + turns: snapshot.turns, + })), + ); + }; + + const respondToRequest: CodexAdapterShape["respondToRequest"] = (threadId, requestId, decision) => + Effect.tryPromise({ + try: () => manager.respondToRequest(threadId, requestId, decision), + catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause), + }); + + const respondToUserInput: CodexAdapterShape["respondToUserInput"] = ( + threadId, + requestId, + answers, + ) => + Effect.tryPromise({ + try: () => manager.respondToUserInput(threadId, requestId, answers), + catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause), + }); + + const stopSession: CodexAdapterShape["stopSession"] = (threadId) => + Effect.sync(() => { + manager.stopSession(threadId); + }); + + const listSessions: CodexAdapterShape["listSessions"] = () => + Effect.sync(() => manager.listSessions()); + + const hasSession: CodexAdapterShape["hasSession"] = (threadId) => + Effect.sync(() => manager.hasSession(threadId)); + + const stopAll: CodexAdapterShape["stopAll"] = () => + Effect.sync(() => { + manager.stopAll(); + }); + + const runtimeEventQueue = yield* Queue.unbounded(); + + const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) { + if (!nativeEventLogger) { + return; + } + yield* nativeEventLogger.write(event, event.threadId); + }); + + const registerListener = Effect.fn("registerListener")(function* () { + const services = yield* Effect.services(); + const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) { + yield* writeNativeEvent(event); + const runtimeEvents = mapToRuntimeEvents(event, event.threadId); + if (runtimeEvents.length === 0) { + yield* Effect.logDebug("ignoring unhandled Codex provider event", { + method: event.method, + threadId: event.threadId, + turnId: event.turnId, + itemId: event.itemId, + }); + return; + } + yield* Queue.offerAll(runtimeEventQueue, runtimeEvents); + }); + const listener = (event: ProviderEvent) => + listenerEffect(event).pipe(Effect.runPromiseWith(services)); + manager.on("event", listener); + return listener; + }); + + const unregisterListener = Effect.fn("unregisterListener")(function* ( + listener: (event: ProviderEvent) => Promise, + ) { + yield* Effect.sync(() => { + manager.off("event", listener); + }); + yield* Queue.shutdown(runtimeEventQueue); + }); + + yield* Effect.acquireRelease(registerListener(), unregisterListener); + + return { + provider: PROVIDER, + capabilities: { + sessionModelSwitch: "in-session", + }, + startSession, + sendTurn, + interruptTurn, + readThread, + rollbackThread, + respondToRequest, + respondToUserInput, + stopSession, + listSessions, + hasSession, + stopAll, + streamEvents: Stream.fromQueue(runtimeEventQueue), + } satisfies CodexAdapterShape; +}); + export const CodexAdapterLive = Layer.effect(CodexAdapter, makeCodexAdapter()); export function makeCodexAdapterLive(options?: CodexAdapterLiveOptions) { diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 913fbb58d5..499d4c6ffd 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,26 +1,35 @@ import * as OS from "node:os"; import type { ModelCapabilities, - CodexModelOptions, CodexSettings, ServerProvider, ServerProviderModel, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderState, } from "@t3tools/contracts"; -import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect"; +import { + Cache, + Duration, + Effect, + Equal, + FileSystem, + Layer, + Option, + Path, + Result, + Stream, +} from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { getDefaultEffort, trimOrNull } from "@t3tools/shared/model"; import { buildServerProvider, - collectStreamAsString, DEFAULT_TIMEOUT_MS, detailFromResult, extractAuthBoolean, isCommandMissingCause, parseGenericCliVersion, providerModelsFromSettings, + spawnAndCollect, type CommandResult, } from "../providerSnapshot"; import { makeManagedServerProvider } from "../makeManagedServerProvider"; @@ -29,8 +38,16 @@ import { isCodexCliVersionSupported, parseCodexCliVersion, } from "../codexCliVersion"; +import { + adjustCodexModelsForAccount, + codexAuthSubLabel, + codexAuthSubType, + type CodexAccountSnapshot, +} 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"]); @@ -48,6 +65,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -64,6 +82,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -80,6 +99,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -96,6 +116,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -112,6 +133,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -128,6 +150,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -140,31 +163,15 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], } ); } -export function normalizeCodexModelOptions( - model: string | null | undefined, - modelOptions: CodexModelOptions | null | undefined, -): CodexModelOptions | undefined { - const caps = getCodexModelCapabilities(model); - const defaultReasoningEffort = getDefaultEffort(caps); - const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort; - const fastModeEnabled = modelOptions?.fastMode === true; - const nextOptions: CodexModelOptions = { - ...(reasoningEffort && reasoningEffort !== defaultReasoningEffort - ? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] } - : {}), - ...(fastModeEnabled ? { fastMode: true } : {}), - }; - return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; -} - export function parseAuthStatusFromOutput(result: CommandResult): { readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: Pick; readonly message?: string; } { const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); @@ -176,7 +183,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): { ) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Codex CLI authentication status command is unavailable in this Codex version.", }; } @@ -190,7 +197,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): { ) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Codex CLI is not authenticated. Run `codex login` and try again.", }; } @@ -211,31 +218,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): { })(); if (parsedAuth.auth === true) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } if (parsedAuth.auth === false) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Codex CLI is not authenticated. Run `codex login` and try again.", }; } if (parsedAuth.attemptedJsonParse) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Could not verify Codex authentication status from JSON output (missing auth marker).", }; } if (result.code === 0) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } const detail = detailFromResult(result); return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: detail ? `Could not verify Codex authentication status. ${detail}` : "Could not verify Codex authentication status.", @@ -284,9 +291,23 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe( Effect.orElseSucceed(() => false), ); +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +const probeCodexCapabilities = (input: { + readonly binaryPath: string; + readonly homePath?: string; +}) => + Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe( + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); + const runCodexCommand = (args: ReadonlyArray) => Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const settingsService = yield* ServerSettingsService; const codexSettings = yield* settingsService.getSettings.pipe( Effect.map((settings) => settings.providers.codex), @@ -298,193 +319,91 @@ const runCodexCommand = (args: ReadonlyArray) => ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), }, }); + return yield* spawnAndCollect(codexSettings.binaryPath, command); + }); - const child = yield* spawner.spawn(command); - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectStreamAsString(child.stdout), - collectStreamAsString(child.stderr), - child.exitCode.pipe(Effect.map(Number)), - ], - { concurrency: "unbounded" }, - ); +export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + resolveAccount?: (input: { + readonly binaryPath: string; + readonly homePath?: string; + }) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ServerSettingsService +> { + const codexSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.codex), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels); - return { stdout, stderr, code: exitCode } satisfies CommandResult; - }).pipe(Effect.scoped); + if (!codexSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex is disabled in T3 Code settings.", + }, + }); + } -export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")( - function* (): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - | ChildProcessSpawner.ChildProcessSpawner - | FileSystem.FileSystem - | Path.Path - | ServerSettingsService - > { - const codexSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.codex), - ); - const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - codexSettings.customModels, - ); + const versionProbe = yield* runCodexCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); - if (!codexSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - enabled: false, - checkedAt, - models, - probe: { - installed: false, - version: null, - status: "warning", - authStatus: "unknown", - message: "Codex is disabled in T3 Code settings.", - }, - }); - } + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Codex CLI (`codex`) is not installed or not on PATH." + : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } - const versionProbe = yield* runCodexCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: "Codex CLI is installed but failed to run. Timed out while running command.", + }, + }); + } - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - authStatus: "unknown", - message: isCommandMissingCause(error) - ? "Codex CLI (`codex`) is not installed or not on PATH." - : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`, - }, - }); - } - - if (Option.isNone(versionProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: null, - status: "error", - authStatus: "unknown", - message: "Codex CLI is installed but failed to run. Timed out while running command.", - }, - }); - } - - const version = versionProbe.success.value; - const parsedVersion = - parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? - parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: detail - ? `Codex CLI is installed but failed to run. ${detail}` - : "Codex CLI is installed but failed to run.", - }, - }); - } - - if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: formatCodexCliUpgradeMessage(parsedVersion), - }, - }); - } - - if (yield* hasCustomModelProvider) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "ready", - authStatus: "unknown", - message: "Using a custom Codex model provider; OpenAI login check skipped.", - }, - }); - } - - const authProbe = yield* runCodexCommand(["login", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - error instanceof Error - ? `Could not verify Codex authentication status: ${error.message}.` - : "Could not verify Codex authentication status.", - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: "Could not verify Codex authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseAuthStatusFromOutput(authProbe.success.value); + const version = versionProbe.success.value; + const parsedVersion = + parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? + parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, @@ -493,13 +412,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")( probe: { installed: true, version: parsedVersion, - status: parsed.status, - authStatus: parsed.authStatus, - ...(parsed.message ? { message: parsed.message } : {}), + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Codex CLI is installed but failed to run. ${detail}` + : "Codex CLI is installed but failed to run.", }, }); - }, -); + } + + if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "error", + auth: { status: "unknown" }, + message: formatCodexCliUpgradeMessage(parsedVersion), + }, + }); + } + + if (yield* hasCustomModelProvider) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "ready", + auth: { status: "unknown" }, + message: "Using a custom Codex model provider; OpenAI login check skipped.", + }, + }); + } + + const authProbe = yield* runCodexCommand(["login", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + const account = resolveAccount + ? yield* resolveAccount({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + }) + : undefined; + const resolvedModels = adjustCodexModelsForAccount(models, account); + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Codex authentication status: ${error.message}.` + : "Could not verify Codex authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Codex authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseAuthStatusFromOutput(authProbe.success.value); + const authType = codexAuthSubType(account); + const authLabel = codexAuthSubLabel(account); + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authType ? { type: authType } : {}), + ...(authLabel ? { label: authLabel } : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); export const CodexProviderLive = Layer.effect( CodexProvider, @@ -508,8 +530,21 @@ export const CodexProviderLive = Layer.effect( const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const accountProbeCache = yield* Cache.make({ + capacity: 4, + timeToLive: Duration.minutes(5), + lookup: (key: string) => { + const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined]; + return probeCodexCapabilities({ + binaryPath, + ...(homePath ? { homePath } : {}), + }); + }, + }); - const checkProvider = checkCodexProviderStatus().pipe( + const checkProvider = checkCodexProviderStatus((input) => + Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])), + ).pipe( Effect.provideService(ServerSettingsService, serverSettings), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index bed25977d6..116c008d67 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -173,7 +173,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "authenticated"); + assert.strictEqual(status.auth.status, "authenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -186,58 +186,186 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); - it.effect("inherits PATH when launching the codex probe with a CODEX_HOME override", () => + it.effect("returns the codex plan type in auth and keeps spark for supported plans", () => Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-bin-", - }); - const codexPath = path.join(binDir, "codex"); - yield* fileSystem.writeFileString( - codexPath, - [ - "#!/bin/sh", - 'if [ "$1" = "--version" ]; then', - ' echo "codex-cli 1.0.0"', - " exit 0", - "fi", - 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then', - ' echo "Logged in using ChatGPT"', - " exit 0", - "fi", - 'echo "unexpected args: $*" >&2', - "exit 1", - "", - ].join("\n"), + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "pro" as const, + sparkEnabled: true, + }), ); - yield* fileSystem.chmod(codexPath, 0o755); - const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-home-", - }); - const previousPath = process.env.PATH; - process.env.PATH = binDir; - try { - const serverSettingsLayer = ServerSettingsService.layerTest({ - providers: { - codex: { - homePath: customCodexHome, - }, - }, + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "pro"); + assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + true, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for unsupported chatgpt plans", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "plus" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "plus"); + assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "team" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.auth.type, "team"); + assert.strictEqual(status.auth.label, "ChatGPT Team Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for codex api key auth", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "apiKey" as const, + planType: null, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "OpenAI API Key"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect.skipIf(process.platform === "win32")( + "inherits PATH when launching the codex probe with a CODEX_HOME override", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-test-codex-bin-", }); - - const status = yield* checkCodexProviderStatus().pipe( - Effect.provide(serverSettingsLayer), + const codexPath = path.join(binDir, "codex"); + yield* fileSystem.writeFileString( + codexPath, + [ + "#!/bin/sh", + 'if [ "$1" = "--version" ]; then', + ' echo "codex-cli 1.0.0"', + " exit 0", + "fi", + 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then', + ' echo "Logged in using ChatGPT"', + " exit 0", + "fi", + 'echo "unexpected args: $*" >&2', + "exit 1", + "", + ].join("\n"), ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.authStatus, "authenticated"); - } finally { - process.env.PATH = previousPath; - } - }), + yield* fileSystem.chmod(codexPath, 0o755); + const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-test-codex-home-", + }); + const previousPath = process.env.PATH; + process.env.PATH = binDir; + + try { + const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + codex: { + homePath: customCodexHome, + }, + }, + }); + + const status = yield* checkCodexProviderStatus().pipe( + Effect.provide(serverSettingsLayer), + ); + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.installed, true); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + } finally { + process.env.PATH = previousPath; + } + }), ); it.effect("returns unavailable when codex is missing", () => @@ -247,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI (`codex`) is not installed or not on PATH.", @@ -262,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", @@ -285,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Codex CLI is not authenticated. Run `codex login` and try again.", @@ -311,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Codex CLI is not authenticated. Run `codex login` and try again.", @@ -336,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "warning"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI authentication status command is unavailable in this Codex version.", @@ -364,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status: "ready", enabled: true, installed: true, - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], @@ -374,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status: "warning", enabled: true, installed: true, - authStatus: "unknown", + auth: { status: "unknown" }, checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], @@ -492,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Using a custom Codex model provider; OpenAI login check skipped.", @@ -535,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const status = yield* checkCodexProviderStatus(); // The auth probe runs and sees "not logged in" → error assert.strictEqual(status.status, "error"); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -556,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("exit code 0 with no auth markers is ready", () => { const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with authenticated=false is unauthenticated", () => { @@ -566,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.authStatus, "unauthenticated"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); }); it("JSON without auth marker is warning", () => { @@ -576,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.authStatus, "unknown"); + assert.strictEqual(parsed.auth.status, "unknown"); }); }); @@ -713,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "authenticated"); + assert.strictEqual(status.auth.status, "authenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -731,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); + it.effect("returns a display label for claude subscription types", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan")); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "maxplan"); + assert.strictEqual(status.auth.label, "Claude Max Subscription"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for claude api key auth", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "Claude API Key"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"api-key"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + it.effect("returns unavailable when claude is missing", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus(); assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Claude Agent CLI (`claude`) is not installed or not on PATH.", @@ -769,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Claude is not authenticated. Run `claude auth login` and try again.", @@ -797,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -817,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "warning"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Claude Agent authentication status command is unavailable in this version of Claude.", @@ -842,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("exit code 0 with no auth markers is ready", () => { const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with loggedIn=true is authenticated", () => { @@ -852,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with loggedIn=false is unauthenticated", () => { @@ -862,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.authStatus, "unauthenticated"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); }); it("JSON without auth marker is warning", () => { @@ -872,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.authStatus, "unknown"); + assert.strictEqual(parsed.auth.status, "unknown"); }); }); }, diff --git a/apps/server/src/provider/codexAccount.ts b/apps/server/src/provider/codexAccount.ts new file mode 100644 index 0000000000..1db00250f6 --- /dev/null +++ b/apps/server/src/provider/codexAccount.ts @@ -0,0 +1,123 @@ +import type { ServerProviderModel } from "@t3tools/contracts"; + +export type CodexPlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "business" + | "enterprise" + | "edu" + | "unknown"; + +export interface CodexAccountSnapshot { + readonly type: "apiKey" | "chatgpt" | "unknown"; + readonly planType: CodexPlanType | null; + readonly sparkEnabled: boolean; +} + +export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; +export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; +const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set(["pro"]); + +function asObject(value: unknown): Record | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + return value as Record; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot { + const record = asObject(response); + const account = asObject(record?.account) ?? record; + const accountType = asString(account?.type); + + if (accountType === "apiKey") { + return { + type: "apiKey", + planType: null, + sparkEnabled: false, + }; + } + + if (accountType === "chatgpt") { + const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; + return { + type: "chatgpt", + planType, + sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType), + }; + } + + return { + type: "unknown", + planType: null, + sparkEnabled: false, + }; +} + +export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined { + if (account?.type === "apiKey") { + return "apiKey"; + } + + if (account?.type !== "chatgpt") { + return undefined; + } + + return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt"; +} + +export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined { + switch (codexAuthSubType(account)) { + case "apiKey": + return "OpenAI API Key"; + case "chatgpt": + return "ChatGPT Subscription"; + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "business": + return "ChatGPT Business Subscription"; + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + default: + return undefined; + } +} + +export function adjustCodexModelsForAccount( + baseModels: ReadonlyArray, + account: CodexAccountSnapshot | undefined, +): ReadonlyArray { + if (account?.sparkEnabled !== false) { + return baseModels; + } + + return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL); +} + +export function resolveCodexModelForAccount( + model: string | undefined, + account: CodexAccountSnapshot, +): string | undefined { + if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { + return model; + } + + return CODEX_DEFAULT_MODEL; +} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts new file mode 100644 index 0000000000..d25fc3533e --- /dev/null +++ b/apps/server/src/provider/codexAppServer.ts @@ -0,0 +1,154 @@ +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; +import readline from "node:readline"; +import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount"; + +interface JsonRpcProbeResponse { + readonly id?: unknown; + readonly result?: unknown; + readonly error?: { + readonly message?: unknown; + }; +} + +function readErrorMessage(response: JsonRpcProbeResponse): string | undefined { + return typeof response.error?.message === "string" ? response.error.message : undefined; +} + +export function buildCodexInitializeParams() { + return { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, + }, + } as const; +} + +export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void { + if (process.platform === "win32" && child.pid !== undefined) { + try { + spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); + return; + } catch { + // Fall through to direct kill when taskkill is unavailable. + } + } + + child.kill(); +} + +export async function probeCodexAccount(input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly signal?: AbortSignal; +}): Promise { + return await new Promise((resolve, reject) => { + const child = spawn(input.binaryPath, ["app-server"], { + env: { + ...process.env, + ...(input.homePath ? { CODEX_HOME: input.homePath } : {}), + }, + stdio: ["pipe", "pipe", "pipe"], + shell: process.platform === "win32", + }); + const output = readline.createInterface({ input: child.stdout }); + + let completed = false; + + const cleanup = () => { + output.removeAllListeners(); + output.close(); + child.removeAllListeners(); + if (!child.killed) { + killCodexChildProcess(child); + } + }; + + const finish = (callback: () => void) => { + if (completed) return; + completed = true; + cleanup(); + callback(); + }; + + const fail = (error: unknown) => + finish(() => + reject( + error instanceof Error + ? error + : new Error(`Codex account probe failed: ${String(error)}.`), + ), + ); + + if (input.signal?.aborted) { + fail(new Error("Codex account probe aborted.")); + return; + } + input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted."))); + + const writeMessage = (message: unknown) => { + if (!child.stdin.writable) { + fail(new Error("Cannot write to codex app-server stdin.")); + return; + } + + child.stdin.write(`${JSON.stringify(message)}\n`); + }; + + output.on("line", (line) => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + fail(new Error("Received invalid JSON from codex app-server during account probe.")); + return; + } + + if (!parsed || typeof parsed !== "object") { + return; + } + + const response = parsed as JsonRpcProbeResponse; + if (response.id === 1) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`initialize failed: ${errorMessage}`)); + return; + } + + writeMessage({ method: "initialized" }); + writeMessage({ id: 2, method: "account/read", params: {} }); + return; + } + + if (response.id === 2) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`account/read failed: ${errorMessage}`)); + return; + } + + finish(() => resolve(readCodexAccountSnapshot(response.result))); + } + }); + + child.once("error", fail); + child.once("exit", (code, signal) => { + if (completed) return; + fail( + new Error( + `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`, + ), + ); + }); + + writeMessage({ + id: 1, + method: "initialize", + params: buildCodexInitializeParams(), + }); + }); +} 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/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index 19111b0485..e1243c4bd0 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -1,11 +1,13 @@ import type { ServerProvider, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; import { Effect, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { normalizeModelSlug } from "@t3tools/shared/model"; +import { isWindowsCommandNotFound } from "../processRunner"; export const DEFAULT_TIMEOUT_MS = 4_000; @@ -19,7 +21,7 @@ export interface ProviderProbeResult { readonly installed: boolean; readonly version: string | null; readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: ServerProviderAuth; readonly message?: string; } @@ -35,6 +37,26 @@ export function isCommandMissingCause(error: unknown): boolean { return lower.includes("enoent") || lower.includes("notfound"); } +export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn(command); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectStreamAsString(child.stdout), + collectStreamAsString(child.stderr), + child.exitCode.pipe(Effect.map(Number)), + ], + { concurrency: "unbounded" }, + ); + + const result: CommandResult = { stdout, stderr, code: exitCode }; + if (isWindowsCommandNotFound(exitCode, stderr)) { + return yield* Effect.fail(new Error(`spawn ${binaryPath} ENOENT`)); + } + return result; + }).pipe(Effect.scoped); + export function detailFromResult( result: CommandResult & { readonly timedOut?: boolean }, ): string | undefined { @@ -115,7 +137,7 @@ export function buildServerProvider(input: { installed: input.probe.installed, version: input.probe.version, status: input.enabled ? input.probe.status : "disabled", - authStatus: input.probe.authStatus, + auth: input.probe.auth, checkedAt: input.checkedAt, ...(input.probe.message ? { message: input.probe.message } : {}), models: input.models, 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..6ce11c8b6a --- /dev/null +++ b/apps/server/src/server.ts @@ -0,0 +1,236 @@ +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 { ProjectionTurnRepositoryLive } from "./persistence/Layers/ProjectionTurns"; +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(ProjectionTurnRepositoryLive), + 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.test.ts b/apps/server/src/serverSettings.test.ts index f26fece246..c0aec009a0 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -104,6 +104,43 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("preserves model when switching providers via textGenerationModelSelection", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + // Start with Claude text generation selection + yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "high", + }, + }, + }); + + // Switch to Codex — the stale Claude "effort" in options must not + // cause the update to lose the selected model. + const next = yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("trims provider path settings when updates are applied", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index f638e7fdfa..79fdc29a8b 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 { @@ -27,6 +28,7 @@ import { FileSystem, Layer, Path, + Equal, PubSub, Ref, Schema, @@ -34,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 { 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; @@ -130,9 +120,12 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings }; } +// Values under these keys are compared as a whole — never stripped field-by-field. +const ATOMIC_SETTINGS_KEYS: ReadonlySet = new Set(["textGenerationModelSelection"]); + function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined { if (Array.isArray(current) || Array.isArray(defaults)) { - return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current; + return Equal.equals(current, defaults) ? undefined : current; } if ( @@ -146,9 +139,15 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow const next: Record = {}; for (const key of Object.keys(currentRecord)) { - const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]); - if (stripped !== undefined) { - next[key] = stripped; + if (ATOMIC_SETTINGS_KEYS.has(key)) { + if (!Equal.equals(currentRecord[key], defaultsRecord[key])) { + next[key] = currentRecord[key]; + } + } else { + const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]); + if (stripped !== undefined) { + next[key] = stripped; + } } } @@ -205,6 +204,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/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 53ee7d74f1..ccdd477178 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -1,24 +1,38 @@ -import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput, type TerminalRestartInput, } from "@t3tools/contracts"; -import { afterEach, describe, expect, it } from "vitest"; - import { - PtySpawnError, + Duration, + Effect, + Encoding, + Exit, + Fiber, + FileSystem, + Option, + PlatformError, + Ref, + Schedule, + Scope, +} from "effect"; +import { TestClock } from "effect/testing"; +import { expect } from "vitest"; + +import type { TerminalManagerShape } from "../Services/Manager"; +import { type PtyAdapterShape, type PtyExitEvent, type PtyProcess, type PtySpawnInput, + PtySpawnError, } from "../Services/PTY"; -import { TerminalManagerRuntime } from "./Manager"; -import { Effect, Encoding } from "effect"; +import { makeTerminalManagerWithOptions } from "./Manager"; class FakePtyProcess implements PtyProcess { readonly writes: string[] = []; @@ -107,27 +121,29 @@ class FakePtyAdapter implements PtyAdapterShape { } } -function waitFor(predicate: () => boolean, timeoutMs = 800): Promise { - const started = Date.now(); - return new Promise((resolve, reject) => { - const poll = () => { - if (predicate()) { - resolve(); - return; - } - if (Date.now() - started > timeoutMs) { - reject(new Error("Timed out waiting for condition")); - return; - } - setTimeout(poll, 15); - }; - poll(); - }); -} +const waitFor = ( + predicate: Effect.Effect, + timeout: Duration.Input = 800, +): Effect.Effect => + predicate.pipe( + Effect.filterOrFail( + (done) => done, + () => new Error("Condition not met"), + ), + Effect.retry(Schedule.spaced("15 millis")), + Effect.timeoutOption(timeout), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => Effect.fail(new Error("Timed out waiting for condition")), + onSome: () => Effect.void, + }), + ), + ); function openInput(overrides: Partial = {}): TerminalOpenInput { return { threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, cwd: process.cwd(), cols: 100, rows: 24, @@ -138,6 +154,7 @@ function openInput(overrides: Partial = {}): TerminalOpenInpu function restartInput(overrides: Partial = {}): TerminalRestartInput { return { threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, cwd: process.cwd(), cols: 100, rows: 24, @@ -169,598 +186,777 @@ function multiTerminalHistoryLogPath( return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId)); } -describe("TerminalManager", () => { - const tempDirs: string[] = []; +interface CreateManagerOptions { + shellResolver?: () => string; + subprocessChecker?: (terminalPid: number) => Effect.Effect; + subprocessPollIntervalMs?: number; + processKillGraceMs?: number; + maxRetainedInactiveSessions?: number; + ptyAdapter?: FakePtyAdapter; +} - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); +interface ManagerFixture { + readonly baseDir: string; + readonly logsDir: string; + readonly ptyAdapter: FakePtyAdapter; + readonly manager: TerminalManagerShape; + readonly getEvents: Effect.Effect>; +} - function makeManager( - historyLineLimit = 5, - options: { - shellResolver?: () => string; - subprocessChecker?: (terminalPid: number) => Promise; - subprocessPollIntervalMs?: number; - processKillGraceMs?: number; - maxRetainedInactiveSessions?: number; - ptyAdapter?: FakePtyAdapter; - } = {}, - ) { - const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-")); - tempDirs.push(logsDir); - const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter(); - const manager = new TerminalManagerRuntime({ - logsDir, - ptyAdapter, - historyLineLimit, - shellResolver: options.shellResolver ?? (() => "/bin/bash"), - ...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}), - ...(options.subprocessPollIntervalMs - ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } - : {}), - ...(options.processKillGraceMs ? { processKillGraceMs: options.processKillGraceMs } : {}), - ...(options.maxRetainedInactiveSessions - ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } - : {}), - }); - return { logsDir, ptyAdapter, manager }; - } +const createManager = ( + historyLineLimit = 5, + options: CreateManagerOptions = {}, +): Effect.Effect< + ManagerFixture, + PlatformError.PlatformError, + FileSystem.FileSystem | Scope.Scope +> => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + Effect.gen(function* () { + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" }); + const logsDir = path.join(baseDir, "userdata", "logs", "terminals"); + const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter(); - it("spawns lazily and reuses running terminal per thread", async () => { - const { manager, ptyAdapter } = makeManager(); - const [first, second] = await Promise.all([ - manager.open(openInput()), - manager.open(openInput()), - ]); - const third = await manager.open(openInput()); + const manager = yield* makeTerminalManagerWithOptions({ + logsDir, + historyLineLimit, + ptyAdapter, + ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), + ...(options.subprocessChecker !== undefined + ? { subprocessChecker: options.subprocessChecker } + : {}), + ...(options.subprocessPollIntervalMs !== undefined + ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } + : {}), + ...(options.processKillGraceMs !== undefined + ? { processKillGraceMs: options.processKillGraceMs } + : {}), + ...(options.maxRetainedInactiveSessions !== undefined + ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } + : {}), + }); + const eventsRef = yield* Ref.make>([]); + const scope = yield* Effect.scope; + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(eventsRef, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); - expect(first.threadId).toBe("thread-1"); - expect(first.terminalId).toBe("default"); - expect(second.threadId).toBe("thread-1"); - expect(third.threadId).toBe("thread-1"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); + return { + baseDir, + logsDir, + ptyAdapter, + manager, + getEvents: Ref.get(eventsRef), + }; + }), + ); - manager.dispose(); - }); +it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => { + it.effect("spawns lazily and reuses running terminal per thread", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const [first, second] = yield* Effect.all( + [manager.open(openInput()), manager.open(openInput())], + { concurrency: "unbounded" }, + ); + const third = yield* manager.open(openInput()); - it("supports asynchronous PTY spawn effects", async () => { - const { manager, ptyAdapter } = makeManager(5, { ptyAdapter: new FakePtyAdapter("async") }); + assert.equal(first.threadId, "thread-1"); + assert.equal(first.terminalId, "default"); + assert.equal(second.threadId, "thread-1"); + assert.equal(third.threadId, "thread-1"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); - const snapshot = await manager.open(openInput()); - - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); - expect(ptyAdapter.processes).toHaveLength(1); - - manager.dispose(); - }); - - it("forwards write and resize to active pty process", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.write({ threadId: "thread-1", data: "ls\n" }); - await manager.resize({ threadId: "thread-1", cols: 120, rows: 30 }); - - expect(process.writes).toEqual(["ls\n"]); - expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); - - manager.dispose(); - }); - - it("resizes running terminal on open when a different size is requested", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ cols: 100, rows: 24 })); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.open(openInput({ cols: 140, rows: 40 })); - - expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]); - - manager.dispose(); - }); - - it("preserves existing terminal size on open when size is omitted", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ cols: 100, rows: 24 })); - const ptyProcess = ptyAdapter.processes[0]; - expect(ptyProcess).toBeDefined(); - if (!ptyProcess) return; - - await manager.open({ - threadId: "thread-1", - cwd: globalThis.process.cwd(), - }); - - expect(ptyProcess.resizeCalls).toEqual([]); - - ptyProcess.emitExit({ exitCode: 0, signal: 0 }); - await manager.open({ - threadId: "thread-1", - cwd: globalThis.process.cwd(), - }); - - const resumedSpawn = ptyAdapter.spawnInputs[1]; - expect(resumedSpawn).toBeDefined(); - if (!resumedSpawn) return; - expect(resumedSpawn.cols).toBe(100); - expect(resumedSpawn.rows).toBe(24); - - manager.dispose(); - }); - - it("uses default dimensions when opening a new terminal without size hints", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open({ - threadId: "thread-1", - cwd: process.cwd(), - }); - - const spawned = ptyAdapter.spawnInputs[0]; - expect(spawned).toBeDefined(); - if (!spawned) return; - expect(spawned.cols).toBe(120); - expect(spawned.rows).toBe(30); - - manager.dispose(); - }); - - it("supports multiple terminals per thread with isolated sessions", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "term-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); - await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - - expect(first.writes).toEqual(["pwd\n"]); - expect(second.writes).toEqual(["ls\n"]); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - - manager.dispose(); - }); - - it("clears transcript and emits cleared event", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - await manager.clear({ threadId: "thread-1" }); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - expect(events.some((event) => event.type === "cleared")).toBe(true); - expect( - events.some( - (event) => - event.type === "cleared" && - event.threadId === "thread-1" && - event.terminalId === "default", - ), - ).toBe(true); - - manager.dispose(); - }); - - it("restarts terminal with empty transcript and respawns pty", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const firstProcess = ptyAdapter.processes[0]; - expect(firstProcess).toBeDefined(); - if (!firstProcess) return; - firstProcess.emitData("before restart\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - const snapshot = await manager.restart(restartInput()); - expect(snapshot.history).toBe(""); - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - manager.dispose(); - }); - - it("emits exited event and reopens with clean transcript after exit", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("old data\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - process.emitExit({ exitCode: 0, signal: 0 }); - - await waitFor(() => events.some((event) => event.type === "exited")); - const reopened = await manager.open(openInput()); - - expect(reopened.history).toBe(""); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - expect(fs.readFileSync(historyLogPath(logsDir), "utf8")).toBe(""); - - manager.dispose(); - }); - - it("ignores trailing writes after terminal exit", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitExit({ exitCode: 0, signal: 0 }); - - await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined(); - expect(process.writes).toEqual([]); - - manager.dispose(); - }); - - it("emits subprocess activity events when child-process state changes", async () => { - let hasRunningSubprocess = false; - const { manager } = makeManager(5, { - subprocessChecker: async () => hasRunningSubprocess, - subprocessPollIntervalMs: 20, - }); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - - await manager.open(openInput()); - await waitFor(() => events.some((event) => event.type === "started")); - expect(events.some((event) => event.type === "activity")).toBe(false); - - hasRunningSubprocess = true; - await waitFor( - () => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true), - 1_200, + const makeDirectory = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.makeDirectory(filePath, { recursive: true }), ); - hasRunningSubprocess = false; - await waitFor( - () => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false), - 1_200, + const chmod = (filePath: string, mode: number) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.chmod(filePath, mode)); + + const pathExists = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath)); + + const readFileString = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.readFileString(filePath)); + + const writeFileString = (filePath: string, contents: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.writeFileString(filePath, contents), ); - manager.dispose(); - }); + it.effect("preserves non-notFound cwd stat failures", () => + Effect.gen(function* () { + const { manager, baseDir } = yield* createManager(); + const blockedRoot = path.join(baseDir, "blocked-root"); + const blockedCwd = path.join(blockedRoot, "cwd"); + yield* makeDirectory(blockedCwd); + yield* chmod(blockedRoot, 0o000); - it("caps persisted history to configured line limit", async () => { - const { manager, ptyAdapter } = makeManager(3); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const error = yield* Effect.flip(manager.open(openInput({ cwd: blockedCwd }))).pipe( + Effect.ensuring(chmod(blockedRoot, 0o755).pipe(Effect.ignore)), + ); - process.emitData("line1\nline2\nline3\nline4\n"); - await manager.close({ threadId: "thread-1" }); + expect(error).toMatchObject({ + _tag: "TerminalCwdError", + cwd: blockedCwd, + reason: "statFailed", + }); + }), + ); - const reopened = await manager.open(openInput()); - const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); - expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); + it.effect("supports asynchronous PTY spawn effects", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); - manager.dispose(); - }); + const snapshot = yield* manager.open(openInput()); - it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + expect(ptyAdapter.processes).toHaveLength(1); + }), + ); - process.emitData("prompt "); - process.emitData("\u001b[32mok\u001b[0m "); - process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); - process.emitData("\u001b[1;1R"); - process.emitData("done\n"); + it.effect("forwards write and resize to active pty process", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - await manager.close({ threadId: "thread-1" }); + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "ls\n", + }); + yield* manager.resize({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cols: 120, + rows: 30, + }); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n"); + expect(process.writes).toEqual(["ls\n"]); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); - manager.dispose(); - }); + it.effect("resizes running terminal on open when a different size is requested", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ cols: 100, rows: 24 })); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const reopened = yield* manager.open(openInput({ cols: 120, rows: 30 })); - process.emitData("before clear\n"); - process.emitData("\u001b[H\u001b[2J"); - process.emitData("prompt "); - process.emitData("\u001b]11;"); - process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); - process.emitData("R\u001b[36mdone\u001b[0m\n"); + assert.equal(reopened.status, "running"); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); - await manager.close({ threadId: "thread-1" }); + it.effect("supports multiple terminals per thread independently", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "term-2" })); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe( - "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", - ); + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; - manager.dispose(); - }); + yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); + yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - it("does not leak final bytes from ESC sequences with intermediate bytes", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + expect(first.writes).toEqual(["pwd\n"]); + expect(second.writes).toEqual(["ls\n"]); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + }), + ); - process.emitData("before "); - process.emitData("\u001b(B"); - process.emitData("after\n"); + it.effect("clears transcript and emits cleared event", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - await manager.close({ threadId: "thread-1" }); + process.emitData("hello\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("before \u001b(Bafter\n"); - - manager.dispose(); - }); - - it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before "); - process.emitData("\u001b("); - process.emitData("Bafter\n"); - - await manager.close({ threadId: "thread-1" }); - - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("before \u001b(Bafter\n"); - - manager.dispose(); - }); - - it("deletes history file when close(deleteHistory=true)", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("bye\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - expect(fs.existsSync(historyLogPath(logsDir))).toBe(false); - - manager.dispose(); - }); - - it("closes all terminals for a thread when close omits terminalId", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "sidecar" })); - const defaultProcess = ptyAdapter.processes[0]; - const sidecarProcess = ptyAdapter.processes[1]; - expect(defaultProcess).toBeDefined(); - expect(sidecarProcess).toBeDefined(); - if (!defaultProcess || !sidecarProcess) return; - - defaultProcess.emitData("default\n"); - sidecarProcess.emitData("sidecar\n"); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - - expect(defaultProcess.killed).toBe(true); - expect(sidecarProcess.killed).toBe(true); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false); - - manager.dispose(); - }); - - it("escalates terminal shutdown to SIGKILL when process does not exit in time", async () => { - const { manager, ptyAdapter } = makeManager(5, { processKillGraceMs: 10 }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.close({ threadId: "thread-1" }); - await waitFor(() => process.killSignals.includes("SIGKILL")); - - expect(process.killSignals[0]).toBe("SIGTERM"); - expect(process.killSignals).toContain("SIGKILL"); - - manager.dispose(); - }); - - it("evicts oldest inactive terminal sessions when retention limit is exceeded", async () => { - const { manager, ptyAdapter } = makeManager(5, { maxRetainedInactiveSessions: 1 }); - - await manager.open(openInput({ threadId: "thread-1" })); - await manager.open(openInput({ threadId: "thread-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - first.emitExit({ exitCode: 0, signal: 0 }); - await new Promise((resolve) => setTimeout(resolve, 5)); - second.emitExit({ exitCode: 0, signal: 0 }); - - await waitFor(() => { - const sessions = (manager as unknown as { sessions: Map }).sessions; - return sessions.size === 1; - }); - - const sessions = (manager as unknown as { sessions: Map }).sessions; - const keys = [...sessions.keys()]; - expect(keys).toEqual(["thread-2\u0000default"]); - - manager.dispose(); - }); - - it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => { - const { manager, logsDir } = makeManager(); - const legacyPath = path.join(logsDir, "thread-1.log"); - const nextPath = historyLogPath(logsDir); - fs.writeFileSync(legacyPath, "legacy-line\n", "utf8"); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.history).toBe("legacy-line\n"); - expect(fs.existsSync(nextPath)).toBe(true); - expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n"); - expect(fs.existsSync(legacyPath)).toBe(false); - - manager.dispose(); - }); - - it("retries with fallback shells when preferred shell spawn fails", async () => { - const { manager, ptyAdapter } = makeManager(5, { - shellResolver: () => "/definitely/missing-shell -l", - }); - ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); - expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); - - if (process.platform === "win32") { + const events = yield* getEvents; + expect(events.some((event) => event.type === "cleared")).toBe(true); expect( - ptyAdapter.spawnInputs.some( - (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", + events.some( + (event) => + event.type === "cleared" && + event.threadId === "thread-1" && + event.terminalId === "default", ), ).toBe(true); - } else { - expect( - ptyAdapter.spawnInputs.some((input) => - ["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell), + }), + ); + + it.effect("restarts terminal with empty transcript and respawns pty", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const firstProcess = ptyAdapter.processes[0]; + expect(firstProcess).toBeDefined(); + if (!firstProcess) return; + firstProcess.emitData("before restart\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + const snapshot = yield* manager.restart(restartInput()); + assert.equal(snapshot.history, ""); + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + }), + ); + + it.effect("emits exited event and reopens with clean transcript after exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("old data\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + const reopened = yield* manager.open(openInput()); + + assert.equal(reopened.history, ""); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + expect(yield* readFileString(historyLogPath(logsDir))).toBe(""); + }), + ); + + it.effect("ignores trailing writes after terminal exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "\r", + }); + expect(process.writes).toEqual([]); + }), + ); + + it.effect("emits subprocess activity events when child-process state changes", () => + Effect.gen(function* () { + let hasRunningSubprocess = false; + const { manager, getEvents } = yield* createManager(5, { + subprocessChecker: () => Effect.succeed(hasRunningSubprocess), + subprocessPollIntervalMs: 20, + }); + + yield* manager.open(openInput()); + expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false); + + hasRunningSubprocess = true; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true), ), - ).toBe(true); - } + "1200 millis", + ); - manager.dispose(); - }); + hasRunningSubprocess = false; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false), + ), + "1200 millis", + ); + }), + ); - it("filters app runtime env variables from terminal sessions", async () => { - const originalValues = new Map(); - const setEnv = (key: string, value: string | undefined) => { - if (!originalValues.has(key)) { - originalValues.set(key, process.env[key]); + it.effect("does not invoke subprocess polling until a terminal session is running", () => + Effect.gen(function* () { + let checks = 0; + const { manager } = yield* createManager(5, { + subprocessChecker: () => { + checks += 1; + return Effect.succeed(false); + }, + subprocessPollIntervalMs: 20, + }); + + yield* Effect.sleep("80 millis"); + assert.equal(checks, 0); + + yield* manager.open(openInput()); + yield* waitFor( + Effect.sync(() => checks > 0), + "1200 millis", + ); + }), + ); + + it.effect("caps persisted history to configured line limit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(3); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("line1\nline2\nline3\nline4\n"); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); + expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); + }), + ); + + it.effect("strips replay-unsafe terminal query and reply sequences from persisted history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("prompt "); + process.emitData("\u001b[32mok\u001b[0m "); + process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); + process.emitData("\u001b[1;1R"); + process.emitData("done\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "prompt \u001b[32mok\u001b[0m done\n"); + }), + ); + + it.effect( + "preserves clear and style control sequences while dropping chunk-split query traffic", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before clear\n"); + process.emitData("\u001b[H\u001b[2J"); + process.emitData("prompt "); + process.emitData("\u001b]11;"); + process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); + process.emitData("R\u001b[36mdone\u001b[0m\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal( + reopened.history, + "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", + ); + }), + ); + + it.effect("does not leak final bytes from ESC sequences with intermediate bytes", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b(B"); + process.emitData("after\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect( + "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b("); + process.emitData("Bafter\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect("deletes history file when close(deleteHistory=true)", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("bye\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + expect(yield* pathExists(historyLogPath(logsDir))).toBe(false); + }), + ); + + it.effect("closes all terminals for a thread when close omits terminalId", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "sidecar" })); + const defaultProcess = ptyAdapter.processes[0]; + const sidecarProcess = ptyAdapter.processes[1]; + expect(defaultProcess).toBeDefined(); + expect(sidecarProcess).toBeDefined(); + if (!defaultProcess || !sidecarProcess) return; + + defaultProcess.emitData("default\n"); + sidecarProcess.emitData("sidecar\n"); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + + assert.equal(defaultProcess.killed, true); + assert.equal(sidecarProcess.killed, true); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe( + false, + ); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe( + false, + ); + }), + ); + + it.effect("escalates terminal shutdown to SIGKILL when process does not exit in time", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10 }); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeFiber = yield* manager.close({ threadId: "thread-1" }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeFiber); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("evicts oldest inactive terminal sessions when retention limit is exceeded", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(5, { + maxRetainedInactiveSessions: 1, + }); + + yield* manager.open(openInput({ threadId: "thread-1" })); + yield* manager.open(openInput({ threadId: "thread-2" })); + + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; + + first.emitData("first-history\n"); + second.emitData("second-history\n"); + yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1"))); + first.emitExit({ exitCode: 0, signal: 0 }); + yield* Effect.sleep(Duration.millis(5)); + second.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map( + getEvents, + (events) => events.filter((event) => event.type === "exited").length === 2, + ), + ); + + const reopenedSecond = yield* manager.open(openInput({ threadId: "thread-2" })); + const reopenedFirst = yield* manager.open(openInput({ threadId: "thread-1" })); + + assert.equal(reopenedFirst.history, "first-history\n"); + assert.equal(reopenedSecond.history, ""); + }), + ); + + it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () => + Effect.gen(function* () { + const { manager, logsDir } = yield* createManager(); + const legacyPath = path.join(logsDir, "thread-1.log"); + const nextPath = historyLogPath(logsDir); + yield* writeFileString(legacyPath, "legacy-line\n"); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.history, "legacy-line\n"); + expect(yield* pathExists(nextPath)).toBe(true); + expect(yield* readFileString(nextPath)).toBe("legacy-line\n"); + expect(yield* pathExists(legacyPath)).toBe(false); + }), + ); + + it.effect("retries with fallback shells when preferred shell spawn fails", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/definitely/missing-shell -l", + }); + ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); + expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); + + if (process.platform === "win32") { + expect( + ptyAdapter.spawnInputs.some( + (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", + ), + ).toBe(true); + } else { + expect( + ptyAdapter.spawnInputs + .slice(1) + .some((input) => input.shell !== "/definitely/missing-shell"), + ).toBe(true); } - if (value === undefined) { - delete process.env[key]; - return; - } - process.env[key] = value; - }; - const restoreEnv = () => { - for (const [key, value] of originalValues) { + }), + ); + + it.effect("filters app runtime env variables from terminal sessions", () => + Effect.gen(function* () { + const originalValues = new Map(); + const setEnv = (key: string, value: string | undefined) => { + if (!originalValues.has(key)) { + originalValues.set(key, process.env[key]); + } if (value === undefined) { delete process.env[key]; - } else { - process.env[key] = value; + return; } + process.env[key] = value; + }; + const restoreEnv = () => { + for (const [key, value] of originalValues) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + }; + + setEnv("PORT", "5173"); + setEnv("T3CODE_PORT", "3773"); + setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); + setEnv("TEST_TERMINAL_KEEP", "keep-me"); + + try { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + expect(spawnInput.env.PORT).toBeUndefined(); + expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); + expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); + expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + } finally { + restoreEnv(); } - }; + }), + ); - setEnv("PORT", "5173"); - setEnv("T3CODE_PORT", "3773"); - setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); - setEnv("TEST_TERMINAL_KEEP", "keep-me"); - - try { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); + it.effect("injects runtime env overrides into spawned terminals", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open( + openInput({ + env: { + T3CODE_PROJECT_ROOT: "/repo", + T3CODE_WORKTREE_PATH: "/repo/worktree-a", + CUSTOM_FLAG: "1", + }, + }), + ); const spawnInput = ptyAdapter.spawnInputs[0]; expect(spawnInput).toBeDefined(); if (!spawnInput) return; - expect(spawnInput.env.PORT).toBeUndefined(); - expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); - expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); - expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + assert.equal(spawnInput.env.T3CODE_PROJECT_ROOT, "/repo"); + assert.equal(spawnInput.env.T3CODE_WORKTREE_PATH, "/repo/worktree-a"); + assert.equal(spawnInput.env.CUSTOM_FLAG, "1"); + }), + ); - manager.dispose(); - } finally { - restoreEnv(); - } - }); + it.effect("starts zsh with prompt spacer disabled to avoid `%` end markers", () => + Effect.gen(function* () { + if (process.platform === "win32") return; + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/bin/zsh", + }); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; - it("injects runtime env overrides into spawned terminals", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open( - openInput({ - env: { - T3CODE_PROJECT_ROOT: "/repo", - T3CODE_WORKTREE_PATH: "/repo/worktree-a", - CUSTOM_FLAG: "1", - }, - }), - ); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; + expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); + }), + ); - expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo"); - expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a"); - expect(spawnInput.env.CUSTOM_FLAG).toBe("1"); + it.effect("bridges PTY callbacks back into Effect-managed event streaming", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); - manager.dispose(); - }); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => { - if (process.platform === "win32") return; - const { manager, ptyAdapter } = makeManager(5, { - shellResolver: () => "/bin/zsh", - }); - await manager.open(openInput()); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; + process.emitData("hello from callback\n"); - expect(spawnInput.shell).toBe("/bin/zsh"); - expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "output" && event.data === "hello from callback\n"), + ), + "1200 millis", + ); + }), + ); - manager.dispose(); - }); + it.effect("pushes PTY callbacks to direct event subscribers", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + const scope = yield* Effect.scope; + const subscriberEvents = yield* Ref.make>([]); + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(subscriberEvents, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("hello from subscriber\n"); + + yield* waitFor( + Effect.map(Ref.get(subscriberEvents), (events) => + events.some( + (event) => event.type === "output" && event.data === "hello from subscriber\n", + ), + ), + "1200 millis", + ); + }), + ); + + it.effect("preserves queued PTY output ordering through exit callbacks", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("first\n"); + process.emitData("second\n"); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => { + const relevant = events.filter( + (event) => event.type === "output" || event.type === "exited", + ); + return relevant.length >= 3; + }), + "1200 millis", + ); + + const relevant = (yield* getEvents).filter( + (event) => event.type === "output" || event.type === "exited", + ); + expect(relevant).toEqual([ + expect.objectContaining({ type: "output", data: "first\n" }), + expect.objectContaining({ type: "output", data: "second\n" }), + expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0 }), + ]); + }), + ); + + it.effect("scoped runtime shutdown stops active terminals cleanly", () => + Effect.gen(function* () { + const scope = yield* Scope.make("sequential"); + const { manager, ptyAdapter } = yield* createManager(5, { + processKillGraceMs: 10, + }).pipe(Effect.provideService(Scope.Scope, scope)); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeScope = yield* Scope.close(scope, Exit.void).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeScope); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); }); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index b5085220c2..7ef18b1655 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -1,32 +1,44 @@ -import { EventEmitter } from "node:events"; -import fs from "node:fs"; import path from "node:path"; import { DEFAULT_TERMINAL_ID, - TerminalClearInput, - TerminalCloseInput, - TerminalOpenInput, - TerminalResizeInput, - TerminalRestartInput, - TerminalWriteInput, type TerminalEvent, type TerminalSessionSnapshot, + type TerminalSessionStatus, } from "@t3tools/contracts"; -import { Effect, Encoding, Layer, Schema } from "effect"; - -import { createLogger } from "../../logger"; -import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY"; -import { runProcess } from "../../processRunner"; -import { ServerConfig } from "../../config"; +import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; import { - ShellCandidate, - TerminalError, + Data, + Effect, + Encoding, + Equal, + Exit, + Fiber, + FileSystem, + Layer, + Option, + Scope, + Semaphore, + SynchronizedRef, +} from "effect"; + +import { ServerConfig } from "../../config"; +import { runProcess } from "../../processRunner"; +import { + TerminalCwdError, + TerminalHistoryError, TerminalManager, - TerminalManagerShape, - TerminalSessionState, - TerminalStartInput, + TerminalNotRunningError, + TerminalSessionLookupError, + type TerminalManagerShape, } from "../Services/Manager"; +import { + PtyAdapter, + PtySpawnError, + type PtyAdapterShape, + type PtyExitEvent, + type PtyProcess, +} from "../Services/PTY"; const DEFAULT_HISTORY_LINE_LIMIT = 5_000; const DEFAULT_PERSIST_DEBOUNCE_MS = 40; @@ -37,14 +49,128 @@ const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); -const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput); -const decodeTerminalRestartInput = Schema.decodeUnknownSync(TerminalRestartInput); -const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput); -const decodeTerminalResizeInput = Schema.decodeUnknownSync(TerminalResizeInput); -const decodeTerminalClearInput = Schema.decodeUnknownSync(TerminalClearInput); -const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput); +type TerminalSubprocessChecker = ( + terminalPid: number, +) => Effect.Effect; -type TerminalSubprocessChecker = (terminalPid: number) => Promise; +class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ + readonly message: string; + readonly cause?: unknown; + readonly terminalPid: number; + readonly command: "powershell" | "pgrep" | "ps"; +}> {} + +class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ + readonly message: string; + readonly cause?: unknown; + readonly signal: "SIGTERM" | "SIGKILL"; +}> {} + +interface ShellCandidate { + shell: string; + args?: string[]; +} + +interface TerminalStartInput { + threadId: string; + terminalId: string; + cwd: string; + cols: number; + rows: number; + env?: Record; +} + +interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + pendingProcessEvents: Array; + pendingProcessEventIndex: number; + processEventDrainRunning: boolean; + 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; +} + +interface PersistHistoryRequest { + history: string; + immediate: boolean; +} + +type PendingProcessEvent = { type: "output"; data: string } | { type: "exit"; event: PtyExitEvent }; + +type DrainProcessEventAction = + | { type: "idle" } + | { + type: "output"; + threadId: string; + terminalId: string; + history: string | null; + data: string; + } + | { + type: "exit"; + process: PtyProcess | null; + threadId: string; + terminalId: string; + exitCode: number | null; + exitSignal: number | null; + }; + +interface TerminalManagerState { + sessions: Map; + killFibers: Map>; +} + +function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { + return { + threadId: session.threadId, + terminalId: session.terminalId, + cwd: session.cwd, + status: session.status, + pid: session.pid, + history: session.history, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + updatedAt: session.updatedAt, + }; +} + +function cleanupProcessHandles(session: TerminalSessionState): void { + session.unsubscribeData?.(); + session.unsubscribeData = null; + session.unsubscribeExit?.(); + session.unsubscribeExit = null; +} + +function enqueueProcessEvent( + session: TerminalSessionState, + expectedPid: number, + event: PendingProcessEvent, +): boolean { + if (!session.process || session.status !== "running" || session.pid !== expectedPid) { + return false; + } + + session.pendingProcessEvents.push(event); + if (session.processEventDrainRunning) { + return false; + } + + session.processEventDrainRunning = true; + return true; +} function defaultShellResolver(): string { if (process.platform === "win32") { @@ -118,7 +244,7 @@ function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] { ]); } -function isRetryableShellSpawnError(error: unknown): boolean { +function isRetryableShellSpawnError(error: PtySpawnError): boolean { const queue: unknown[] = [error]; const seen = new Set(); const messages: string[] = []; @@ -165,82 +291,107 @@ function isRetryableShellSpawnError(error: unknown): boolean { ); } -async function checkWindowsSubprocessActivity(terminalPid: number): Promise { +function checkWindowsSubprocessActivity( + terminalPid: number, +): Effect.Effect { const command = [ `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`, "if ($children) { exit 0 }", "exit 1", ].join("; "); - try { - const result = await runProcess( - "powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", command], - { + return Effect.tryPromise({ + try: () => + runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { timeoutMs: 1_500, allowNonZeroExit: true, maxBufferBytes: 32_768, outputMode: "truncate", - }, - ); - return result.code === 0; - } catch { - return false; - } + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to check Windows terminal subprocess activity.", + cause, + terminalPid, + command: "powershell", + }), + }).pipe(Effect.map((result) => result.code === 0)); } -async function checkPosixSubprocessActivity(terminalPid: number): Promise { - try { - const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], { - timeoutMs: 1_000, - allowNonZeroExit: true, - maxBufferBytes: 32_768, - outputMode: "truncate", - }); - if (pgrepResult.code === 0) { - return pgrepResult.stdout.trim().length > 0; +const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* ( + terminalPid: number, +): Effect.fn.Return { + const runPgrep = Effect.tryPromise({ + try: () => + runProcess("pgrep", ["-P", String(terminalPid)], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 32_768, + outputMode: "truncate", + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to inspect terminal subprocesses with pgrep.", + cause, + terminalPid, + command: "pgrep", + }), + }); + + const runPs = Effect.tryPromise({ + try: () => + runProcess("ps", ["-eo", "pid=,ppid="], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 262_144, + outputMode: "truncate", + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to inspect terminal subprocesses with ps.", + cause, + terminalPid, + command: "ps", + }), + }); + + const pgrepResult = yield* Effect.exit(runPgrep); + if (pgrepResult._tag === "Success") { + if (pgrepResult.value.code === 0) { + return pgrepResult.value.stdout.trim().length > 0; } - if (pgrepResult.code === 1) { + if (pgrepResult.value.code === 1) { return false; } - } catch { - // Fall back to ps when pgrep is unavailable. } - try { - const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], { - timeoutMs: 1_000, - allowNonZeroExit: true, - maxBufferBytes: 262_144, - outputMode: "truncate", - }); - if (psResult.code !== 0) { - return false; - } - - for (const line of psResult.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - if (ppid === terminalPid) { - return true; - } - } - return false; - } catch { + const psResult = yield* Effect.exit(runPs); + if (psResult._tag === "Failure" || psResult.value.code !== 0) { return false; } -} -async function defaultSubprocessChecker(terminalPid: number): Promise { + for (const line of psResult.value.stdout.split(/\r?\n/g)) { + const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); + const pid = Number(pidRaw); + const ppid = Number(ppidRaw); + if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; + if (ppid === terminalPid) { + return true; + } + } + return false; +}); + +const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* ( + terminalPid: number, +): Effect.fn.Return { if (!Number.isInteger(terminalPid) || terminalPid <= 0) { return false; } if (process.platform === "win32") { - return checkWindowsSubprocessActivity(terminalPid); + return yield* checkWindowsSubprocessActivity(terminalPid); } - return checkPosixSubprocessActivity(terminalPid); -} + return yield* checkPosixSubprocessActivity(terminalPid); +}); function capHistory(history: string, maxLines: number): string { if (history.length === 0) return history; @@ -482,12 +633,8 @@ function normalizedRuntimeEnv( return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right))); } -interface TerminalManagerEvents { - event: [event: TerminalEvent]; -} - interface TerminalManagerOptions { - logsDir?: string; + logsDir: string; historyLineLimit?: number; ptyAdapter: PtyAdapterShape; shellResolver?: () => string; @@ -497,917 +644,1192 @@ interface TerminalManagerOptions { maxRetainedInactiveSessions?: number; } -export class TerminalManagerRuntime extends EventEmitter { - private readonly sessions = new Map(); - private readonly logsDir: string; - private readonly historyLineLimit: number; - private readonly ptyAdapter: PtyAdapterShape; - private readonly shellResolver: () => string; - private readonly persistQueues = new Map>(); - private readonly persistTimers = new Map>(); - private readonly pendingPersistHistory = new Map(); - private readonly threadLocks = new Map>(); - private readonly persistDebounceMs: number; - private readonly subprocessChecker: TerminalSubprocessChecker; - private readonly subprocessPollIntervalMs: number; - private readonly processKillGraceMs: number; - private readonly maxRetainedInactiveSessions: number; - private subprocessPollTimer: ReturnType | null = null; - private subprocessPollInFlight = false; - private readonly killEscalationTimers = new Map>(); - private readonly logger = createLogger("terminal"); +const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { + const { terminalLogsDir } = yield* ServerConfig; + const ptyAdapter = yield* PtyAdapter; + return yield* makeTerminalManagerWithOptions({ + logsDir: terminalLogsDir, + ptyAdapter, + }); +}); - constructor(options: TerminalManagerOptions) { - super(); - this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals"); - this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; - this.ptyAdapter = options.ptyAdapter; - this.shellResolver = options.shellResolver ?? defaultShellResolver; - this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS; - this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; - this.subprocessPollIntervalMs = +export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWithOptions")( + function* (options: TerminalManagerOptions) { + const fileSystem = yield* FileSystem.FileSystem; + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + + const logsDir = options.logsDir; + const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; + const shellResolver = options.shellResolver ?? defaultShellResolver; + const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; + const subprocessPollIntervalMs = options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; - this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; - this.maxRetainedInactiveSessions = + const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; + const maxRetainedInactiveSessions = options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; - fs.mkdirSync(this.logsDir, { recursive: true }); - } - async open(raw: TerminalOpenInput): Promise { - const input = decodeTerminalOpenInput(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); + yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); - const sessionKey = toSessionKey(input.threadId, input.terminalId); - const existing = this.sessions.get(sessionKey); - if (!existing) { - await this.flushPersistQueue(input.threadId, input.terminalId); - const history = await this.readHistory(input.threadId, input.terminalId); - const cols = input.cols ?? DEFAULT_OPEN_COLS; - const rows = input.rows ?? DEFAULT_OPEN_ROWS; - const session: TerminalSessionState = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history, - pendingHistoryControlSequence: "", - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols, - rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runtimeEnv: normalizedRuntimeEnv(input.env), - }; - this.sessions.set(sessionKey, session); - this.evictInactiveSessionsIfNeeded(); - await this.startSession(session, { ...input, cols, rows }, "started"); - return this.snapshot(session); - } - - const nextRuntimeEnv = normalizedRuntimeEnv(input.env); - const currentRuntimeEnv = existing.runtimeEnv; - const targetCols = input.cols ?? existing.cols; - const targetRows = input.rows ?? existing.rows; - const runtimeEnvChanged = - JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv); - - if (existing.cwd !== input.cwd || runtimeEnvChanged) { - this.stopProcess(existing); - existing.cwd = input.cwd; - existing.runtimeEnv = nextRuntimeEnv; - existing.history = ""; - existing.pendingHistoryControlSequence = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } else if (existing.status === "exited" || existing.status === "error") { - existing.runtimeEnv = nextRuntimeEnv; - existing.history = ""; - existing.pendingHistoryControlSequence = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } else if (currentRuntimeEnv !== nextRuntimeEnv) { - existing.runtimeEnv = nextRuntimeEnv; - } - - if (!existing.process) { - await this.startSession( - existing, - { ...input, cols: targetCols, rows: targetRows }, - "started", - ); - return this.snapshot(existing); - } - - if (existing.cols !== targetCols || existing.rows !== targetRows) { - existing.cols = targetCols; - existing.rows = targetRows; - existing.process.resize(targetCols, targetRows); - existing.updatedAt = new Date().toISOString(); - } - - return this.snapshot(existing); + const managerStateRef = yield* SynchronizedRef.make({ + sessions: new Map(), + killFibers: new Map(), }); - } + const threadLocksRef = yield* SynchronizedRef.make(new Map()); + const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect>(); + const workerScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); - async write(raw: TerminalWriteInput): Promise { - const input = decodeTerminalWriteInput(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - if (session.status === "exited") { - return; + const publishEvent = (event: TerminalEvent) => + Effect.gen(function* () { + for (const listener of terminalEventListeners) { + yield* listener(event).pipe(Effect.ignoreCause({ log: true })); + } + }); + + const historyPath = (threadId: string, terminalId: string) => { + const threadPart = toSafeThreadId(threadId); + if (terminalId === DEFAULT_TERMINAL_ID) { + return path.join(logsDir, `${threadPart}.log`); } - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.process.write(input.data); - } + return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); + }; - async resize(raw: TerminalResizeInput): Promise { - const input = decodeTerminalResizeInput(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.cols = input.cols; - session.rows = input.rows; - session.updatedAt = new Date().toISOString(); - session.process.resize(input.cols, input.rows); - } + const legacyHistoryPath = (threadId: string) => + path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); - async clear(raw: TerminalClearInput): Promise { - const input = decodeTerminalClearInput(raw); - await this.runWithThreadLock(input.threadId, async () => { - const session = this.requireSession(input.threadId, input.terminalId); - session.history = ""; - session.pendingHistoryControlSequence = ""; - session.updatedAt = new Date().toISOString(); - await this.persistHistory(input.threadId, input.terminalId, session.history); - this.emitEvent({ - type: "cleared", - threadId: input.threadId, - terminalId: input.terminalId, - createdAt: new Date().toISOString(), + const toTerminalHistoryError = + (operation: "read" | "truncate" | "migrate", threadId: string, terminalId: string) => + (cause: unknown) => + new TerminalHistoryError({ + operation, + threadId, + terminalId, + cause, + }); + + const readManagerState = SynchronizedRef.get(managerStateRef); + + const modifyManagerState = ( + f: (state: TerminalManagerState) => readonly [A, TerminalManagerState], + ) => SynchronizedRef.modify(managerStateRef, f); + + const getThreadSemaphore = (threadId: string) => + SynchronizedRef.modifyEffect(threadLocksRef, (current) => { + const existing: Option.Option = Option.fromNullishOr( + current.get(threadId), + ); + return Option.match(existing, { + onNone: () => + Semaphore.make(1).pipe( + Effect.map((semaphore) => { + const next = new Map(current); + next.set(threadId, semaphore); + return [semaphore, next] as const; + }), + ), + onSome: (semaphore) => Effect.succeed([semaphore, current] as const), + }); + }); + + const withThreadLock = ( + threadId: string, + effect: Effect.Effect, + ): Effect.Effect => + Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); + + const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* ( + process: PtyProcess | null, + ) { + if (!process) return; + const fiber: Option.Option> = yield* modifyManagerState< + Option.Option> + >((state) => { + const existing: Option.Option> = Option.fromNullishOr( + state.killFibers.get(process), + ); + if (Option.isNone(existing)) { + return [Option.none>(), state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [existing, { ...state, killFibers }] as const; + }); + if (Option.isSome(fiber)) { + yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore); + } + }); + + const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* ( + process: PtyProcess, + fiber: Fiber.Fiber, + ) { + yield* modifyManagerState((state) => { + const killFibers = new Map(state.killFibers); + killFibers.set(process, fiber); + return [undefined, { ...state, killFibers }] as const; }); }); - } - async restart(raw: TerminalRestartInput): Promise { - const input = decodeTerminalRestartInput(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); - - const sessionKey = toSessionKey(input.threadId, input.terminalId); - let session = this.sessions.get(sessionKey); - if (!session) { - const cols = input.cols ?? DEFAULT_OPEN_COLS; - const rows = input.rows ?? DEFAULT_OPEN_ROWS; - session = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history: "", - pendingHistoryControlSequence: "", - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols, - rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runtimeEnv: normalizedRuntimeEnv(input.env), - }; - this.sessions.set(sessionKey, session); - this.evictInactiveSessionsIfNeeded(); - } else { - this.stopProcess(session); - session.cwd = input.cwd; - session.runtimeEnv = normalizedRuntimeEnv(input.env); - } - - const cols = input.cols ?? session.cols; - const rows = input.rows ?? session.rows; - - session.history = ""; - session.pendingHistoryControlSequence = ""; - await this.persistHistory(input.threadId, input.terminalId, session.history); - await this.startSession(session, { ...input, cols, rows }, "restarted"); - return this.snapshot(session); - }); - } - - async close(raw: TerminalCloseInput): Promise { - const input = decodeTerminalCloseInput(raw); - await this.runWithThreadLock(input.threadId, async () => { - if (input.terminalId) { - await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true); - return; - } - - const threadSessions = this.sessionsForThread(input.threadId); - for (const session of threadSessions) { - this.stopProcess(session); - this.sessions.delete(toSessionKey(session.threadId, session.terminalId)); - } - await Promise.all( - threadSessions.map((session) => - this.flushPersistQueue(session.threadId, session.terminalId), + const runKillEscalation = Effect.fn("terminal.runKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const terminated = yield* Effect.try({ + try: () => process.kill("SIGTERM"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGTERM to terminal process.", + cause, + signal: "SIGTERM", + }), + }).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logWarning("failed to kill terminal process", { + threadId, + terminalId, + signal: "SIGTERM", + error: error.message, + }).pipe(Effect.as(false)), ), ); - - if (input.deleteHistory) { - await this.deleteAllHistoryForThread(input.threadId); - } - this.updateSubprocessPollingState(); - }); - } - - dispose(): void { - this.stopSubprocessPolling(); - const sessions = [...this.sessions.values()]; - this.sessions.clear(); - for (const session of sessions) { - this.stopProcess(session); - } - for (const timer of this.persistTimers.values()) { - clearTimeout(timer); - } - this.persistTimers.clear(); - for (const timer of this.killEscalationTimers.values()) { - clearTimeout(timer); - } - this.killEscalationTimers.clear(); - this.pendingPersistHistory.clear(); - this.threadLocks.clear(); - this.persistQueues.clear(); - } - - private async startSession( - session: TerminalSessionState, - input: TerminalStartInput, - eventType: "started" | "restarted", - ): Promise { - this.stopProcess(session); - - session.status = "starting"; - session.cwd = input.cwd; - session.cols = input.cols; - session.rows = input.rows; - session.exitCode = null; - session.exitSignal = null; - session.hasRunningSubprocess = false; - session.updatedAt = new Date().toISOString(); - - let ptyProcess: PtyProcess | null = null; - let startedShell: string | null = null; - try { - const shellCandidates = resolveShellCandidates(this.shellResolver); - const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); - let lastSpawnError: unknown = null; - - const spawnWithCandidate = (candidate: ShellCandidate) => - Effect.runPromise( - this.ptyAdapter.spawn({ - shell: candidate.shell, - ...(candidate.args ? { args: candidate.args } : {}), - cwd: session.cwd, - cols: session.cols, - rows: session.rows, - env: terminalEnv, - }), - ); - - const trySpawn = async ( - candidates: ShellCandidate[], - index = 0, - ): Promise<{ process: PtyProcess; shellLabel: string } | null> => { - if (index >= candidates.length) { - return null; - } - const candidate = candidates[index]; - if (!candidate) { - return null; - } - - try { - const process = await spawnWithCandidate(candidate); - return { process, shellLabel: formatShellCandidate(candidate) }; - } catch (error) { - lastSpawnError = error; - if (!isRetryableShellSpawnError(error)) { - throw error; - } - return trySpawn(candidates, index + 1); - } - }; - - const spawnResult = await trySpawn(shellCandidates); - if (spawnResult) { - ptyProcess = spawnResult.process; - startedShell = spawnResult.shellLabel; - } - - if (!ptyProcess) { - const detail = - lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed"; - const tried = - shellCandidates.length > 0 - ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` - : ""; - throw new Error(`${detail}.${tried}`.trim()); - } - - session.process = ptyProcess; - session.pid = ptyProcess.pid; - session.status = "running"; - session.updatedAt = new Date().toISOString(); - session.unsubscribeData = ptyProcess.onData((data) => { - this.onProcessData(session, data); - }); - session.unsubscribeExit = ptyProcess.onExit((event) => { - this.onProcessExit(session, event); - }); - this.updateSubprocessPollingState(); - this.emitEvent({ - type: eventType, - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - snapshot: this.snapshot(session), - }); - } catch (error) { - if (ptyProcess) { - this.killProcessWithEscalation(ptyProcess, session.threadId, session.terminalId); - } - session.status = "error"; - session.pid = null; - session.process = null; - session.hasRunningSubprocess = false; - session.updatedAt = new Date().toISOString(); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - const message = error instanceof Error ? error.message : "Terminal start failed"; - this.emitEvent({ - type: "error", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - message, - }); - this.logger.error("failed to start terminal", { - threadId: session.threadId, - terminalId: session.terminalId, - error: message, - ...(startedShell ? { shell: startedShell } : {}), - }); - } - } - - private onProcessData(session: TerminalSessionState, data: string): void { - const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data); - session.pendingHistoryControlSequence = sanitized.pendingControlSequence; - if (sanitized.visibleText.length > 0) { - session.history = capHistory( - `${session.history}${sanitized.visibleText}`, - this.historyLineLimit, - ); - this.queuePersist(session.threadId, session.terminalId, session.history); - } - session.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "output", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - data, - }); - } - - private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void { - this.clearKillEscalationTimer(session.process); - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.status = "exited"; - session.pendingHistoryControlSequence = ""; - session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null; - session.exitSignal = Number.isInteger(event.signal) ? event.signal : null; - session.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "exited", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - exitCode: session.exitCode, - exitSignal: session.exitSignal, - }); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - } - - private stopProcess(session: TerminalSessionState): void { - const process = session.process; - if (!process) return; - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.status = "exited"; - session.pendingHistoryControlSequence = ""; - session.updatedAt = new Date().toISOString(); - this.killProcessWithEscalation(process, session.threadId, session.terminalId); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - } - - private cleanupProcessHandles(session: TerminalSessionState): void { - session.unsubscribeData?.(); - session.unsubscribeData = null; - session.unsubscribeExit?.(); - session.unsubscribeExit = null; - } - - private clearKillEscalationTimer(process: PtyProcess | null): void { - if (!process) return; - const timer = this.killEscalationTimers.get(process); - if (!timer) return; - clearTimeout(timer); - this.killEscalationTimers.delete(process); - } - - private killProcessWithEscalation( - process: PtyProcess, - threadId: string, - terminalId: string, - ): void { - this.clearKillEscalationTimer(process); - try { - process.kill("SIGTERM"); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.logger.warn("failed to kill terminal process", { - threadId, - terminalId, - signal: "SIGTERM", - error: message, - }); - return; - } - - const timer = setTimeout(() => { - this.killEscalationTimers.delete(process); - try { - process.kill("SIGKILL"); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.logger.warn("failed to force-kill terminal process", { - threadId, - terminalId, - signal: "SIGKILL", - error: message, - }); - } - }, this.processKillGraceMs); - timer.unref?.(); - this.killEscalationTimers.set(process, timer); - } - - private evictInactiveSessionsIfNeeded(): void { - const inactiveSessions = [...this.sessions.values()].filter( - (session) => session.status !== "running", - ); - if (inactiveSessions.length <= this.maxRetainedInactiveSessions) { - return; - } - - inactiveSessions.sort( - (left, right) => - left.updatedAt.localeCompare(right.updatedAt) || - left.threadId.localeCompare(right.threadId) || - left.terminalId.localeCompare(right.terminalId), - ); - const toEvict = inactiveSessions.length - this.maxRetainedInactiveSessions; - for (const session of inactiveSessions.slice(0, toEvict)) { - const key = toSessionKey(session.threadId, session.terminalId); - this.sessions.delete(key); - this.clearPersistTimer(session.threadId, session.terminalId); - this.pendingPersistHistory.delete(key); - this.persistQueues.delete(key); - this.clearKillEscalationTimer(session.process); - } - } - - private queuePersist(threadId: string, terminalId: string, history: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - this.pendingPersistHistory.set(persistenceKey, history); - this.schedulePersist(threadId, terminalId); - } - - private async persistHistory( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, history); - } - - private enqueuePersistWrite( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - const task = async () => { - await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8"); - }; - const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve(); - const next = previous - .catch(() => undefined) - .then(task) - .catch((error) => { - this.logger.warn("failed to persist terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - }); - this.persistQueues.set(persistenceKey, next); - const finalized = next.finally(() => { - if (this.persistQueues.get(persistenceKey) === next) { - this.persistQueues.delete(persistenceKey); - } - if ( - this.pendingPersistHistory.has(persistenceKey) && - !this.persistTimers.has(persistenceKey) - ) { - this.schedulePersist(threadId, terminalId); - } - }); - void finalized.catch(() => undefined); - return finalized; - } - - private schedulePersist(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - if (this.persistTimers.has(persistenceKey)) return; - const timer = setTimeout(() => { - this.persistTimers.delete(persistenceKey); - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory === undefined) return; - this.pendingPersistHistory.delete(persistenceKey); - void this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - }, this.persistDebounceMs); - this.persistTimers.set(persistenceKey, timer); - } - - private clearPersistTimer(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - const timer = this.persistTimers.get(persistenceKey); - if (!timer) return; - clearTimeout(timer); - this.persistTimers.delete(persistenceKey); - } - - private async readHistory(threadId: string, terminalId: string): Promise { - const nextPath = this.historyPath(threadId, terminalId); - try { - const raw = await fs.promises.readFile(nextPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - if (capped !== raw) { - await fs.promises.writeFile(nextPath, capped, "utf8"); - } - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - throw error; - } - } - - if (terminalId !== DEFAULT_TERMINAL_ID) { - return ""; - } - - const legacyPath = this.legacyHistoryPath(threadId); - try { - const raw = await fs.promises.readFile(legacyPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - - // Migrate legacy transcript filename to the terminal-scoped path. - await fs.promises.writeFile(nextPath, capped, "utf8"); - try { - await fs.promises.rm(legacyPath, { force: true }); - } catch (cleanupError) { - this.logger.warn("failed to remove legacy terminal history", { - threadId, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), - }); - } - - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return ""; - } - throw error; - } - } - - private async deleteHistory(threadId: string, terminalId: string): Promise { - const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })]; - if (terminalId === DEFAULT_TERMINAL_ID) { - deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true })); - } - try { - await Promise.all(deletions); - } catch (error) { - this.logger.warn("failed to delete terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private async flushPersistQueue(threadId: string, terminalId: string): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - - while (true) { - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory !== undefined) { - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - } - - const pending = this.persistQueues.get(persistenceKey); - if (!pending) { + if (!terminated) { return; } - await pending.catch(() => undefined); - } - } - private updateSubprocessPollingState(): void { - const hasRunningSessions = [...this.sessions.values()].some( - (session) => session.status === "running" && session.pid !== null, - ); - if (hasRunningSessions) { - this.ensureSubprocessPolling(); - return; - } - this.stopSubprocessPolling(); - } + yield* Effect.sleep(processKillGraceMs); - private ensureSubprocessPolling(): void { - if (this.subprocessPollTimer) return; - this.subprocessPollTimer = setInterval(() => { - void this.pollSubprocessActivity(); - }, this.subprocessPollIntervalMs); - this.subprocessPollTimer.unref?.(); - void this.pollSubprocessActivity(); - } - - private stopSubprocessPolling(): void { - if (!this.subprocessPollTimer) return; - clearInterval(this.subprocessPollTimer); - this.subprocessPollTimer = null; - } - - private async pollSubprocessActivity(): Promise { - if (this.subprocessPollInFlight) return; - - const runningSessions = [...this.sessions.values()].filter( - (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), - ); - if (runningSessions.length === 0) { - this.stopSubprocessPolling(); - return; - } - - this.subprocessPollInFlight = true; - try { - await Promise.all( - runningSessions.map(async (session) => { - const terminalPid = session.pid; - let hasRunningSubprocess = false; - try { - hasRunningSubprocess = await this.subprocessChecker(terminalPid); - } catch (error) { - this.logger.warn("failed to check terminal subprocess activity", { - threadId: session.threadId, - terminalId: session.terminalId, - terminalPid, - error: error instanceof Error ? error.message : String(error), - }); - return; - } - - const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId)); - if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) { - return; - } - if (liveSession.hasRunningSubprocess === hasRunningSubprocess) { - return; - } - - liveSession.hasRunningSubprocess = hasRunningSubprocess; - liveSession.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "activity", - threadId: liveSession.threadId, - terminalId: liveSession.terminalId, - createdAt: new Date().toISOString(), - hasRunningSubprocess, - }); - }), + yield* Effect.try({ + try: () => process.kill("SIGKILL"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGKILL to terminal process.", + cause, + signal: "SIGKILL", + }), + }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to force-kill terminal process", { + threadId, + terminalId, + signal: "SIGKILL", + error: error.message, + }), + ), ); - } finally { - this.subprocessPollInFlight = false; - } - } + }); - private async assertValidCwd(cwd: string): Promise { - let stats: fs.Stats; - try { - stats = await fs.promises.stat(cwd); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error }); + const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe( + Effect.ensuring( + modifyManagerState((state) => { + if (!state.killFibers.has(process)) { + return [undefined, state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [undefined, { ...state, killFibers }] as const; + }), + ), + Effect.forkIn(workerScope), + ); + + yield* registerKillFiber(process, fiber); + }); + + const persistWorker = yield* makeKeyedCoalescingWorker< + string, + PersistHistoryRequest, + never, + never + >({ + merge: (current, next) => ({ + history: next.history, + immediate: current.immediate || next.immediate, + }), + process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { + if (!request.immediate) { + yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); + } + + const [threadId, terminalId] = sessionKey.split("\u0000"); + if (!threadId || !terminalId) { + return; + } + + yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe( + Effect.catch((error) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + }), + }); + + const queuePersist = Effect.fn("terminal.queuePersist")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: false, + }); + }); + + const flushPersist = Effect.fn("terminal.flushPersist")(function* ( + threadId: string, + terminalId: string, + ) { + yield* persistWorker.drainKey(toSessionKey(threadId, terminalId)); + }); + + const persistHistory = Effect.fn("terminal.persistHistory")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: true, + }); + yield* flushPersist(threadId, terminalId); + }); + + const readHistory = Effect.fn("terminal.readHistory")(function* ( + threadId: string, + terminalId: string, + ) { + const nextPath = historyPath(threadId, terminalId); + if ( + yield* fileSystem + .exists(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))) + ) { + const raw = yield* fileSystem + .readFileString(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + if (capped !== raw) { + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("truncate", threadId, terminalId))); + } + return capped; } - throw error; - } - if (!stats.isDirectory()) { - throw new Error(`Terminal cwd is not a directory: ${cwd}`); - } - } - private async closeSession( - threadId: string, - terminalId: string, - deleteHistory: boolean, - ): Promise { - const key = toSessionKey(threadId, terminalId); - const session = this.sessions.get(key); - if (session) { - this.stopProcess(session); - this.sessions.delete(key); - } - this.updateSubprocessPollingState(); - await this.flushPersistQueue(threadId, terminalId); - if (deleteHistory) { - await this.deleteHistory(threadId, terminalId); - } - } + if (terminalId !== DEFAULT_TERMINAL_ID) { + return ""; + } - private sessionsForThread(threadId: string): TerminalSessionState[] { - return [...this.sessions.values()].filter((session) => session.threadId === threadId); - } + const legacyPath = legacyHistoryPath(threadId); + if ( + !(yield* fileSystem + .exists(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)))) + ) { + return ""; + } - private async deleteAllHistoryForThread(threadId: string): Promise { - const threadPrefix = `${toSafeThreadId(threadId)}_`; - try { - const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true }); - const removals = entries - .filter((entry) => entry.isFile()) - .map((entry) => entry.name) - .filter( + const raw = yield* fileSystem + .readFileString(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + yield* fileSystem.remove(legacyPath, { force: true }).pipe( + Effect.catch((cleanupError) => + Effect.logWarning("failed to remove legacy terminal history", { + threadId, + error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + }), + ), + ); + return capped; + }); + + const deleteHistory = Effect.fn("terminal.deleteHistory")(function* ( + threadId: string, + terminalId: string, + ) { + yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + if (terminalId === DEFAULT_TERMINAL_ID) { + yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + } + }); + + const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* ( + threadId: string, + ) { + const threadPrefix = `${toSafeThreadId(threadId)}_`; + const entries = yield* fileSystem + .readDirectory(logsDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); + yield* Effect.forEach( + entries.filter( (name) => name === `${toSafeThreadId(threadId)}.log` || name === `${legacySafeThreadId(threadId)}.log` || name.startsWith(threadPrefix), - ) - .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true })); - await Promise.all(removals); - } catch (error) { - this.logger.warn("failed to delete terminal histories for thread", { - threadId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private requireSession(threadId: string, terminalId: string): TerminalSessionState { - const session = this.sessions.get(toSessionKey(threadId, terminalId)); - if (!session) { - throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`); - } - return session; - } - - private snapshot(session: TerminalSessionState): TerminalSessionSnapshot { - return { - threadId: session.threadId, - terminalId: session.terminalId, - cwd: session.cwd, - status: session.status, - pid: session.pid, - history: session.history, - exitCode: session.exitCode, - exitSignal: session.exitSignal, - updatedAt: session.updatedAt, - }; - } - - private emitEvent(event: TerminalEvent): void { - this.emit("event", event); - } - - private historyPath(threadId: string, terminalId: string): string { - const threadPart = toSafeThreadId(threadId); - if (terminalId === DEFAULT_TERMINAL_ID) { - return path.join(this.logsDir, `${threadPart}.log`); - } - return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); - } - - private legacyHistoryPath(threadId: string): string { - return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`); - } - - private async runWithThreadLock(threadId: string, task: () => Promise): Promise { - const previous = this.threadLocks.get(threadId) ?? Promise.resolve(); - let release!: () => void; - const current = new Promise((resolve) => { - release = resolve; + ), + (name) => + fileSystem.remove(path.join(logsDir, name), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal histories for thread", { + threadId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ), + { discard: true }, + ); }); - this.threadLocks.set(threadId, current); - await previous.catch(() => undefined); - try { - return await task(); - } finally { - release(); - if (this.threadLocks.get(threadId) === current) { - this.threadLocks.delete(threadId); + + const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) { + const stats = yield* fileSystem.stat(cwd).pipe( + Effect.mapError( + (cause) => + new TerminalCwdError({ + cwd, + reason: cause.reason._tag === "NotFound" ? "notFound" : "statFailed", + cause, + }), + ), + ); + if (stats.type !== "Directory") { + return yield* new TerminalCwdError({ + cwd, + reason: "notDirectory", + }); } - } - } -} + }); -export const TerminalManagerLive = Layer.effect( - TerminalManager, - Effect.gen(function* () { - const { terminalLogsDir } = yield* ServerConfig; + const getSession = Effect.fn("terminal.getSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return> { + return yield* Effect.map(readManagerState, (state) => + Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))), + ); + }); - const ptyAdapter = yield* PtyAdapter; - const runtime = yield* Effect.acquireRelease( - Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })), - (r) => Effect.sync(() => r.dispose()), + const requireSession = Effect.fn("terminal.requireSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return { + return yield* Effect.flatMap(getSession(threadId, terminalId), (session) => + Option.match(session, { + onNone: () => + Effect.fail( + new TerminalSessionLookupError({ + threadId, + terminalId, + }), + ), + onSome: Effect.succeed, + }), + ); + }); + + const sessionsForThread = Effect.fn("terminal.sessionsForThread")(function* (threadId: string) { + return yield* readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].filter((session) => session.threadId === threadId), + ), + ); + }); + + const evictInactiveSessionsIfNeeded = Effect.fn("terminal.evictInactiveSessionsIfNeeded")( + function* () { + yield* modifyManagerState((state) => { + const inactiveSessions = [...state.sessions.values()].filter( + (session) => session.status !== "running", + ); + if (inactiveSessions.length <= maxRetainedInactiveSessions) { + return [undefined, state] as const; + } + + inactiveSessions.sort( + (left, right) => + left.updatedAt.localeCompare(right.updatedAt) || + left.threadId.localeCompare(right.threadId) || + left.terminalId.localeCompare(right.terminalId), + ); + + const sessions = new Map(state.sessions); + + const toEvict = inactiveSessions.length - maxRetainedInactiveSessions; + for (const session of inactiveSessions.slice(0, toEvict)) { + const key = toSessionKey(session.threadId, session.terminalId); + sessions.delete(key); + } + + return [undefined, { ...state, sessions }] as const; + }); + }, ); + const drainProcessEvents = Effect.fn("terminal.drainProcessEvents")(function* ( + session: TerminalSessionState, + expectedPid: number, + ) { + while (true) { + const action: DrainProcessEventAction = yield* Effect.sync(() => { + if (session.pid !== expectedPid || !session.process || session.status !== "running") { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex]; + if (!nextEvent) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + session.pendingProcessEventIndex += 1; + if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + } + + if (nextEvent.type === "output") { + const sanitized = sanitizeTerminalHistoryChunk( + session.pendingHistoryControlSequence, + nextEvent.data, + ); + session.pendingHistoryControlSequence = sanitized.pendingControlSequence; + if (sanitized.visibleText.length > 0) { + session.history = capHistory( + `${session.history}${sanitized.visibleText}`, + historyLineLimit, + ); + } + session.updatedAt = new Date().toISOString(); + + return { + type: "output", + threadId: session.threadId, + terminalId: session.terminalId, + history: sanitized.visibleText.length > 0 ? session.history : null, + data: nextEvent.data, + } as const; + } + + const process = session.process; + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.exitCode = Number.isInteger(nextEvent.event.exitCode) + ? nextEvent.event.exitCode + : null; + session.exitSignal = Number.isInteger(nextEvent.event.signal) + ? nextEvent.event.signal + : null; + session.updatedAt = new Date().toISOString(); + + return { + type: "exit", + process, + threadId: session.threadId, + terminalId: session.terminalId, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + } as const; + }); + + if (action.type === "idle") { + return; + } + + if (action.type === "output") { + if (action.history !== null) { + yield* queuePersist(action.threadId, action.terminalId, action.history); + } + + yield* publishEvent({ + type: "output", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + data: action.data, + }); + continue; + } + + yield* clearKillFiber(action.process); + yield* publishEvent({ + type: "exited", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + exitCode: action.exitCode, + exitSignal: action.exitSignal, + }); + yield* evictInactiveSessionsIfNeeded(); + return; + } + }); + + const stopProcess = Effect.fn("terminal.stopProcess")(function* ( + session: TerminalSessionState, + ) { + const process = session.process; + if (!process) return; + + yield* modifyManagerState((state) => { + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* clearKillFiber(process); + yield* startKillEscalation(process, session.threadId, session.terminalId); + yield* evictInactiveSessionsIfNeeded(); + }); + + const trySpawn = Effect.fn("terminal.trySpawn")(function* ( + shellCandidates: ReadonlyArray, + spawnEnv: NodeJS.ProcessEnv, + session: TerminalSessionState, + index = 0, + lastError: PtySpawnError | null = null, + ): Effect.fn.Return<{ process: PtyProcess; shellLabel: string }, PtySpawnError> { + if (index >= shellCandidates.length) { + const detail = lastError?.message ?? "Failed to spawn PTY process"; + const tried = + shellCandidates.length > 0 + ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` + : ""; + return yield* new PtySpawnError({ + adapter: "terminal-manager", + message: `${detail}.${tried}`.trim(), + ...(lastError ? { cause: lastError } : {}), + }); + } + + const candidate = shellCandidates[index]; + if (!candidate) { + return yield* ( + lastError ?? + new PtySpawnError({ + adapter: "terminal-manager", + message: "No shell candidate available for PTY spawn.", + }) + ); + } + + const attempt = yield* Effect.result( + options.ptyAdapter.spawn({ + shell: candidate.shell, + ...(candidate.args ? { args: candidate.args } : {}), + cwd: session.cwd, + cols: session.cols, + rows: session.rows, + env: spawnEnv, + }), + ); + + if (attempt._tag === "Success") { + return { + process: attempt.success, + shellLabel: formatShellCandidate(candidate), + }; + } + + const spawnError = attempt.failure; + if (!isRetryableShellSpawnError(spawnError)) { + return yield* spawnError; + } + + return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError); + }); + + const startSession = Effect.fn("terminal.startSession")(function* ( + session: TerminalSessionState, + input: TerminalStartInput, + eventType: "started" | "restarted", + ) { + yield* stopProcess(session); + + yield* modifyManagerState((state) => { + session.status = "starting"; + session.cwd = input.cwd; + session.cols = input.cols; + session.rows = input.rows; + session.exitCode = null; + session.exitSignal = null; + session.hasRunningSubprocess = false; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + let ptyProcess: PtyProcess | null = null; + let startedShell: string | null = null; + + const startResult = yield* Effect.result( + Effect.gen(function* () { + const shellCandidates = resolveShellCandidates(shellResolver); + const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); + const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); + ptyProcess = spawnResult.process; + startedShell = spawnResult.shellLabel; + + const processPid = ptyProcess.pid; + const unsubscribeData = ptyProcess.onData((data) => { + if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + const unsubscribeExit = ptyProcess.onExit((event) => { + if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + + yield* modifyManagerState((state) => { + session.process = ptyProcess; + session.pid = processPid; + session.status = "running"; + session.updatedAt = new Date().toISOString(); + session.unsubscribeData = unsubscribeData; + session.unsubscribeExit = unsubscribeExit; + return [undefined, state] as const; + }); + + yield* publishEvent({ + type: eventType, + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + snapshot: snapshot(session), + }); + }), + ); + + if (startResult._tag === "Success") { + return; + } + + { + const error = startResult.failure; + if (ptyProcess) { + yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); + } + + yield* modifyManagerState((state) => { + session.status = "error"; + session.pid = null; + session.process = null; + session.unsubscribeData = null; + session.unsubscribeExit = null; + session.hasRunningSubprocess = false; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + + const message = error.message; + yield* publishEvent({ + type: "error", + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + message, + }); + yield* Effect.logError("failed to start terminal", { + threadId: session.threadId, + terminalId: session.terminalId, + error: message, + ...(startedShell ? { shell: startedShell } : {}), + }); + } + }); + + const closeSession = Effect.fn("terminal.closeSession")(function* ( + threadId: string, + terminalId: string, + deleteHistoryOnClose: boolean, + ) { + const key = toSessionKey(threadId, terminalId); + const session = yield* getSession(threadId, terminalId); + + if (Option.isSome(session)) { + yield* stopProcess(session.value); + yield* persistHistory(threadId, terminalId, session.value.history); + } + + yield* flushPersist(threadId, terminalId); + + yield* modifyManagerState((state) => { + if (!state.sessions.has(key)) { + return [undefined, state] as const; + } + const sessions = new Map(state.sessions); + sessions.delete(key); + return [undefined, { ...state, sessions }] as const; + }); + + if (deleteHistoryOnClose) { + yield* deleteHistory(threadId, terminalId); + } + }); + + const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { + const state = yield* readManagerState; + const runningSessions = [...state.sessions.values()].filter( + (session): session is TerminalSessionState & { pid: number } => + session.status === "running" && Number.isInteger(session.pid), + ); + + if (runningSessions.length === 0) { + return; + } + + const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( + session: TerminalSessionState & { pid: number }, + ) { + const terminalPid = session.pid; + const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe( + Effect.map(Option.some), + Effect.catch((error) => + Effect.logWarning("failed to check terminal subprocess activity", { + threadId: session.threadId, + terminalId: session.terminalId, + terminalPid, + error: error instanceof Error ? error.message : String(error), + }).pipe(Effect.as(Option.none())), + ), + ); + + if (Option.isNone(hasRunningSubprocess)) { + return; + } + + const event = yield* modifyManagerState((state) => { + const liveSession: Option.Option = Option.fromNullishOr( + state.sessions.get(toSessionKey(session.threadId, session.terminalId)), + ); + if ( + Option.isNone(liveSession) || + liveSession.value.status !== "running" || + liveSession.value.pid !== terminalPid || + liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value + ) { + return [Option.none(), state] as const; + } + + liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value; + liveSession.value.updatedAt = new Date().toISOString(); + + return [ + Option.some({ + type: "activity" as const, + threadId: liveSession.value.threadId, + terminalId: liveSession.value.terminalId, + createdAt: new Date().toISOString(), + hasRunningSubprocess: hasRunningSubprocess.value, + }), + state, + ] as const; + }); + + if (Option.isSome(event)) { + yield* publishEvent(event.value); + } + }); + + yield* Effect.forEach(runningSessions, checkSubprocessActivity, { + concurrency: "unbounded", + discard: true, + }); + }); + + const hasRunningSessions = readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].some((session) => session.status === "running"), + ), + ); + + yield* Effect.forever( + hasRunningSessions.pipe( + Effect.flatMap((active) => + active + ? pollSubprocessActivity().pipe( + Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)), + ) + : Effect.sleep(subprocessPollIntervalMs), + ), + ), + ).pipe(Effect.forkIn(workerScope)); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const sessions = yield* modifyManagerState( + (state) => + [ + [...state.sessions.values()], + { + ...state, + sessions: new Map(), + }, + ] as const, + ); + + const cleanupSession = Effect.fn("terminal.cleanupSession")(function* ( + session: TerminalSessionState, + ) { + cleanupProcessHandles(session); + if (!session.process) return; + yield* clearKillFiber(session.process); + yield* runKillEscalation(session.process, session.threadId, session.terminalId); + }); + + yield* Effect.forEach(sessions, cleanupSession, { + concurrency: "unbounded", + discard: true, + }); + }).pipe(Effect.ignoreCause({ log: true })), + ); + + const open: TerminalManagerShape["open"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existing = yield* getSession(input.threadId, terminalId); + if (Option.isNone(existing)) { + yield* flushPersist(input.threadId, terminalId); + const history = yield* readHistory(input.threadId, terminalId); + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + const session: TerminalSessionState = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + status: "starting", + pid: null, + history, + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(session); + } + + const liveSession = existing.value; + const nextRuntimeEnv = normalizedRuntimeEnv(input.env); + const currentRuntimeEnv = liveSession.runtimeEnv; + const targetCols = input.cols ?? liveSession.cols; + const targetRows = input.rows ?? liveSession.rows; + const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv); + + if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { + yield* stopProcess(liveSession); + liveSession.cwd = input.cwd; + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } else if (liveSession.status === "exited" || liveSession.status === "error") { + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } + + if (!liveSession.process) { + yield* startSession( + liveSession, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols: targetCols, + rows: targetRows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(liveSession); + } + + if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { + liveSession.cols = targetCols; + liveSession.rows = targetRows; + liveSession.updatedAt = new Date().toISOString(); + liveSession.process.resize(targetCols, targetRows); + } + + return snapshot(liveSession); + }), + ); + + const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + if (session.status === "exited") return; + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + yield* Effect.sync(() => process.write(input.data)); + }); + + const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + session.cols = input.cols; + session.rows = input.rows; + session.updatedAt = new Date().toISOString(); + yield* Effect.sync(() => process.resize(input.cols, input.rows)); + }); + + const clear: TerminalManagerShape["clear"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + yield* persistHistory(input.threadId, terminalId, session.history); + yield* publishEvent({ + type: "cleared", + threadId: input.threadId, + terminalId, + createdAt: new Date().toISOString(), + }); + }), + ); + + const restart: TerminalManagerShape["restart"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existingSession = yield* getSession(input.threadId, terminalId); + let session: TerminalSessionState; + if (Option.isNone(existingSession)) { + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + session = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + status: "starting", + pid: null, + history: "", + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + yield* evictInactiveSessionsIfNeeded(); + } else { + session = existingSession.value; + yield* stopProcess(session); + session.cwd = input.cwd; + session.runtimeEnv = normalizedRuntimeEnv(input.env); + } + + const cols = input.cols ?? session.cols; + const rows = input.rows ?? session.rows; + + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + yield* persistHistory(input.threadId, terminalId, session.history); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "restarted", + ); + return snapshot(session); + }), + ); + + const close: TerminalManagerShape["close"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + if (input.terminalId) { + yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true); + return; + } + + const threadSessions = yield* sessionsForThread(input.threadId); + yield* Effect.forEach( + threadSessions, + (session) => closeSession(input.threadId, session.terminalId, false), + { discard: true }, + ); + + if (input.deleteHistory) { + yield* deleteAllHistoryForThread(input.threadId); + } + }), + ); + return { - open: (input) => - Effect.tryPromise({ - try: () => runtime.open(input), - catch: (cause) => new TerminalError({ message: "Failed to open terminal", cause }), - }), - write: (input) => - Effect.tryPromise({ - try: () => runtime.write(input), - catch: (cause) => new TerminalError({ message: "Failed to write to terminal", cause }), - }), - resize: (input) => - Effect.tryPromise({ - try: () => runtime.resize(input), - catch: (cause) => new TerminalError({ message: "Failed to resize terminal", cause }), - }), - clear: (input) => - Effect.tryPromise({ - try: () => runtime.clear(input), - catch: (cause) => new TerminalError({ message: "Failed to clear terminal", cause }), - }), - restart: (input) => - Effect.tryPromise({ - try: () => runtime.restart(input), - catch: (cause) => new TerminalError({ message: "Failed to restart terminal", cause }), - }), - close: (input) => - Effect.tryPromise({ - try: () => runtime.close(input), - catch: (cause) => new TerminalError({ message: "Failed to close terminal", cause }), - }), + open, + write, + resize, + clear, + restart, + close, subscribe: (listener) => Effect.sync(() => { - runtime.on("event", listener); + terminalEventListeners.add(listener); return () => { - runtime.off("event", listener); + terminalEventListeners.delete(listener); }; }), - dispose: Effect.sync(() => runtime.dispose()), } satisfies TerminalManagerShape; - }), + }, ); + +export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()); diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index c2539da4b6..bdfbc85cc5 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -10,20 +10,28 @@ import { TerminalClearInput, TerminalCloseInput, TerminalEvent, + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, TerminalOpenInput, TerminalResizeInput, TerminalRestartInput, TerminalSessionSnapshot, + TerminalSessionLookupError, TerminalSessionStatus, TerminalWriteInput, } from "@t3tools/contracts"; import { PtyProcess } from "./PTY"; -import { Effect, Schema, ServiceMap } from "effect"; +import { Effect, ServiceMap } from "effect"; -export class TerminalError extends Schema.TaggedErrorClass()("TerminalError", { - message: Schema.String, - cause: Schema.optional(Schema.Defect), -}) {} +export { + TerminalCwdError, + TerminalError, + TerminalHistoryError, + TerminalNotRunningError, + TerminalSessionLookupError, +}; export interface TerminalSessionState { threadId: string; @@ -101,14 +109,13 @@ export interface TerminalManagerShape { readonly close: (input: TerminalCloseInput) => Effect.Effect; /** - * Subscribe to terminal runtime events. + * Subscribe to terminal runtime events with a direct callback. + * + * Returns an unsubscribe function. */ - readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>; - - /** - * Dispose all managed terminal resources. - */ - readonly dispose: Effect.Effect; + readonly subscribe: ( + listener: (event: TerminalEvent) => Effect.Effect, + ) => Effect.Effect<() => void>; } /** 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 826b9ad6fd..0000000000 --- a/apps/server/src/wsServer.test.ts +++ /dev/null @@ -1,1962 +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, 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", - authStatus: "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 listeners = new Set<(event: TerminalEvent) => void>(); - - private key(threadId: string, terminalId: string): string { - return `${threadId}\u0000${terminalId}`; - } - - emitEvent(event: TerminalEvent): void { - for (const listener of this.listeners) { - listener(event); - } - } - - subscriptionCount(): number { - return this.listeners.size; - } - - readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) => - Effect.sync(() => { - const now = new Date().toISOString(); - 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.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - }); - - readonly dispose: TerminalManagerShape["dispose"] = Effect.void; -} - -// --------------------------------------------------------------------------- -// WebSocket test harness -// -// Incoming messages are split into two channels: -// - pushChannel: server push envelopes (type === "push") -// - responseChannel: request/response envelopes (have an "id" field) -// -// This means sendRequest never has to skip push messages and waitForPush -// never has to skip response messages, eliminating a class of ordering bugs. -// --------------------------------------------------------------------------- - -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("detaches terminal event listener on stop for injected manager", async () => { - const terminalManager = new MockTerminalManager(); - server = await createTestServer({ - cwd: "/test", - terminalManager, - }); - - expect(terminalManager.subscriptionCount()).toBe(1); - - await closeTestServer(); - server = null; - - expect(terminalManager.subscriptionCount()).toBe(0); - }); - - it("returns validation errors for invalid terminal open params", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - const response = await sendRequest(ws, WS_METHODS.terminalOpen, { - threadId: "", - cwd: "", - cols: 1, - rows: 1, - }); - expect(response.error).toBeDefined(); - }); - - it("handles invalid JSON gracefully", async () => { - server = await createTestServer({ cwd: "/test" }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - // Send garbage - ws.send("not json at all"); - - // Error response goes to the response channel - const channels = channelsBySocket.get(ws)!; - let response: WebSocketResponse | null = null; - for (let attempt = 0; attempt < 5; attempt += 1) { - const message = await dequeue(channels.response, 5_000); - if (message.id === "unknown") { - response = message; - break; - } - if (message.error) { - response = message; - break; - } - } - expect(response).toBeDefined(); - expect(response!.error).toBeDefined(); - expect(response!.error!.message).toContain("Invalid request format"); - }); - - it("catches websocket message handler rejections and keeps the socket usable", async () => { - const unhandledRejections: unknown[] = []; - const onUnhandledRejection = (reason: unknown) => { - unhandledRejections.push(reason); - }; - process.on("unhandledRejection", onUnhandledRejection); - - const brokenOpenService: OpenShape = { - openBrowser: () => Effect.void, - openInEditor: () => - Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)), - }; - - try { - server = await createTestServer({ cwd: "/test", open: brokenOpenService }); - const addr = server.address(); - const port = typeof addr === "object" && addr !== null ? addr.port : 0; - - const [ws] = await connectAndAwaitWelcome(port); - connections.push(ws); - - ws.send( - JSON.stringify({ - id: "req-broken-open", - body: { - _tag: WS_METHODS.shellOpenInEditor, - cwd: "/tmp", - editor: "cursor", - }, - }), - ); - - await new Promise((resolve) => setTimeout(resolve, 50)); - expect(unhandledRejections).toHaveLength(0); - - const workspace = makeTempDir("t3code-ws-handler-still-usable-"); - fs.writeFileSync(path.join(workspace, "file.txt"), "ok\n", "utf8"); - const response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { - cwd: workspace, - query: "file", - limit: 5, - }); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual( - expect.objectContaining({ - entries: expect.arrayContaining([ - expect.objectContaining({ - path: "file.txt", - kind: "file", - }), - ]), - }), - ); - } 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 a4f6f987b6..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 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 Effect.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 runtimeServices = yield* Effect.services< - ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path - >(); - const runPromise = Effect.runPromiseWith(runtimeServices); - - const unsubscribeTerminalEvents = yield* terminalManager.subscribe( - (event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)), - ); - yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents())); - yield* readiness.markTerminalSubscriptionsReady; - - yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe( - Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })), - ); - yield* readiness.markHttpListening; - - yield* Effect.addFinalizer(() => - Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]), - ); - - const routeRequest = Effect.fnUntraced(function* (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 5127faf827..499943c3f0 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.14", + "version": "0.0.15", "private": true, "type": "module", "scripts": { @@ -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/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx new file mode 100644 index 0000000000..a2b27bb1e9 --- /dev/null +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -0,0 +1,49 @@ +import { useEffect, type ReactNode } from "react"; +import { useNavigate } from "@tanstack/react-router"; + +import ThreadSidebar from "./Sidebar"; +import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar"; + +const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width"; +const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16; +const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16; + +export function AppSidebarLayout({ children }: { children: ReactNode }) { + const navigate = useNavigate(); + + useEffect(() => { + const onMenuAction = window.desktopBridge?.onMenuAction; + if (typeof onMenuAction !== "function") { + return; + } + + const unsubscribe = onMenuAction((action) => { + if (action !== "open-settings") return; + void navigate({ to: "/settings" }); + }); + + return () => { + unsubscribe?.(); + }; + }, [navigate]); + + return ( + + + wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, + storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, + }} + > + + + + {children} + + ); +} diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 5aef38ccf6..2f66e063ad 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -6,6 +6,7 @@ import { resolveBranchSelectionTarget, resolveDraftEnvModeAfterBranchChange, resolveBranchToolbarValue, + shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; describe("resolveDraftEnvModeAfterBranchChange", () => { @@ -267,3 +268,38 @@ describe("resolveBranchSelectionTarget", () => { }); }); }); + +describe("shouldIncludeBranchPickerItem", () => { + it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "__checkout_pull_request__:1359", + normalizedQuery: "gh pr checkout 1359", + createBranchItemValue: "__create_new_branch__:gh pr checkout 1359", + checkoutPullRequestItemValue: "__checkout_pull_request__:1359", + }), + ).toBe(true); + }); + + it("keeps the synthetic create-branch item visible for arbitrary branch input", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "__create_new_branch__:feature/demo", + normalizedQuery: "feature/demo", + createBranchItemValue: "__create_new_branch__:feature/demo", + checkoutPullRequestItemValue: null, + }), + ).toBe(true); + }); + + it("still filters ordinary branch items by query text", () => { + expect( + shouldIncludeBranchPickerItem({ + itemValue: "main", + normalizedQuery: "gh pr checkout 1359", + createBranchItemValue: "__create_new_branch__:gh pr checkout 1359", + checkoutPullRequestItemValue: "__checkout_pull_request__:1359", + }), + ).toBe(false); + }); +}); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 2215569c83..99928441c7 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -123,3 +123,26 @@ export function resolveBranchSelectionTarget(input: { reuseExistingWorktree: false, }; } + +export function shouldIncludeBranchPickerItem(input: { + itemValue: string; + normalizedQuery: string; + createBranchItemValue: string | null; + checkoutPullRequestItemValue: string | null; +}): boolean { + const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input; + + if (normalizedQuery.length === 0) { + return true; + } + + if (createBranchItemValue && itemValue === createBranchItemValue) { + return true; + } + + if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) { + return true; + } + + return itemValue.toLowerCase().includes(normalizedQuery); +} diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 9446279161..c1a43adc90 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -28,6 +28,7 @@ import { EnvMode, resolveBranchSelectionTarget, resolveBranchToolbarValue, + shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; import { Button } from "./ui/button"; import { @@ -134,11 +135,20 @@ export function BranchToolbarBranchSelector({ () => normalizedDeferredBranchQuery.length === 0 ? branchPickerItems - : branchPickerItems.filter((itemValue) => { - if (createBranchItemValue && itemValue === createBranchItemValue) return true; - return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery); - }), - [branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery], + : branchPickerItems.filter((itemValue) => + shouldIncludeBranchPickerItem({ + itemValue, + normalizedQuery: normalizedDeferredBranchQuery, + createBranchItemValue, + checkoutPullRequestItemValue, + }), + ), + [ + branchPickerItems, + checkoutPullRequestItemValue, + createBranchItemValue, + normalizedDeferredBranchQuery, + ], ); const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic( canonicalActiveBranch, @@ -387,7 +397,6 @@ export function BranchToolbarBranchSelector({ key={itemValue} index={index} value={itemValue} - className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined} style={style} onClick={() => selectBranch(branch)} > diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 9663d158eb..b364a8e3a1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -243,7 +243,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) { a({ node: _node, href, ...props }) { const targetPath = resolveMarkdownFileLinkTarget(href, cwd); if (!targetPath) { - return
; + return ; } return ( diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 0995ae1ccc..33b9b62859 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -2,14 +2,16 @@ import "../index.css"; import { + EventId, ORCHESTRATION_WS_METHODS, 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, @@ -28,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"; @@ -40,22 +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"][] = []; +const rpcHarness = new BrowserWsRpcHarness(); +const wsRequests = rpcHarness.requests; +let customWsRpcResolver: ((body: NormalizedWsRpcRequestBody) => unknown | undefined) | null = null; const wsLink = ws.link(/ws(s)?:\/\/.*/); interface ViewportSpec { @@ -73,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 }, @@ -96,6 +108,7 @@ interface MountedChatView { cleanup: () => Promise; measureUserRow: (targetMessageId: MessageId) => Promise; setViewport: (viewport: ViewportSpec) => Promise; + setContainerSize: (viewport: Pick) => Promise; router: ReturnType; } @@ -116,7 +129,7 @@ function createBaseServerConfig(): ServerConfig { installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: NOW_ISO, models: [], }, @@ -257,6 +270,7 @@ function createSnapshotForTargetUser(options: { latestTurn: null, createdAt: NOW_ISO, updatedAt: NOW_ISO, + archivedAt: null, deletedAt: null, messages, activities: [], @@ -314,6 +328,7 @@ function addThreadToSnapshot( latestTurn: null, createdAt: NOW_ISO, updatedAt: NOW_ISO, + archivedAt: null, deletedAt: null, messages: [], activities: [], @@ -333,6 +348,67 @@ function addThreadToSnapshot( }; } +function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent { + return { + sequence, + eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: NOW_ISO, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.created", + payload: { + threadId, + projectId: PROJECT_ID, + title: "New thread", + modelSelection: { + provider: "codex", + model: "gpt-5", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + }, + }; +} + +function sendOrchestrationDomainEvent(event: OrchestrationEvent): void { + rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event); +} + +async function waitForWsClient(): Promise { + await vi.waitFor( + () => { + expect( + wsRequests.some( + (request) => request._tag === WS_METHODS.subscribeOrchestrationDomainEvents, + ), + ).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { + await waitForWsClient(); + fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); + sendOrchestrationDomainEvent( + createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence), + ); + await vi.waitFor( + () => { + expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined(); + }, + { timeout: 8_000, interval: 16 }, + ); +} + function createDraftOnlySnapshot(): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ targetMessageId: "msg-user-draft-target" as MessageId, @@ -356,6 +432,25 @@ function withProjectScripts( }; } +function setDraftThreadWithoutWorktree(): void { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + envMode: "local", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); +} + function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ targetMessageId: "msg-user-plan-target" as MessageId, @@ -413,7 +508,119 @@ 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; + } const tag = body._tag; if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) { return fixture.snapshot; @@ -456,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, @@ -474,32 +684,11 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { const worker = setupWorker( wsLink.addEventListener("connection", ({ client }) => { - client.send( - JSON.stringify({ - type: "push", - sequence: 1, - 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", () => @@ -588,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"]'), @@ -595,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 { @@ -610,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 }, ); @@ -748,15 +1002,18 @@ async function mountChatView(options: { viewport: ViewportSpec; snapshot: OrchestrationReadModel; configureFixture?: (fixture: TestFixture) => void; + resolveRpc?: (body: NormalizedWsRpcRequestBody) => unknown | undefined; }): Promise { fixture = buildFixture(options.snapshot); options.configureFixture?.(fixture); + customWsRpcResolver = options.resolveRpc ?? null; await setViewport(options.viewport); await waitForProductionStyles(); 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"; @@ -776,6 +1033,7 @@ async function mountChatView(options: { await waitForLayout(); const cleanup = async () => { + customWsRpcResolver = null; await screen.unmount(); host.remove(); }; @@ -788,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, }; } @@ -827,14 +1090,42 @@ 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 = ""; wsRequests.length = 0; + customWsRpcResolver = null; useComposerDraftStore.setState({ draftsByThreadId: {}, draftThreadsByThreadId: {}, @@ -845,11 +1136,12 @@ describe("ChatView timeline estimator parity (full app)", () => { useStore.setState({ projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }); }); afterEach(() => { + customWsRpcResolver = null; document.body.innerHTML = ""; }); @@ -1010,24 +1302,22 @@ describe("ChatView timeline estimator parity (full app)", () => { }, ); - it("opens the project cwd for draft threads without a worktree path", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadId: { - [THREAD_ID]: { - projectId: PROJECT_ID, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - projectDraftThreadIdByProjectId: { - [PROJECT_ID]: THREAD_ID, - }, + it("shows an explicit empty state for projects without threads in the sidebar", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), }); + try { + await expect.element(page.getByText("No threads yet")).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + + it("opens the project cwd for draft threads without a worktree path", async () => { + setDraftThreadWithoutWorktree(); + const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, snapshot: createDraftOnlySnapshot(), @@ -1040,6 +1330,7 @@ describe("ChatView timeline estimator parity (full app)", () => { }); try { + await waitForServerConfigToApply(); const openButton = await waitForElement( () => Array.from(document.querySelectorAll("button")).find( @@ -1047,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( @@ -1067,6 +1361,162 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + openButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscode-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("filters the open picker menu and opens VSCodium from the menu", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders", "vscodium"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const menuButton = await waitForElement( + () => document.querySelector('button[aria-label="Copy options"]'), + "Unable to find Open picker button.", + ); + (menuButton as HTMLButtonElement).click(); + + await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VS Code Insiders"), + ) ?? null, + "Unable to find VS Code Insiders menu item.", + ); + + expect( + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) => + item.textContent?.includes("Zed"), + ), + ).toBe(false); + + const vscodiumItem = await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VSCodium"), + ) ?? null, + "Unable to find VSCodium menu item.", + ); + (vscodiumItem as HTMLElement).click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscodium", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("falls back to the first installed editor when the stored favorite is unavailable", async () => { + localStorage.setItem("t3code:last-editor", JSON.stringify("vscodium")); + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + await vi.waitFor(() => { + expect(openButton.disabled).toBe(false); + }); + openButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscode-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("runs project scripts from local draft threads at the project cwd", async () => { useComposerDraftStore.setState({ draftThreadsByThreadId: { @@ -1206,6 +1656,154 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("runs setup scripts after preparing a pull request worktree thread", async () => { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + envMode: "local", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === WS_METHODS.gitResolvePullRequest) { + return { + pullRequest: { + number: 1359, + title: "Add thread archiving and settings navigation", + url: "https://github.com/pingdotgg/t3code/pull/1359", + baseBranch: "main", + headBranch: "archive-settings-overhaul", + state: "open", + }, + }; + } + if (body._tag === WS_METHODS.gitPreparePullRequestThread) { + return { + pullRequest: { + number: 1359, + title: "Add thread archiving and settings navigation", + url: "https://github.com/pingdotgg/t3code/pull/1359", + baseBranch: "main", + headBranch: "archive-settings-overhaul", + state: "open", + }, + branch: "archive-settings-overhaul", + worktreePath: "/repo/worktrees/pr-1359", + }; + } + return undefined; + }, + }); + + try { + const branchButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "main", + ) as HTMLButtonElement | null, + "Unable to find branch selector button.", + ); + branchButton.click(); + + const branchInput = await waitForElement( + () => document.querySelector('input[placeholder="Search branches..."]'), + "Unable to find branch search input.", + ); + branchInput.focus(); + await page.getByPlaceholder("Search branches...").fill("1359"); + + const checkoutItem = await waitForElement( + () => + Array.from(document.querySelectorAll("span")).find( + (element) => element.textContent?.trim() === "Checkout Pull Request", + ) as HTMLSpanElement | null, + "Unable to find checkout pull request option.", + ); + checkoutItem.click(); + + const worktreeButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Worktree", + ) as HTMLButtonElement | null, + "Unable to find Worktree button.", + ); + worktreeButton.click(); + + await vi.waitFor( + () => { + const prepareRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.gitPreparePullRequestThread, + ); + expect(prepareRequest).toMatchObject({ + _tag: WS_METHODS.gitPreparePullRequestThread, + cwd: "/repo/project", + reference: "1359", + mode: "worktree", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => + request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359", + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + threadId: expect.any(String), + cwd: "/repo/worktrees/pr-1359", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359", + }, + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await vi.waitFor( + () => { + const writeRequest = wsRequests.find( + (request) => + request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", + ); + expect(writeRequest).toMatchObject({ + _tag: WS_METHODS.terminalWrite, + threadId: expect.any(String), + data: "bun install\r", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("toggles plan mode with Shift+Tab only while the composer is focused", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, @@ -1449,6 +2047,87 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("hides the archive action when the pointer leaves a thread row", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-archive-hover-test" as MessageId, + targetText: "archive hover target", + }), + }); + + try { + const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); + + await expect.element(threadRow).toBeInTheDocument(); + const archiveButton = await waitForElement( + () => + document.querySelector(`[data-testid="thread-archive-${THREAD_ID}"]`), + "Unable to find archive button.", + ); + const archiveAction = archiveButton.parentElement; + expect( + archiveAction, + "Archive button should render inside a visibility wrapper.", + ).not.toBeNull(); + expect(getComputedStyle(archiveAction!).opacity).toBe("0"); + + await threadRow.hover(); + await vi.waitFor( + () => { + expect(getComputedStyle(archiveAction!).opacity).toBe("1"); + }, + { timeout: 4_000, interval: 16 }, + ); + + await page.getByTestId("composer-editor").hover(); + await vi.waitFor( + () => { + expect(getComputedStyle(archiveAction!).opacity).toBe("0"); + }, + { timeout: 4_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("shows the confirm archive action after clicking the archive button", async () => { + localStorage.setItem( + "t3code:client-settings:v1", + JSON.stringify({ + ...DEFAULT_CLIENT_SETTINGS, + confirmThreadArchive: true, + }), + ); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-archive-confirm-test" as MessageId, + targetText: "archive confirm target", + }), + }); + + try { + const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`); + + await expect.element(threadRow).toBeInTheDocument(); + await threadRow.hover(); + + const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`); + await expect.element(archiveButton).toBeInTheDocument(); + await archiveButton.click(); + + const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`); + await expect.element(confirmButton).toBeInTheDocument(); + await expect.element(confirmButton).toBeVisible(); + } finally { + localStorage.removeItem("t3code:client-settings:v1"); + await mounted.cleanup(); + } + }); + it("keeps the new thread selected after clicking the new-thread button", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, @@ -1476,21 +2155,16 @@ describe("ChatView timeline estimator parity (full app)", () => { // The composer editor should be present for the new draft thread. await waitForComposerEditor(); - // Simulate the snapshot sync arriving from the server after the draft - // thread has been promoted to a server thread (thread.create + turn.start - // succeeded). The snapshot now includes the new thread, and the sync - // should clear the draft without disrupting the route. - const { syncServerReadModel } = useStore.getState(); - syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId)); - - // Clear the draft now that the server thread exists (mirrors EventRouter behavior). - useComposerDraftStore.getState().clearDraftThread(newThreadId); + // Simulate the steady-state promotion path: the server emits + // `thread.created`, the client materializes the thread incrementally, + // and the draft is cleared by live batch effects. + await promoteDraftThreadViaDomainEvent(newThreadId); // The route should still be on the new thread — not redirected away. await waitForURL( mounted.router, (path) => path === newThreadPath, - "New thread should remain selected after snapshot sync clears the draft.", + "New thread should remain selected after server thread promotion clears the draft.", ); // The empty thread view and composer should still be visible. @@ -1812,9 +2486,7 @@ describe("ChatView timeline estimator parity (full app)", () => { ); const promotedThreadId = promotedThreadPath.slice(1) as ThreadId; - const { syncServerReadModel } = useStore.getState(); - syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId)); - useComposerDraftStore.getState().clearDraftThread(promotedThreadId); + await promoteDraftThreadViaDomainEvent(promotedThreadId); const freshThreadPath = await triggerChatNewShortcutUntilPath( mounted.router, @@ -1863,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.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index bf72ec0b84..80c842d91f 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,7 +1,14 @@ -import { ThreadId } from "@t3tools/contracts"; -import { describe, expect, it } from "vitest"; +import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { useStore } from "../store"; -import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic"; +import { + buildExpiredTerminalContextToastCopy, + createLocalDispatchSnapshot, + deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, + waitForStartedServerThread, +} from "./ChatView.logic"; describe("deriveComposerSendState", () => { it("treats expired terminal pills as non-sendable content", () => { @@ -67,3 +74,290 @@ describe("buildExpiredTerminalContextToastCopy", () => { }); }); }); + +const makeThread = (input?: { + id?: ThreadId; + latestTurn?: { + turnId: TurnId; + state: "running" | "completed"; + requestedAt: string; + startedAt: string | null; + completedAt: string | null; + } | null; +}) => ({ + id: input?.id ?? ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId: ProjectId.makeUnsafe("project-1"), + title: "Thread", + modelSelection: { provider: "codex" as const, model: "gpt-5.4" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + session: null, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:00.000Z", + latestTurn: input?.latestTurn + ? { + ...input.latestTurn, + assistantMessageId: null, + } + : null, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + useStore.setState((state) => ({ + ...state, + projects: [], + threads: [], + bootstrapComplete: true, + })); +}); + +describe("waitForStartedServerThread", () => { + it("resolves immediately when the thread is already started", async () => { + const threadId = ThreadId.makeUnsafe("thread-started"); + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(waitForStartedServerThread(threadId)).resolves.toBe(true); + }); + + it("waits for the thread to start via subscription updates", async () => { + const threadId = ThreadId.makeUnsafe("thread-wait"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const promise = waitForStartedServerThread(threadId, 500); + + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(promise).resolves.toBe(true); + }); + + it("handles the thread starting between the initial read and subscription setup", async () => { + const threadId = ThreadId.makeUnsafe("thread-race"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const originalSubscribe = useStore.subscribe.bind(useStore); + let raced = false; + vi.spyOn(useStore, "subscribe").mockImplementation((listener) => { + if (!raced) { + raced = true; + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-race"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + } + return originalSubscribe(listener); + }); + + await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true); + }); + + it("returns false after the timeout when the thread never starts", async () => { + vi.useFakeTimers(); + + const threadId = ThreadId.makeUnsafe("thread-timeout"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + const promise = waitForStartedServerThread(threadId, 500); + + await vi.advanceTimersByTimeAsync(500); + + await expect(promise).resolves.toBe(false); + }); +}); + +describe("hasServerAcknowledgedLocalDispatch", () => { + const projectId = ProjectId.makeUnsafe("project-1"); + const previousLatestTurn = { + turnId: TurnId.makeUnsafe("turn-1"), + state: "completed" as const, + requestedAt: "2026-03-29T00:00:00.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: "2026-03-29T00:00:10.000Z", + assistantMessageId: null, + }; + + const previousSession = { + provider: "codex" as const, + status: "ready" as const, + createdAt: "2026-03-29T00:00:00.000Z", + updatedAt: "2026-03-29T00:00:10.000Z", + orchestrationStatus: "idle" as const, + }; + + it("does not clear local dispatch before server state changes", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: previousSession, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(false); + }); + + it("clears local dispatch when a new turn is already settled", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: { + ...previousLatestTurn, + turnId: TurnId.makeUnsafe("turn-2"), + requestedAt: "2026-03-29T00:01:00.000Z", + startedAt: "2026-03-29T00:01:01.000Z", + completedAt: "2026-03-29T00:01:30.000Z", + }, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:01:30.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); + + it("clears local dispatch when the session changes without an observed running phase", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:00:11.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 0a9f242ed0..1821c65ed9 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1,8 +1,9 @@ -import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts"; -import { type ChatMessage, type Thread } from "../types"; +import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts"; +import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types"; import { randomUUID } from "~/lib/utils"; import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; import { Schema } from "effect"; +import { useStore } from "../store"; import { filterTerminalContextsWithText, stripInlineTerminalContextPlaceholders, @@ -32,8 +33,8 @@ export function buildLocalDraftThread( messages: [], error, createdAt: draftThread.createdAt, + archivedAt: null, latestTurn: null, - lastVisitedAt: draftThread.createdAt, branch: draftThread.branch, worktreePath: draftThread.worktreePath, turnDiffSummaries: [], @@ -74,8 +75,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[ return previewUrls; } -export type SendPhase = "idle" | "preparing-worktree" | "sending-turn"; - export interface PullRequestDialogState { initialReference: string | null; key: number; @@ -160,3 +159,116 @@ export function buildExpiredTerminalContextToastCopy( description: "Re-add it if you want that terminal output included.", }; } + +export function threadHasStarted(thread: Thread | null | undefined): boolean { + return Boolean( + thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null), + ); +} + +export async function waitForStartedServerThread( + threadId: ThreadId, + timeoutMs = 1_000, +): Promise { + const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId); + const thread = getThread(); + + if (threadHasStarted(thread)) { + return true; + } + + return await new Promise((resolve) => { + let settled = false; + let timeoutId: ReturnType | null = null; + const finish = (result: boolean) => { + if (settled) { + return; + } + settled = true; + if (timeoutId !== null) { + globalThis.clearTimeout(timeoutId); + } + unsubscribe(); + resolve(result); + }; + + const unsubscribe = useStore.subscribe((state) => { + if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) { + return; + } + finish(true); + }); + + if (threadHasStarted(getThread())) { + finish(true); + return; + } + + timeoutId = globalThis.setTimeout(() => { + finish(false); + }, timeoutMs); + }); +} + +export interface LocalDispatchSnapshot { + startedAt: string; + preparingWorktree: boolean; + latestTurnTurnId: TurnId | null; + latestTurnRequestedAt: string | null; + latestTurnStartedAt: string | null; + latestTurnCompletedAt: string | null; + sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null; + sessionUpdatedAt: string | null; +} + +export function createLocalDispatchSnapshot( + activeThread: Thread | undefined, + options?: { preparingWorktree?: boolean }, +): LocalDispatchSnapshot { + const latestTurn = activeThread?.latestTurn ?? null; + const session = activeThread?.session ?? null; + return { + startedAt: new Date().toISOString(), + preparingWorktree: Boolean(options?.preparingWorktree), + latestTurnTurnId: latestTurn?.turnId ?? null, + latestTurnRequestedAt: latestTurn?.requestedAt ?? null, + latestTurnStartedAt: latestTurn?.startedAt ?? null, + latestTurnCompletedAt: latestTurn?.completedAt ?? null, + sessionOrchestrationStatus: session?.orchestrationStatus ?? null, + sessionUpdatedAt: session?.updatedAt ?? null, + }; +} + +export function hasServerAcknowledgedLocalDispatch(input: { + localDispatch: LocalDispatchSnapshot | null; + phase: SessionPhase; + latestTurn: Thread["latestTurn"] | null; + session: Thread["session"] | null; + hasPendingApproval: boolean; + hasPendingUserInput: boolean; + threadError: string | null | undefined; +}): boolean { + if (!input.localDispatch) { + return false; + } + if ( + input.phase === "running" || + input.hasPendingApproval || + input.hasPendingUserInput || + Boolean(input.threadError) + ) { + return true; + } + + const latestTurn = input.latestTurn ?? null; + const session = input.session ?? null; + + return ( + input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) || + input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) || + input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) || + input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) || + input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) || + input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null) + ); +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 202ea45426..d6de629ca7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5,7 +5,6 @@ import { type MessageId, type ModelSelection, type ProjectScript, - type ModelSlug, type ProviderKind, type ProviderUserInputAnswers, type ProjectEntry, @@ -13,24 +12,23 @@ 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, RuntimeMode, + TerminalOpenInput, } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model"; +import { truncate } from "@t3tools/shared/String"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; 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 { @@ -43,6 +41,7 @@ import { replaceTextRange, } from "../composer-logic"; import { + deriveCompletionDividerBeforeEntryId, derivePendingApprovals, derivePendingUserInputs, derivePhase, @@ -65,21 +64,26 @@ import { type PendingUserInputDraftAnswer, } from "../pendingUserInput"; import { useStore } from "../store"; +import { useProjectById, useThreadById } from "../storeSelectors"; +import { useUiStateStore } from "../uiStateStore"; import { buildPlanImplementationThreadTitle, buildPlanImplementationPrompt, proposedPlanTitle, resolvePlanFollowUpSubmission, } from "../proposedPlan"; -import { truncateTitle } from "../truncateTitle"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, DEFAULT_THREAD_TERMINAL_ID, MAX_TERMINALS_PER_GROUP, type ChatMessage, + type SessionPhase, + type Thread, type TurnDiffSummary, } from "../types"; +import { LRUCache } from "../lib/lruCache"; + import { basenameOfPath } from "../vscode-icons"; import { useTheme } from "../hooks/useTheme"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; @@ -100,7 +104,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"; @@ -142,7 +145,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"; @@ -154,6 +162,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"; @@ -170,28 +179,110 @@ import { buildTemporaryWorktreeBranchName, cloneComposerImageForRetry, collectUserMessageBlobPreviewUrls, + createLocalDispatchSnapshot, deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, LastInvokedScriptByProjectSchema, + type LocalDispatchSnapshot, PullRequestDialogState, readFileAsDataUrl, revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, - SendPhase, + threadHasStarted, + 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 = {}; +type ThreadPlanCatalogEntry = Pick; + +const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500; +const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024; +const threadPlanCatalogCache = new LRUCache<{ + proposedPlans: Thread["proposedPlans"]; + entry: ThreadPlanCatalogEntry; +}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES); + +function estimateThreadPlanCatalogEntrySize(thread: Thread): number { + return Math.max( + 64, + thread.id.length + + thread.proposedPlans.reduce( + (total, plan) => + total + + plan.id.length + + plan.planMarkdown.length + + plan.updatedAt.length + + (plan.turnId?.length ?? 0), + 0, + ), + ); +} + +function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry { + const cached = threadPlanCatalogCache.get(thread.id); + if (cached && cached.proposedPlans === thread.proposedPlans) { + return cached.entry; + } + + const entry: ThreadPlanCatalogEntry = { + id: thread.id, + proposedPlans: thread.proposedPlans, + }; + threadPlanCatalogCache.set( + thread.id, + { + proposedPlans: thread.proposedPlans, + entry, + }, + estimateThreadPlanCatalogEntrySize(thread), + ); + return entry; +} + +function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] { + const selector = useMemo(() => { + let previousThreads: Array | null = null; + let previousEntries: ThreadPlanCatalogEntry[] = []; + + return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => { + const nextThreads = threadIds.map((threadId) => + state.threads.find((thread) => thread.id === threadId), + ); + const cachedThreads = previousThreads; + if ( + cachedThreads && + nextThreads.length === cachedThreads.length && + nextThreads.every((thread, index) => thread === cachedThreads[index]) + ) { + return previousEntries; + } + + previousThreads = nextThreads; + previousEntries = nextThreads.flatMap((thread) => + thread ? [toThreadPlanCatalogEntry(thread)] : [], + ); + return previousEntries; + }; + }, [threadIds]); + + return useStore(selector); +} + function formatOutgoingPrompt(params: { provider: ProviderKind; model: string | null; @@ -241,13 +332,87 @@ interface ChatViewProps { threadId: ThreadId; } +interface PendingPullRequestSetupRequest { + threadId: ThreadId; + worktreePath: string; + scriptId: string; +} + +function useLocalDispatchState(input: { + activeThread: Thread | undefined; + activeLatestTurn: Thread["latestTurn"] | null; + phase: SessionPhase; + activePendingApproval: ApprovalRequestId | null; + activePendingUserInput: ApprovalRequestId | null; + threadError: string | null | undefined; +}) { + const [localDispatch, setLocalDispatch] = useState(null); + + const beginLocalDispatch = useCallback( + (options?: { preparingWorktree?: boolean }) => { + const preparingWorktree = Boolean(options?.preparingWorktree); + setLocalDispatch((current) => { + if (current) { + return current.preparingWorktree === preparingWorktree + ? current + : { ...current, preparingWorktree }; + } + return createLocalDispatchSnapshot(input.activeThread, options); + }); + }, + [input.activeThread], + ); + + const resetLocalDispatch = useCallback(() => { + setLocalDispatch(null); + }, []); + + const serverAcknowledgedLocalDispatch = useMemo( + () => + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: input.phase, + latestTurn: input.activeLatestTurn, + session: input.activeThread?.session ?? null, + hasPendingApproval: input.activePendingApproval !== null, + hasPendingUserInput: input.activePendingUserInput !== null, + threadError: input.threadError, + }), + [ + input.activeLatestTurn, + input.activePendingApproval, + input.activePendingUserInput, + input.activeThread?.session, + input.phase, + input.threadError, + localDispatch, + ], + ); + + useEffect(() => { + if (!serverAcknowledgedLocalDispatch) { + return; + } + resetLocalDispatch(); + }, [resetLocalDispatch, serverAcknowledgedLocalDispatch]); + + return { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt: localDispatch?.startedAt ?? null, + isPreparingWorktree: localDispatch?.preparingWorktree ?? false, + isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch, + }; +} + export default function ChatView({ threadId }: ChatViewProps) { - const threads = useStore((store) => store.threads); - const projects = useStore((store) => store.projects); - const markThreadVisited = useStore((store) => store.markThreadVisited); - const syncServerReadModel = useStore((store) => store.syncServerReadModel); + const serverThread = useThreadById(threadId); const setStoreThreadError = useStore((store) => store.setError); const setStoreThreadBranch = useStore((store) => store.setThreadBranch); + const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); + const activeThreadLastVisitedAt = useUiStateStore( + (store) => store.threadLastVisitedAtById[threadId], + ); const settings = useSettings(); const setStickyComposerModelSelection = useComposerDraftStore( (store) => store.setStickyModelSelection, @@ -326,8 +491,6 @@ export default function ChatView({ threadId }: ChatViewProps) { const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState< Record >({}); - const [sendPhase, setSendPhase] = useState("idle"); - const [sendStartedAt, setSendStartedAt] = useState(null); const [isConnecting, _setIsConnecting] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); const [respondingRequestIds, setRespondingRequestIds] = useState([]); @@ -342,6 +505,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. @@ -352,6 +516,8 @@ export default function ChatView({ threadId }: ChatViewProps) { const [composerHighlightedItemId, setComposerHighlightedItemId] = useState(null); const [pullRequestDialogState, setPullRequestDialogState] = useState(null); + const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] = + useState(null); const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState< Record >({}); @@ -382,6 +548,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); @@ -460,8 +629,7 @@ export default function ChatView({ threadId }: ChatViewProps) { [composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId], ); - const serverThread = threads.find((t) => t.id === threadId); - const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId); + const fallbackDraftProject = useProjectById(draftThread?.projectId); const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null); const localDraftThread = useMemo( () => @@ -489,12 +657,25 @@ export default function ChatView({ threadId }: ChatViewProps) { const diffOpen = rawSearch.diff === "1"; const activeThreadId = activeThread?.id ?? null; const activeLatestTurn = activeThread?.latestTurn ?? null; + const threadPlanCatalog = useThreadPlanCatalog( + useMemo(() => { + const threadIds: ThreadId[] = []; + if (activeThread?.id) { + threadIds.push(activeThread.id); + } + const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId; + if (sourceThreadId && sourceThreadId !== activeThread?.id) { + threadIds.push(sourceThreadId); + } + return threadIds; + }, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]), + ); const activeContextWindow = useMemo( () => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []), [activeThread?.activities], ); const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); - const activeProject = projects.find((p) => p.id === activeThread?.projectId); + const activeProject = useProjectById(activeThread?.projectId); const openPullRequestDialog = useCallback( (reference?: string) => { @@ -529,14 +710,14 @@ export default function ChatView({ threadId }: ChatViewProps) { params: { threadId: storedDraftThread.threadId }, }); } - return; + return storedDraftThread.threadId; } const activeDraftThread = getDraftThread(threadId); if (!isServerThread && activeDraftThread?.projectId === activeProject.id) { setDraftThreadContext(threadId, input); setProjectDraftThreadId(activeProject.id, threadId, input); - return; + return threadId; } clearProjectDraftThreadId(activeProject.id); @@ -551,6 +732,7 @@ export default function ChatView({ threadId }: ChatViewProps) { to: "/$threadId", params: { threadId: nextThreadId }, }); + return nextThreadId; }, [ activeProject, @@ -567,48 +749,54 @@ export default function ChatView({ threadId }: ChatViewProps) { const handlePreparedPullRequestThread = useCallback( async (input: { branch: string; worktreePath: string | null }) => { - await openOrReuseProjectDraftThread({ + const targetThreadId = await openOrReuseProjectDraftThread({ branch: input.branch, worktreePath: input.worktreePath, envMode: input.worktreePath ? "worktree" : "local", }); + const setupScript = + input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null; + if (targetThreadId && input.worktreePath && setupScript) { + setPendingPullRequestSetupRequest({ + threadId: targetThreadId, + worktreePath: input.worktreePath, + scriptId: setupScript.id, + }); + } else { + setPendingPullRequestSetupRequest(null); + } }, - [openOrReuseProjectDraftThread], + [activeProject, openOrReuseProjectDraftThread], ); useEffect(() => { - if (!activeThread?.id) return; + if (!serverThread?.id) return; if (!latestTurnSettled) return; if (!activeLatestTurn?.completedAt) return; const turnCompletedAt = Date.parse(activeLatestTurn.completedAt); if (Number.isNaN(turnCompletedAt)) return; - const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN; + const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN; if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return; - markThreadVisited(activeThread.id); + markThreadVisited(serverThread.id); }, [ - activeThread?.id, - activeThread?.lastVisitedAt, activeLatestTurn?.completedAt, + activeThreadLastVisitedAt, latestTurnSettled, markThreadVisited, + serverThread?.id, ]); const sessionProvider = activeThread?.session?.provider ?? null; const selectedProviderByThreadId = composerDraft.activeProvider ?? null; const threadProvider = activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null; - const hasThreadStarted = Boolean( - activeThread && - (activeThread.latestTurn !== null || - activeThread.messages.length > 0 || - activeThread.session !== null), - ); + const hasThreadStarted = threadHasStarted(activeThread); 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", @@ -646,15 +834,6 @@ export default function ChatView({ threadId }: ChatViewProps) { ); const selectedModelForPicker = selectedModel; const phase = derivePhase(activeThread?.session ?? null); - const isSendBusy = sendPhase !== "idle"; - const isPreparingWorktree = sendPhase === "preparing-worktree"; - const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; - const nowIso = new Date(nowTick).toISOString(); - const activeWorkStartedAt = deriveActiveWorkStartedAt( - activeLatestTurn, - activeThread?.session ?? null, - sendStartedAt, - ); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo( () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined), @@ -717,12 +896,12 @@ export default function ChatView({ threadId }: ChatViewProps) { const sidebarProposedPlan = useMemo( () => findSidebarProposedPlan({ - threads, + threads: threadPlanCatalog, latestTurn: activeLatestTurn, latestTurnSettled, threadId: activeThread?.id ?? null, }), - [activeLatestTurn, activeThread?.id, latestTurnSettled, threads], + [activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog], ); const activePlan = useMemo( () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined), @@ -734,12 +913,55 @@ export default function ChatView({ threadId }: ChatViewProps) { latestTurnSettled && hasActionableProposedPlan(activeProposedPlan); const activePendingApproval = pendingApprovals[0] ?? null; + const { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt, + isPreparingWorktree, + isSendBusy, + } = useLocalDispatchState({ + activeThread, + activeLatestTurn, + phase, + activePendingApproval: activePendingApproval?.requestId ?? null, + activePendingUserInput: activePendingUserInput?.requestId ?? null, + threadError: activeThread?.error, + }); + const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; + const nowIso = new Date(nowTick).toISOString(); + const activeWorkStartedAt = deriveActiveWorkStartedAt( + activeLatestTurn, + activeThread?.session ?? null, + localDispatchStartedAt, + ); const isComposerApprovalState = activePendingApproval !== null; const hasComposerHeader = isComposerApprovalState || 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; @@ -962,35 +1184,9 @@ export default function ChatView({ threadId }: ChatViewProps) { ]); const completionDividerBeforeEntryId = useMemo(() => { if (!latestTurnSettled) return null; - if (!activeLatestTurn?.startedAt) return null; - if (!activeLatestTurn.completedAt) return null; if (!completionSummary) return null; - - const turnStartedAt = Date.parse(activeLatestTurn.startedAt); - const turnCompletedAt = Date.parse(activeLatestTurn.completedAt); - if (Number.isNaN(turnStartedAt)) return null; - if (Number.isNaN(turnCompletedAt)) return null; - - let inRangeMatch: string | null = null; - let fallbackMatch: string | null = null; - for (const timelineEntry of timelineEntries) { - if (timelineEntry.kind !== "message") continue; - if (timelineEntry.message.role !== "assistant") continue; - const messageAt = Date.parse(timelineEntry.message.createdAt); - if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue; - fallbackMatch = timelineEntry.id; - if (messageAt <= turnCompletedAt) { - inRangeMatch = timelineEntry.id; - } - } - return inRangeMatch ?? fallbackMatch; - }, [ - activeLatestTurn?.completedAt, - activeLatestTurn?.startedAt, - completionSummary, - latestTurnSettled, - timelineEntries, - ]); + return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn); + }, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]); const gitCwd = activeProject ? projectScriptCwd({ project: { cwd: activeProject.cwd }, @@ -1007,8 +1203,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 ?? [], @@ -1144,25 +1340,43 @@ export default function ChatView({ threadId }: ChatViewProps) { }, [activeProjectCwd, activeThreadWorktreePath]); // Default true while loading to avoid toolbar flicker. const isGitRepo = branchesQuery.data?.isRepo ?? true; + const terminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: true, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); + const nonTerminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: false, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); const terminalToggleShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.toggle"), [keybindings], ); const splitTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.split"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const newTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.new"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const closeTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.close"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const diffPanelShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "diff.toggle"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions), + [keybindings, nonTerminalShortcutLabelOptions], ); const onToggleDiff = useCallback(() => { void navigate({ @@ -1194,7 +1408,7 @@ export default function ChatView({ threadId }: ChatViewProps) { const setThreadError = useCallback( (targetThreadId: ThreadId | null, error: string | null) => { if (!targetThreadId) return; - if (threads.some((thread) => thread.id === targetThreadId)) { + if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) { setStoreThreadError(targetThreadId, error); return; } @@ -1208,7 +1422,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }; }); }, - [setStoreThreadError, threads], + [setStoreThreadError], ); const focusComposer = useCallback(() => { @@ -1375,7 +1589,7 @@ export default function ChatView({ threadId }: ChatViewProps) { worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null, ...(options?.env ? { extraEnv: options.env } : {}), }); - const openTerminalInput: Parameters[0] = shouldCreateNewTerminal + const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal ? { threadId: activeThreadId, terminalId: targetTerminalId, @@ -1420,6 +1634,45 @@ export default function ChatView({ threadId }: ChatViewProps) { terminalState.terminalIds, ], ); + + useEffect(() => { + if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) { + return; + } + if (pendingPullRequestSetupRequest.threadId !== activeThreadId) { + return; + } + if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) { + return; + } + + const setupScript = + activeProject.scripts.find( + (script) => script.id === pendingPullRequestSetupRequest.scriptId, + ) ?? null; + setPendingPullRequestSetupRequest(null); + if (!setupScript) { + return; + } + + void runProjectScript(setupScript, { + cwd: pendingPullRequestSetupRequest.worktreePath, + worktreePath: pendingPullRequestSetupRequest.worktreePath, + rememberAsLastInvoked: false, + }).catch((error) => { + toastManager.add({ + type: "error", + title: "Failed to run setup script.", + description: error instanceof Error ? error.message : "An error occurred.", + }); + }); + }, [ + activeProject, + activeThread, + activeThreadId, + pendingPullRequestSetupRequest, + runProjectScript, + ]); const persistProjectScripts = useCallback( async (input: { projectId: ProjectId; @@ -1446,10 +1699,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) => { @@ -1817,23 +2069,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; @@ -1848,7 +2133,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(); @@ -1945,15 +2235,14 @@ export default function ChatView({ threadId }: ChatViewProps) { } return []; }); - setSendPhase("idle"); - setSendStartedAt(null); + resetLocalDispatch(); setComposerHighlightedItemId(null); setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length)); setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length)); dragDepthRef.current = 0; setIsDragOverComposer(false); setExpandedImage(null); - }, [threadId]); + }, [resetLocalDispatch, threadId]); useEffect(() => { let cancelled = false; @@ -2086,37 +2375,6 @@ export default function ChatView({ threadId }: ChatViewProps) { }; }, [phase]); - const beginSendPhase = useCallback((nextPhase: Exclude) => { - setSendStartedAt((current) => current ?? new Date().toISOString()); - setSendPhase(nextPhase); - }, []); - - const resetSendPhase = useCallback(() => { - setSendPhase("idle"); - setSendStartedAt(null); - }, []); - - useEffect(() => { - if (sendPhase === "idle") { - return; - } - if ( - phase === "running" || - activePendingApproval !== null || - activePendingUserInput !== null || - activeThread?.error - ) { - resetSendPhase(); - } - }, [ - activePendingApproval, - activePendingUserInput, - activeThread?.error, - phase, - resetSendPhase, - sendPhase, - ]); - useEffect(() => { if (!activeThreadId) return; const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false; @@ -2454,7 +2712,7 @@ export default function ChatView({ threadId }: ChatViewProps) { } sendInFlightRef.current = true; - beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn"); + beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); const composerImagesSnapshot = [...composerImages]; const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; @@ -2528,7 +2786,7 @@ export default function ChatView({ threadId }: ChatViewProps) { await (async () => { // On first message: lock in branch + create worktree if needed. if (baseBranchForWorktree) { - beginSendPhase("preparing-worktree"); + beginLocalDispatch({ preparingWorktree: true }); const newBranch = buildTemporaryWorktreeBranchName(); const result = await createWorktreeMutation.mutateAsync({ cwd: activeProject.cwd, @@ -2568,7 +2826,7 @@ export default function ChatView({ threadId }: ChatViewProps) { titleSeed = "New thread"; } } - const title = truncateTitle(titleSeed); + const title = truncate(titleSeed); const threadCreateModelSelection: ModelSelection = { provider: selectedProvider, model: @@ -2640,7 +2898,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); } - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); const turnAttachments = await turnAttachmentsPromise; await api.orchestration.dispatchCommand({ type: "thread.turn.start", @@ -2653,6 +2911,7 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: turnAttachments, }, modelSelection: selectedModelSelection, + titleSeed: title, runtimeMode, interactionMode, createdAt: messageCreatedAt, @@ -2696,7 +2955,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); sendInFlightRef.current = false; if (!turnStartSucceeded) { - resetSendPhase(); + resetLocalDispatch(); } }; @@ -2895,7 +3154,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); sendInFlightRef.current = true; - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); setThreadError(threadIdForSend, null); setOptimisticUserMessages((existing) => [ ...existing, @@ -2934,6 +3193,7 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: [], }, modelSelection: selectedModelSelection, + titleSeed: activeThread.title, runtimeMode, interactionMode: nextInteractionMode, ...(nextInteractionMode === "default" && activeProposedPlan @@ -2963,19 +3223,19 @@ export default function ChatView({ threadId }: ChatViewProps) { err instanceof Error ? err.message : "Failed to send plan follow-up.", ); sendInFlightRef.current = false; - resetSendPhase(); + resetLocalDispatch(); } }, [ activeThread, activeProposedPlan, - beginSendPhase, + beginLocalDispatch, forceStickToBottom, isConnecting, isSendBusy, isServerThread, persistThreadSettingsForNextTurn, - resetSendPhase, + resetLocalDispatch, runtimeMode, selectedPromptEffort, selectedModelSelection, @@ -3013,14 +3273,14 @@ export default function ChatView({ threadId }: ChatViewProps) { effort: selectedPromptEffort, text: implementationPrompt, }); - const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown)); + const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown)); const nextThreadModelSelection: ModelSelection = selectedModelSelection; sendInFlightRef.current = true; - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); const finish = () => { sendInFlightRef.current = false; - resetSendPhase(); + resetLocalDispatch(); }; await api.orchestration @@ -3049,14 +3309,20 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: [], }, modelSelection: selectedModelSelection, + titleSeed: nextThreadTitle, runtimeMode, interactionMode: "default", + sourceProposedPlan: { + threadId: activeThread.id, + planId: activeProposedPlan.id, + }, createdAt, }); }) - .then(() => api.orchestration.getSnapshot()) - .then((snapshot) => { - syncServerReadModel(snapshot); + .then(() => { + return waitForStartedServerThread(nextThreadId); + }) + .then(() => { // Signal that the plan sidebar should open on the new thread. planSidebarOpenOnNextThreadRef.current = true; return navigate({ @@ -3072,12 +3338,6 @@ export default function ChatView({ threadId }: ChatViewProps) { threadId: nextThreadId, }) .catch(() => undefined); - await api.orchestration - .getSnapshot() - .then((snapshot) => { - syncServerReadModel(snapshot); - }) - .catch(() => undefined); toastManager.add({ type: "error", title: "Could not start implementation thread", @@ -3090,23 +3350,22 @@ export default function ChatView({ threadId }: ChatViewProps) { activeProject, activeProposedPlan, activeThread, - beginSendPhase, + beginLocalDispatch, isConnecting, isSendBusy, isServerThread, navigate, - resetSendPhase, + resetLocalDispatch, runtimeMode, selectedPromptEffort, selectedModelSelection, selectedProvider, selectedProviderModels, - syncServerReadModel, selectedModel, ]); const onProviderModelSelect = useCallback( - (provider: ProviderKind, model: ModelSlug) => { + (provider: ProviderKind, model: string) => { if (!activeThread) return; if (lockedProvider !== null && provider !== lockedProvider) { scheduleComposerFocus(); @@ -3602,7 +3861,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
) : (
@@ -3927,8 +4187,12 @@ export default function ChatView({ threadId }: ChatViewProps) { {/* Right side: send / stop button */}
{activeContextWindow ? ( @@ -3938,156 +4202,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 09b84444e2..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 { @@ -765,7 +754,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions } > - + {quickAction.label} @@ -781,12 +770,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions onClick={runQuickAction} > - + {quickAction.label} )} - + { if (open) void invalidateGitQueries(queryClient); diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index e64a981eec..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)?:\/\/.*/); @@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig { installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: NOW_ISO, models: [], }, @@ -102,6 +102,7 @@ function createMinimalSnapshot(): OrchestrationReadModel { latestTurn: null, createdAt: NOW_ISO, updatedAt: NOW_ISO, + archivedAt: null, deletedAt: null, messages: [ { @@ -178,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[] { @@ -307,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: {}, @@ -322,7 +320,7 @@ describe("Keybindings update toast", () => { useStore.setState({ projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }); }); diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx new file mode 100644 index 0000000000..58426f50ba --- /dev/null +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -0,0 +1,34 @@ +import { FolderIcon } from "lucide-react"; +import { useState } from "react"; +import { resolveServerUrl } from "~/lib/utils"; + +const loadedProjectFaviconSrcs = new Set(); + +export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) { + const src = resolveServerUrl({ + protocol: "http", + pathname: "/api/project-favicon", + searchParams: { cwd }, + }); + const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => + loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", + ); + + return ( + <> + {status !== "loaded" ? ( + + ) : null} + { + loadedProjectFaviconSrcs.add(src); + setStatus("loaded"); + }} + onError={() => setStatus("error")} + /> + + ); +} diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 4d6c5eef78..11b08cc2cf 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -277,11 +277,11 @@ export default function ProjectScriptsControl({ title={`Run ${primaryScript.name}`} > - + {primaryScript.name} - + } @@ -342,7 +342,7 @@ export default function ProjectScriptsControl({ ) : ( diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 8b1ed51220..2a69facd10 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -153,9 +153,9 @@ export function PullRequestThreadDialog({ const validationMessage = !referenceDirty ? null : reference.trim().length === 0 - ? "Paste a GitHub pull request URL or enter 123 / #123." + ? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123." : parsedReference === null - ? "Use a GitHub pull request URL, 123, or #123." + ? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123." : null; const errorMessage = validationMessage ?? @@ -191,7 +191,7 @@ export function PullRequestThreadDialog({ Pull request { setReferenceDirty(true); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index dcfe3f6b69..d4cd25db4c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1,10 +1,15 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + createThreadJumpHintVisibilityController, + getVisibleSidebarThreadIds, + resolveAdjacentThreadId, getFallbackThreadIdAfterDelete, getVisibleThreadsForProject, getProjectSortTimestamp, hasUnseenCompletion, + isContextMenuPointerDown, + orderItemsByPreferredIds, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, @@ -12,8 +17,9 @@ import { shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, sortThreadsForSidebar, + THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; -import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -24,7 +30,7 @@ import { function makeLatestTurn(overrides?: { completedAt?: string | null; startedAt?: string | null; -}): Parameters[0]["latestTurn"] { +}): OrchestrationLatestTurn { return { turnId: "turn-1" as never, state: "completed", @@ -49,6 +55,68 @@ describe("hasUnseenCompletion", () => { }); }); +describe("createThreadJumpHintVisibilityController", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("delays showing jump hints until the configured delay elapses", () => { + const visibilityChanges: boolean[] = []; + const controller = createThreadJumpHintVisibilityController({ + delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS, + onVisibilityChange: (visible) => { + visibilityChanges.push(visible); + }, + }); + + controller.sync(true); + vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1); + + expect(visibilityChanges).toEqual([]); + + vi.advanceTimersByTime(1); + + expect(visibilityChanges).toEqual([true]); + }); + + it("hides immediately when the modifiers are released", () => { + const visibilityChanges: boolean[] = []; + const controller = createThreadJumpHintVisibilityController({ + delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS, + onVisibilityChange: (visible) => { + visibilityChanges.push(visible); + }, + }); + + controller.sync(true); + vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS); + controller.sync(false); + + expect(visibilityChanges).toEqual([true, false]); + }); + + it("cancels a pending reveal when the modifier is released early", () => { + const visibilityChanges: boolean[] = []; + const controller = createThreadJumpHintVisibilityController({ + delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS, + onVisibilityChange: (visible) => { + visibilityChanges.push(visible); + }, + }); + + controller.sync(true); + vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2)); + controller.sync(false); + vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS); + + expect(visibilityChanges).toEqual([]); + }); +}); + describe("shouldClearThreadSelectionOnMouseDown", () => { it("preserves selection for thread items", () => { const child = { @@ -96,6 +164,177 @@ describe("resolveSidebarNewThreadEnvMode", () => { }); }); +describe("orderItemsByPreferredIds", () => { + it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => { + const ordered = orderItemsByPreferredIds({ + items: [ + { id: ProjectId.makeUnsafe("project-1"), name: "One" }, + { id: ProjectId.makeUnsafe("project-2"), name: "Two" }, + { id: ProjectId.makeUnsafe("project-3"), name: "Three" }, + ], + preferredIds: [ + ProjectId.makeUnsafe("project-3"), + ProjectId.makeUnsafe("project-missing"), + ProjectId.makeUnsafe("project-1"), + ], + getId: (project) => project.id, + }); + + expect(ordered.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-3"), + ProjectId.makeUnsafe("project-1"), + ProjectId.makeUnsafe("project-2"), + ]); + }); + + it("does not duplicate items when preferred ids repeat", () => { + const ordered = orderItemsByPreferredIds({ + items: [ + { id: ProjectId.makeUnsafe("project-1"), name: "One" }, + { id: ProjectId.makeUnsafe("project-2"), name: "Two" }, + ], + preferredIds: [ + ProjectId.makeUnsafe("project-2"), + ProjectId.makeUnsafe("project-1"), + ProjectId.makeUnsafe("project-2"), + ], + getId: (project) => project.id, + }); + + expect(ordered.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-2"), + ProjectId.makeUnsafe("project-1"), + ]); + }); +}); + +describe("resolveAdjacentThreadId", () => { + it("resolves adjacent thread ids in ordered sidebar traversal", () => { + const threads = [ + ThreadId.makeUnsafe("thread-1"), + ThreadId.makeUnsafe("thread-2"), + ThreadId.makeUnsafe("thread-3"), + ]; + + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[1] ?? null, + direction: "previous", + }), + ).toBe(threads[0]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[1] ?? null, + direction: "next", + }), + ).toBe(threads[2]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: null, + direction: "next", + }), + ).toBe(threads[0]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: null, + direction: "previous", + }), + ).toBe(threads[2]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[0] ?? null, + direction: "previous", + }), + ).toBeNull(); + }); +}); + +describe("getVisibleSidebarThreadIds", () => { + it("returns only the rendered visible thread order across projects", () => { + expect( + getVisibleSidebarThreadIds([ + { + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-12") }, + { id: ThreadId.makeUnsafe("thread-11") }, + { id: ThreadId.makeUnsafe("thread-10") }, + ], + }, + { + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-8") }, + { id: ThreadId.makeUnsafe("thread-6") }, + ], + }, + ]), + ).toEqual([ + ThreadId.makeUnsafe("thread-12"), + ThreadId.makeUnsafe("thread-11"), + ThreadId.makeUnsafe("thread-10"), + ThreadId.makeUnsafe("thread-8"), + ThreadId.makeUnsafe("thread-6"), + ]); + }); + + it("skips threads from collapsed projects whose thread panels are not shown", () => { + expect( + getVisibleSidebarThreadIds([ + { + shouldShowThreadPanel: false, + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-hidden-2") }, + { id: ThreadId.makeUnsafe("thread-hidden-1") }, + ], + }, + { + shouldShowThreadPanel: true, + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-12") }, + { id: ThreadId.makeUnsafe("thread-11") }, + ], + }, + ]), + ).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]); + }); +}); + +describe("isContextMenuPointerDown", () => { + it("treats secondary-button presses as context menu gestures on all platforms", () => { + expect( + isContextMenuPointerDown({ + button: 2, + ctrlKey: false, + isMac: false, + }), + ).toBe(true); + }); + + it("treats ctrl+primary-click as a context menu gesture on macOS", () => { + expect( + isContextMenuPointerDown({ + button: 0, + ctrlKey: true, + isMac: true, + }), + ).toBe(true); + }); + + it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => { + expect( + isContextMenuPointerDown({ + button: 0, + ctrlKey: true, + isMac: false, + }), + ).toBe(false); + }); +}); + describe("resolveThreadStatusPill", () => { const baseThread = { interactionMode: "plan" as const, @@ -320,6 +559,9 @@ describe("getVisibleThreadsForProject", () => { ThreadId.makeUnsafe("thread-6"), ThreadId.makeUnsafe("thread-8"), ]); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ + ThreadId.makeUnsafe("thread-7"), + ]); }); it("returns all threads when the list is expanded", () => { @@ -340,6 +582,7 @@ describe("getVisibleThreadsForProject", () => { expect(result.visibleThreads.map((thread) => thread.id)).toEqual( threads.map((thread) => thread.id), ); + expect(result.hiddenThreads).toEqual([]); }); }); @@ -354,7 +597,6 @@ function makeProject(overrides: Partial = {}): Project { model: "gpt-5.4", ...defaultModelSelection, }, - expanded: true, createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:00:00.000Z", scripts: [], @@ -380,6 +622,7 @@ function makeThread(overrides: Partial = {}): Thread { proposedPlans: [], error: null, createdAt: "2026-03-09T10:00:00.000Z", + archivedAt: null, updatedAt: "2026-03-09T10:00:00.000Z", latestTurn: null, branch: null, @@ -697,6 +940,43 @@ describe("sortProjectsForSidebar", () => { ]); }); + it("ignores archived threads when sorting projects", () => { + const sorted = sortProjectsForSidebar( + [ + makeProject({ + id: ProjectId.makeUnsafe("project-1"), + name: "Visible project", + updatedAt: "2026-03-09T10:01:00.000Z", + }), + makeProject({ + id: ProjectId.makeUnsafe("project-2"), + name: "Archived-only project", + updatedAt: "2026-03-09T10:00:00.000Z", + }), + ], + [ + makeThread({ + id: ThreadId.makeUnsafe("thread-visible"), + projectId: ProjectId.makeUnsafe("project-1"), + updatedAt: "2026-03-09T10:02:00.000Z", + archivedAt: null, + }), + makeThread({ + id: ThreadId.makeUnsafe("thread-archived"), + projectId: ProjectId.makeUnsafe("project-2"), + updatedAt: "2026-03-09T10:10:00.000Z", + archivedAt: "2026-03-09T10:11:00.000Z", + }), + ].filter((thread) => thread.archivedAt === null), + "updated_at", + ); + + expect(sorted.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-1"), + ProjectId.makeUnsafe("project-2"), + ]); + }); + it("returns the project timestamp when no threads are present", () => { const timestamp = getProjectSortTimestamp( makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }), diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 6ca29d27e9..16c7752f74 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,3 +1,4 @@ +import * as React from "react"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; import type { Thread } from "../types"; import { cn } from "../lib/utils"; @@ -8,6 +9,7 @@ import { } from "../session-logic"; export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]"; +export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100; export type SidebarNewThreadEnvMode = "local" | "worktree"; type SidebarProject = { id: string; @@ -15,7 +17,12 @@ type SidebarProject = { createdAt?: string | undefined; updatedAt?: string | undefined; }; -type SidebarThreadSortInput = Pick; +type SidebarThreadSortInput = Pick & { + latestUserMessageAt?: string | null; + messages?: Pick[]; +}; + +export type ThreadTraversalDirection = "previous" | "next"; export interface ThreadStatusPill { label: @@ -41,8 +48,95 @@ const THREAD_STATUS_PRIORITY: Record = { type ThreadStatusInput = Pick< Thread, - "interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session" ->; + "interactionMode" | "latestTurn" | "proposedPlans" | "session" +> & { + lastVisitedAt?: string | undefined; +}; + +export interface ThreadJumpHintVisibilityController { + sync: (shouldShow: boolean) => void; + dispose: () => void; +} + +export function createThreadJumpHintVisibilityController(input: { + delayMs: number; + onVisibilityChange: (visible: boolean) => void; + setTimeoutFn?: typeof globalThis.setTimeout; + clearTimeoutFn?: typeof globalThis.clearTimeout; +}): ThreadJumpHintVisibilityController { + const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout; + const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout; + let isVisible = false; + let timeoutId: NodeJS.Timeout | null = null; + + const clearPendingShow = () => { + if (timeoutId === null) { + return; + } + clearTimeoutFn(timeoutId); + timeoutId = null; + }; + + return { + sync: (shouldShow) => { + if (!shouldShow) { + clearPendingShow(); + if (isVisible) { + isVisible = false; + input.onVisibilityChange(false); + } + return; + } + + if (isVisible || timeoutId !== null) { + return; + } + + timeoutId = setTimeoutFn(() => { + timeoutId = null; + isVisible = true; + input.onVisibilityChange(true); + }, input.delayMs); + }, + dispose: () => { + clearPendingShow(); + }, + }; +} + +export function useThreadJumpHintVisibility(): { + showThreadJumpHints: boolean; + updateThreadJumpHintsVisibility: (shouldShow: boolean) => void; +} { + const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false); + const controllerRef = React.useRef(null); + + React.useEffect(() => { + const controller = createThreadJumpHintVisibilityController({ + delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS, + onVisibilityChange: (visible) => { + setShowThreadJumpHints(visible); + }, + setTimeoutFn: window.setTimeout.bind(window), + clearTimeoutFn: window.clearTimeout.bind(window), + }); + controllerRef.current = controller; + + return () => { + controller.dispose(); + controllerRef.current = null; + }; + }, []); + + const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => { + controllerRef.current?.sync(shouldShow); + }, []); + + return { + showThreadJumpHints, + updateThreadJumpHintsVisibility, + }; +} export function hasUnseenCompletion(thread: ThreadStatusInput): boolean { if (!thread.latestTurn?.completedAt) return false; @@ -67,6 +161,85 @@ export function resolveSidebarNewThreadEnvMode(input: { return input.requestedEnvMode ?? input.defaultEnvMode; } +export function orderItemsByPreferredIds(input: { + items: readonly TItem[]; + preferredIds: readonly TId[]; + getId: (item: TItem) => TId; +}): TItem[] { + const { getId, items, preferredIds } = input; + if (preferredIds.length === 0) { + return [...items]; + } + + const itemsById = new Map(items.map((item) => [getId(item), item] as const)); + const preferredIdSet = new Set(preferredIds); + const emittedPreferredIds = new Set(); + const ordered = preferredIds.flatMap((id) => { + if (emittedPreferredIds.has(id)) { + return []; + } + const item = itemsById.get(id); + if (!item) { + return []; + } + emittedPreferredIds.add(id); + return [item]; + }); + const remaining = items.filter((item) => !preferredIdSet.has(getId(item))); + return [...ordered, ...remaining]; +} + +export function getVisibleSidebarThreadIds( + renderedProjects: readonly { + shouldShowThreadPanel?: boolean; + renderedThreads: readonly { + id: TThreadId; + }[]; + }[], +): TThreadId[] { + return renderedProjects.flatMap((renderedProject) => + renderedProject.shouldShowThreadPanel === false + ? [] + : renderedProject.renderedThreads.map((thread) => thread.id), + ); +} + +export function resolveAdjacentThreadId(input: { + threadIds: readonly T[]; + currentThreadId: T | null; + direction: ThreadTraversalDirection; +}): T | null { + const { currentThreadId, direction, threadIds } = input; + + if (threadIds.length === 0) { + return null; + } + + if (currentThreadId === null) { + return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null); + } + + const currentIndex = threadIds.indexOf(currentThreadId); + if (currentIndex === -1) { + return null; + } + + if (direction === "previous") { + return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null; + } + + return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null; +} + +export function isContextMenuPointerDown(input: { + button: number; + ctrlKey: boolean; + isMac: boolean; +}): boolean { + if (input.button === 2) return true; + return input.isMac && input.button === 0 && input.ctrlKey; +} + export function resolveThreadRowClassName(input: { isActive: boolean; isSelected: boolean; @@ -187,14 +360,15 @@ export function resolveProjectStatusIndicator( return highestPriorityStatus; } -export function getVisibleThreadsForProject(input: { - threads: readonly Thread[]; - activeThreadId: Thread["id"] | undefined; +export function getVisibleThreadsForProject>(input: { + threads: readonly T[]; + activeThreadId: T["id"] | undefined; isThreadListExpanded: boolean; previewLimit: number; }): { hasHiddenThreads: boolean; - visibleThreads: Thread[]; + visibleThreads: T[]; + hiddenThreads: T[]; } { const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input; const hasHiddenThreads = threads.length > previewLimit; @@ -202,6 +376,7 @@ export function getVisibleThreadsForProject(input: { if (!hasHiddenThreads || isThreadListExpanded) { return { hasHiddenThreads, + hiddenThreads: [], visibleThreads: [...threads], }; } @@ -210,6 +385,7 @@ export function getVisibleThreadsForProject(input: { if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) { return { hasHiddenThreads: true, + hiddenThreads: threads.slice(previewLimit), visibleThreads: previewThreads, }; } @@ -218,6 +394,7 @@ export function getVisibleThreadsForProject(input: { if (!activeThread) { return { hasHiddenThreads: true, + hiddenThreads: threads.slice(previewLimit), visibleThreads: previewThreads, }; } @@ -226,6 +403,7 @@ export function getVisibleThreadsForProject(input: { return { hasHiddenThreads: true, + hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)), visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)), }; } @@ -237,9 +415,13 @@ function toSortableTimestamp(iso: string | undefined): number | null { } function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number { + if (thread.latestUserMessageAt) { + return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY; + } + let latestUserMessageTimestamp: number | null = null; - for (const message of thread.messages) { + for (const message of thread.messages ?? []) { if (message.role !== "user") continue; const messageTimestamp = toSortableTimestamp(message.createdAt); if (messageTimestamp === null) continue; @@ -267,7 +449,7 @@ function getThreadSortTimestamp( } export function sortThreadsForSidebar< - T extends Pick, + T extends Pick & SidebarThreadSortInput, >(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] { return threads.toSorted((left, right) => { const rightTimestamp = getThreadSortTimestamp(right, sortOrder); @@ -280,7 +462,7 @@ export function sortThreadsForSidebar< } export function getFallbackThreadIdAfterDelete< - T extends Pick, + T extends Pick & SidebarThreadSortInput, >(input: { threads: readonly T[]; deletedThreadId: T["id"]; @@ -324,7 +506,10 @@ export function getProjectSortTimestamp( return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY; } -export function sortProjectsForSidebar( +export function sortProjectsForSidebar< + TProject extends SidebarProject, + TThread extends Pick & SidebarThreadSortInput, +>( projects: readonly TProject[], threads: readonly TThread[], sortOrder: SidebarProjectSortOrder, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 6c531b1e7a..c819ce81cd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,18 +1,27 @@ import { - ArrowLeftIcon, + ArchiveIcon, ArrowUpDownIcon, ChevronRightIcon, FolderIcon, GitPullRequestIcon, PlusIcon, - RocketIcon, SettingsIcon, SquarePenIcon, TerminalIcon, TriangleAlertIcon, } from "lucide-react"; +import { ProjectFavicon } from "./ProjectFavicon"; import { autoAnimate } from "@formkit/auto-animate"; -import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react"; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type MouseEvent, + type PointerEvent, +} from "react"; +import { useShallow } from "zustand/react/shallow"; import { DndContext, type DragCancelEvent, @@ -34,9 +43,8 @@ import { ProjectId, ThreadId, type GitStatusResult, - type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; -import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useQueries } from "@tanstack/react-query"; import { useLocation, useNavigate, useParams } from "@tanstack/react-router"; import { type SidebarProjectSortOrder, @@ -44,31 +52,40 @@ import { } from "@t3tools/contracts/settings"; import { isElectron } from "../env"; import { APP_STAGE_LABEL, APP_VERSION } from "../branding"; +import { isTerminalFocused } from "../lib/terminalFocus"; import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils"; import { useStore } from "../store"; -import { shortcutLabelForCommand } from "../keybindings"; +import { useUiStateStore } from "../uiStateStore"; +import { + resolveShortcutCommand, + shortcutLabelForCommand, + shouldShowThreadJumpHints, + threadJumpCommandForIndex, + threadJumpIndexFromCommand, + threadTraversalDirectionFromCommand, +} from "../keybindings"; import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic"; -import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery"; -import { serverConfigQueryOptions } from "../lib/serverReactQuery"; +import { gitStatusQueryOptions } from "../lib/gitReactQuery"; import { readNativeApi } from "../nativeApi"; import { useComposerDraftStore } from "../composerDraftStore"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; + +import { useThreadActions } from "../hooks/useThreadActions"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { toastManager } from "./ui/toast"; +import { formatRelativeTimeLabel } from "../timestampFormat"; +import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; import { getArm64IntelBuildWarningDescription, getDesktopUpdateActionError, - getDesktopUpdateButtonTooltip, + getDesktopUpdateInstallConfirmationMessage, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, shouldShowArm64IntelBuildWarning, - shouldHighlightDesktopUpdateError, - shouldShowDesktopUpdateButton, shouldToastDesktopUpdateActionResult, } from "./desktopUpdate.logic"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; import { Button } from "./ui/button"; -import { Collapsible, CollapsibleContent } from "./ui/collapsible"; import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { @@ -87,23 +104,27 @@ import { SidebarTrigger, } from "./ui/sidebar"; import { useThreadSelectionStore } from "../threadSelectionStore"; -import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup"; import { isNonEmpty as isNonEmptyString } from "effect/String"; import { - getFallbackThreadIdAfterDelete, + getVisibleSidebarThreadIds, getVisibleThreadsForProject, + resolveAdjacentThreadId, + isContextMenuPointerDown, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, resolveThreadStatusPill, + orderItemsByPreferredIds, shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, sortThreadsForSidebar, + useThreadJumpHintVisibility, } from "./Sidebar.logic"; +import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; - -const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; +import { useServerKeybindings } from "../rpc/serverState"; +import type { Project, Thread } from "../types"; const THREAD_PREVIEW_LIMIT = 6; const SIDEBAR_SORT_LABELS: Record = { updated_at: "Last user message", @@ -118,18 +139,80 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = { duration: 180, easing: "ease-out", } as const; -const loadedProjectFaviconSrcs = new Set(); -function formatRelativeTime(iso: string): string { - const diff = Date.now() - new Date(iso).getTime(); - const minutes = Math.floor(diff / 60_000); - if (minutes < 1) return "just now"; - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - return `${Math.floor(hours / 24)}d ago`; +type SidebarThreadSnapshot = Pick< + Thread, + | "activities" + | "archivedAt" + | "branch" + | "createdAt" + | "id" + | "interactionMode" + | "latestTurn" + | "projectId" + | "proposedPlans" + | "session" + | "title" + | "updatedAt" + | "worktreePath" +> & { + lastVisitedAt?: string | undefined; + latestUserMessageAt: string | null; +}; + +type SidebarProjectSnapshot = Project & { + expanded: boolean; +}; + +const sidebarThreadSnapshotCache = new WeakMap< + Thread, + { lastVisitedAt?: string | undefined; snapshot: SidebarThreadSnapshot } +>(); + +function getLatestUserMessageAt(thread: Thread): string | null { + let latestUserMessageAt: string | null = null; + + for (const message of thread.messages) { + if (message.role !== "user") { + continue; + } + if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) { + latestUserMessageAt = message.createdAt; + } + } + + return latestUserMessageAt; } +function toSidebarThreadSnapshot( + thread: Thread, + lastVisitedAt: string | undefined, +): SidebarThreadSnapshot { + const cached = sidebarThreadSnapshotCache.get(thread); + if (cached && cached.lastVisitedAt === lastVisitedAt) { + return cached.snapshot; + } + + const snapshot: SidebarThreadSnapshot = { + id: thread.id, + projectId: thread.projectId, + title: thread.title, + interactionMode: thread.interactionMode, + session: thread.session, + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, + archivedAt: thread.archivedAt, + latestTurn: thread.latestTurn, + lastVisitedAt, + branch: thread.branch, + worktreePath: thread.worktreePath, + activities: thread.activities, + proposedPlans: thread.proposedPlans, + latestUserMessageAt: getLatestUserMessageAt(thread), + }; + sidebarThreadSnapshotCache.set(thread, { lastVisitedAt, snapshot }); + return snapshot; +} interface TerminalStatusIndicator { label: "Terminal process running"; colorClass: string; @@ -145,6 +228,44 @@ interface PrStatusIndicator { type ThreadPr = GitStatusResult["pr"]; +function ThreadStatusLabel({ + status, + compact = false, +}: { + status: NonNullable>; + compact?: boolean; +}) { + if (compact) { + return ( + + + {status.label} + + ); + } + + return ( + + + {status.label} + + ); +} + function terminalStatusFromRunningIds( runningTerminalIds: string[], ): TerminalStatusIndicator | null { @@ -204,54 +325,6 @@ function T3Wordmark() { ); } -/** - * Derives the server's HTTP origin (scheme + host + port) from the same - * sources WsTransport uses, converting ws(s) to http(s). - */ -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(); - -function ProjectFavicon({ cwd }: { cwd: string }) { - const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`; - const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => - loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", - ); - - if (status === "error") { - return ; - } - - return ( - { - loadedProjectFaviconSrcs.add(src); - setStatus("loaded"); - }} - onError={() => setStatus("error")} - /> - ); -} - type SortableProjectHandleProps = Pick< ReturnType, "attributes" | "listeners" | "setActivatorNodeRef" @@ -363,37 +436,37 @@ function SortableProjectItem({ export default function Sidebar() { const projects = useStore((store) => store.projects); - const threads = useStore((store) => store.threads); - const markThreadUnread = useStore((store) => store.markThreadUnread); - const toggleProject = useStore((store) => store.toggleProject); - const reorderProjects = useStore((store) => store.reorderProjects); + const serverThreads = useStore((store) => store.threads); + const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore( + useShallow((store) => ({ + projectExpandedById: store.projectExpandedById, + projectOrder: store.projectOrder, + threadLastVisitedAtById: store.threadLastVisitedAtById, + })), + ); + const markThreadUnread = useUiStateStore((store) => store.markThreadUnread); + const toggleProject = useUiStateStore((store) => store.toggleProject); + const reorderProjects = useUiStateStore((store) => store.reorderProjects); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const getDraftThreadByProjectId = useComposerDraftStore( (store) => store.getDraftThreadByProjectId, ); const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId); - const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState); const clearProjectDraftThreadId = useComposerDraftStore( (store) => store.clearProjectDraftThreadId, ); - const clearProjectDraftThreadById = useComposerDraftStore( - (store) => store.clearProjectDraftThreadById, - ); const navigate = useNavigate(); - const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" }); + const pathname = useLocation({ select: (loc) => loc.pathname }); + const isOnSettings = pathname.startsWith("/settings"); const appSettings = useSettings(); const { updateSettings } = useUpdateSettings(); const { handleNewThread } = useHandleNewThread(); + const { archiveThread, deleteThread } = useThreadActions(); const routeThreadId = useParams({ strict: false, select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), }); - const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({ - ...serverConfigQueryOptions(), - select: (config) => config.keybindings, - }); - const queryClient = useQueryClient(); - const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient })); + const keybindings = useServerKeybindings(); const [addingProject, setAddingProject] = useState(false); const [newCwd, setNewCwd] = useState(""); const [isPickingFolder, setIsPickingFolder] = useState(false); @@ -402,13 +475,17 @@ export default function Sidebar() { const addProjectInputRef = useRef(null); const [renamingThreadId, setRenamingThreadId] = useState(null); const [renamingTitle, setRenamingTitle] = useState(""); + const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState(null); const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< ReadonlySet >(() => new Set()); + const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility(); const renamingCommittedRef = useRef(false); const renamingInputRef = useRef(null); + const confirmArchiveButtonRefs = useRef(new Map()); const dragInProgressRef = useRef(false); const suppressProjectClickAfterDragRef = useRef(false); + const suppressProjectClickForContextMenuRef = useRef(false); const [desktopUpdateState, setDesktopUpdateState] = useState(null); const selectedThreadIds = useThreadSelectionStore((s) => s.selectedThreadIds); const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); @@ -417,12 +494,48 @@ export default function Sidebar() { const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const isLinuxDesktop = isElectron && isLinuxPlatform(navigator.platform); + const platform = navigator.platform; const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop; const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately; + const orderedProjects = useMemo(() => { + return orderItemsByPreferredIds({ + items: projects, + preferredIds: projectOrder, + getId: (project) => project.id, + }); + }, [projectOrder, projects]); + const sidebarProjects = useMemo( + () => + orderedProjects.map((project) => ({ + ...project, + expanded: projectExpandedById[project.id] ?? true, + })), + [orderedProjects, projectExpandedById], + ); + const threads = useMemo( + () => + serverThreads.map((thread) => + toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]), + ), + [serverThreads, threadLastVisitedAtById], + ); const projectCwdById = useMemo( () => new Map(projects.map((project) => [project.id, project.cwd] as const)), [projects], ); + const routeTerminalOpen = routeThreadId + ? selectThreadTerminalState(terminalStateByThreadId, routeThreadId).terminalOpen + : false; + const sidebarShortcutLabelOptions = useMemo( + () => ({ + platform, + context: { + terminalFocus: false, + terminalOpen: routeTerminalOpen, + }, + }), + [platform, routeTerminalOpen], + ); const threadGitTargets = useMemo( () => threads.map((thread) => ({ @@ -493,10 +606,25 @@ export default function Sidebar() { }); }, []); + const attemptArchiveThread = useCallback( + async (threadId: ThreadId) => { + try { + await archiveThread(threadId); + } catch (error) { + toastManager.add({ + type: "error", + title: "Failed to archive thread", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } + }, + [archiveThread], + ); + const focusMostRecentThreadForProject = useCallback( (projectId: ProjectId) => { const latestThread = sortThreadsForSidebar( - threads.filter((thread) => thread.projectId === projectId), + threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null), appSettings.sidebarThreadSortOrder, )[0]; if (!latestThread) return; @@ -627,7 +755,10 @@ export default function Sidebar() { const trimmed = newTitle.trim(); if (trimmed.length === 0) { - toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); + toastManager.add({ + type: "warning", + title: "Thread title cannot be empty", + }); finishRename(); return; } @@ -659,129 +790,9 @@ export default function Sidebar() { [], ); - /** - * Delete a single thread: stop session, close terminal, dispatch delete, - * clean up drafts/state, and optionally remove orphaned worktree. - * Callers handle thread-level confirmation; this still prompts for worktree removal. - */ - const deleteThread = useCallback( - async ( - threadId: ThreadId, - opts: { deletedThreadIds?: ReadonlySet } = {}, - ): Promise => { - const api = readNativeApi(); - if (!api) return; - const thread = threads.find((t) => t.id === threadId); - if (!thread) return; - const threadProject = projects.find((project) => project.id === thread.projectId); - // When bulk-deleting, exclude the other threads being deleted so - // getOrphanedWorktreePathForThread correctly detects that no surviving - // threads will reference this worktree. - const deletedIds = opts.deletedThreadIds; - const survivingThreads = - deletedIds && deletedIds.size > 0 - ? threads.filter((t) => t.id === threadId || !deletedIds.has(t.id)) - : threads; - const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId); - const displayWorktreePath = orphanedWorktreePath - ? formatWorktreePathForDisplay(orphanedWorktreePath) - : null; - const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined; - const shouldDeleteWorktree = - canDeleteWorktree && - (await api.dialogs.confirm( - [ - "This thread is the only one linked to this worktree:", - displayWorktreePath ?? orphanedWorktreePath, - "", - "Delete the worktree too?", - ].join("\n"), - )); - - if (thread.session && thread.session.status !== "closed") { - await api.orchestration - .dispatchCommand({ - type: "thread.session.stop", - commandId: newCommandId(), - threadId, - createdAt: new Date().toISOString(), - }) - .catch(() => undefined); - } - - try { - await api.terminal.close({ threadId, deleteHistory: true }); - } catch { - // Terminal may already be closed - } - - const allDeletedIds = deletedIds ?? new Set(); - const shouldNavigateToFallback = routeThreadId === threadId; - const fallbackThreadId = getFallbackThreadIdAfterDelete({ - threads, - deletedThreadId: threadId, - deletedThreadIds: allDeletedIds, - sortOrder: appSettings.sidebarThreadSortOrder, - }); - await api.orchestration.dispatchCommand({ - type: "thread.delete", - commandId: newCommandId(), - threadId, - }); - clearComposerDraftForThread(threadId); - clearProjectDraftThreadById(thread.projectId, thread.id); - clearTerminalState(threadId); - if (shouldNavigateToFallback) { - if (fallbackThreadId) { - void navigate({ - to: "/$threadId", - params: { threadId: fallbackThreadId }, - replace: true, - }); - } else { - void navigate({ to: "/", replace: true }); - } - } - - if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) { - return; - } - - try { - await removeWorktreeMutation.mutateAsync({ - cwd: threadProject.cwd, - path: orphanedWorktreePath, - force: true, - }); - } catch (error) { - const message = error instanceof Error ? error.message : "Unknown error removing worktree."; - console.error("Failed to remove orphaned worktree after thread deletion", { - threadId, - projectCwd: threadProject.cwd, - worktreePath: orphanedWorktreePath, - error, - }); - toastManager.add({ - type: "error", - title: "Thread deleted, but worktree removal failed", - description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`, - }); - } - }, - [ - appSettings.sidebarThreadSortOrder, - clearComposerDraftForThread, - clearProjectDraftThreadById, - clearTerminalState, - navigate, - projects, - removeWorktreeMutation, - routeThreadId, - threads, - ], - ); - - const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({ + const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ + threadId: ThreadId; + }>({ onCopy: (ctx) => { toastManager.add({ type: "success", @@ -797,7 +808,9 @@ export default function Sidebar() { }); }, }); - const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ + const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ + path: string; + }>({ onCopy: (ctx) => { toastManager.add({ type: "success", @@ -840,7 +853,7 @@ export default function Sidebar() { } if (clicked === "mark-unread") { - markThreadUnread(threadId); + markThreadUnread(threadId, thread.latestTurn?.completedAt); return; } if (clicked === "copy-path") { @@ -902,7 +915,8 @@ export default function Sidebar() { if (clicked === "mark-unread") { for (const id of ids) { - markThreadUnread(id); + const thread = threads.find((candidate) => candidate.id === id); + markThreadUnread(id, thread?.latestTurn?.completedAt); } clearSelection(); return; @@ -933,6 +947,7 @@ export default function Sidebar() { markThreadUnread, removeFromSelection, selectedThreadIds, + threads, ], ); @@ -974,19 +989,40 @@ export default function Sidebar() { ], ); + const navigateToThread = useCallback( + (threadId: ThreadId) => { + if (selectedThreadIds.size > 0) { + clearSelection(); + } + setSelectionAnchor(threadId); + void navigate({ + to: "/$threadId", + params: { threadId }, + }); + }, + [clearSelection, navigate, selectedThreadIds.size, setSelectionAnchor], + ); + const handleProjectContextMenu = useCallback( async (projectId: ProjectId, position: { x: number; y: number }) => { const api = readNativeApi(); if (!api) return; - const clicked = await api.contextMenu.show( - [{ id: "delete", label: "Remove project", destructive: true }], - position, - ); - if (clicked !== "delete") return; - const project = projects.find((entry) => entry.id === projectId); if (!project) return; + const clicked = await api.contextMenu.show( + [ + { id: "copy-path", label: "Copy Project Path" }, + { id: "delete", label: "Remove project", destructive: true }, + ], + position, + ); + if (clicked === "copy-path") { + copyPathToClipboard(project.cwd, { path: project.cwd }); + return; + } + if (clicked !== "delete") return; + const projectThreads = threads.filter((thread) => thread.projectId === projectId); if (projectThreads.length > 0) { toastManager.add({ @@ -1024,6 +1060,7 @@ export default function Sidebar() { [ clearComposerDraftForThread, clearProjectDraftThreadId, + copyPathToClipboard, getDraftThreadByProjectId, projects, threads, @@ -1053,12 +1090,12 @@ export default function Sidebar() { dragInProgressRef.current = false; const { active, over } = event; if (!over || active.id === over.id) return; - const activeProject = projects.find((project) => project.id === active.id); - const overProject = projects.find((project) => project.id === over.id); + const activeProject = sidebarProjects.find((project) => project.id === active.id); + const overProject = sidebarProjects.find((project) => project.id === over.id); if (!activeProject || !overProject) return; reorderProjects(activeProject.id, overProject.id); }, - [appSettings.sidebarProjectSortOrder, projects, reorderProjects], + [appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects], ); const handleProjectDragStart = useCallback( @@ -1094,86 +1131,292 @@ export default function Sidebar() { animatedThreadListsRef.current.add(node); }, []); - const handleProjectTitlePointerDownCapture = useCallback(() => { - suppressProjectClickAfterDragRef.current = false; - }, []); + const handleProjectTitlePointerDownCapture = useCallback( + (event: PointerEvent) => { + suppressProjectClickForContextMenuRef.current = false; + if ( + isContextMenuPointerDown({ + button: event.button, + ctrlKey: event.ctrlKey, + isMac: isMacPlatform(navigator.platform), + }) + ) { + // Keep context-menu gestures from arming the sortable drag sensor. + event.stopPropagation(); + } + suppressProjectClickAfterDragRef.current = false; + }, + [], + ); + + const visibleThreads = useMemo( + () => threads.filter((thread) => thread.archivedAt === null), + [threads], + ); const sortedProjects = useMemo( - () => sortProjectsForSidebar(projects, threads, appSettings.sidebarProjectSortOrder), - [appSettings.sidebarProjectSortOrder, projects, threads], + () => + sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder), + [appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads], ); const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual"; + const renderedProjects = useMemo( + () => + sortedProjects.map((project) => { + const projectThreads = sortThreadsForSidebar( + visibleThreads.filter((thread) => thread.projectId === project.id), + appSettings.sidebarThreadSortOrder, + ); + const threadStatuses = new Map( + projectThreads.map((thread) => [ + thread.id, + resolveThreadStatusPill({ + thread, + hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, + hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, + }), + ]), + ); + const projectStatus = resolveProjectStatusIndicator( + projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null), + ); + const activeThreadId = routeThreadId ?? undefined; + const isThreadListExpanded = expandedThreadListsByProject.has(project.id); + const pinnedCollapsedThread = + !project.expanded && activeThreadId + ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) + : null; + const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null; + const { + hasHiddenThreads, + hiddenThreads, + visibleThreads: visibleProjectThreads, + } = getVisibleThreadsForProject({ + threads: projectThreads, + activeThreadId, + isThreadListExpanded, + previewLimit: THREAD_PREVIEW_LIMIT, + }); + const hiddenThreadStatus = resolveProjectStatusIndicator( + hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null), + ); + const orderedProjectThreadIds = projectThreads.map((thread) => thread.id); + const renderedThreads = pinnedCollapsedThread + ? [pinnedCollapsedThread] + : visibleProjectThreads; + const showEmptyThreadState = project.expanded && projectThreads.length === 0; + + return { + hasHiddenThreads, + hiddenThreadStatus, + orderedProjectThreadIds, + project, + projectStatus, + projectThreads, + threadStatuses, + renderedThreads, + showEmptyThreadState, + shouldShowThreadPanel, + isThreadListExpanded, + }; + }), + [ + appSettings.sidebarThreadSortOrder, + expandedThreadListsByProject, + routeThreadId, + sortedProjects, + visibleThreads, + ], + ); + const visibleSidebarThreadIds = useMemo( + () => getVisibleSidebarThreadIds(renderedProjects), + [renderedProjects], + ); + const threadJumpCommandById = useMemo(() => { + const mapping = new Map>>(); + for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) { + const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); + if (!jumpCommand) { + return mapping; + } + mapping.set(threadId, jumpCommand); + } + + return mapping; + }, [visibleSidebarThreadIds]); + const threadJumpThreadIds = useMemo( + () => [...threadJumpCommandById.keys()], + [threadJumpCommandById], + ); + const threadJumpLabelById = useMemo(() => { + const mapping = new Map(); + for (const [threadId, command] of threadJumpCommandById) { + const label = shortcutLabelForCommand(keybindings, command, sidebarShortcutLabelOptions); + if (label) { + mapping.set(threadId, label); + } + } + return mapping; + }, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]); + const orderedSidebarThreadIds = visibleSidebarThreadIds; + + useEffect(() => { + const getShortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: routeTerminalOpen, + }); + + const onWindowKeyDown = (event: KeyboardEvent) => { + updateThreadJumpHintsVisibility( + shouldShowThreadJumpHints(event, keybindings, { + platform, + context: getShortcutContext(), + }), + ); + + if (event.defaultPrevented || event.repeat) { + return; + } + + const command = resolveShortcutCommand(event, keybindings, { + platform, + context: getShortcutContext(), + }); + const traversalDirection = threadTraversalDirectionFromCommand(command); + if (traversalDirection !== null) { + const targetThreadId = resolveAdjacentThreadId({ + threadIds: orderedSidebarThreadIds, + currentThreadId: routeThreadId, + direction: traversalDirection, + }); + if (!targetThreadId) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + navigateToThread(targetThreadId); + return; + } + + const jumpIndex = threadJumpIndexFromCommand(command ?? ""); + if (jumpIndex === null) { + return; + } + + const targetThreadId = threadJumpThreadIds[jumpIndex]; + if (!targetThreadId) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + navigateToThread(targetThreadId); + }; + + const onWindowKeyUp = (event: KeyboardEvent) => { + updateThreadJumpHintsVisibility( + shouldShowThreadJumpHints(event, keybindings, { + platform, + context: getShortcutContext(), + }), + ); + }; + + const onWindowBlur = () => { + updateThreadJumpHintsVisibility(false); + }; + + window.addEventListener("keydown", onWindowKeyDown); + window.addEventListener("keyup", onWindowKeyUp); + window.addEventListener("blur", onWindowBlur); + + return () => { + window.removeEventListener("keydown", onWindowKeyDown); + window.removeEventListener("keyup", onWindowKeyUp); + window.removeEventListener("blur", onWindowBlur); + }; + }, [ + keybindings, + navigateToThread, + orderedSidebarThreadIds, + platform, + routeTerminalOpen, + routeThreadId, + threadJumpThreadIds, + updateThreadJumpHintsVisibility, + ]); function renderProjectItem( - project: (typeof sortedProjects)[number], + renderedProject: (typeof renderedProjects)[number], dragHandleProps: SortableProjectHandleProps | null, ) { - const projectThreads = sortThreadsForSidebar( - threads.filter((thread) => thread.projectId === project.id), - appSettings.sidebarThreadSortOrder, - ); - const projectStatus = resolveProjectStatusIndicator( - projectThreads.map((thread) => - resolveThreadStatusPill({ - thread, - hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, - hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, - }), - ), - ); - const activeThreadId = routeThreadId ?? undefined; - const isThreadListExpanded = expandedThreadListsByProject.has(project.id); - const pinnedCollapsedThread = - !project.expanded && activeThreadId - ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) - : null; - const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null; - const { hasHiddenThreads, visibleThreads } = getVisibleThreadsForProject({ - threads: projectThreads, - activeThreadId, + const { + hasHiddenThreads, + hiddenThreadStatus, + orderedProjectThreadIds, + project, + projectStatus, + projectThreads, + threadStatuses, + renderedThreads, + showEmptyThreadState, + shouldShowThreadPanel, isThreadListExpanded, - previewLimit: THREAD_PREVIEW_LIMIT, - }); - const orderedProjectThreadIds = projectThreads.map((thread) => thread.id); - const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads; + } = renderedProject; const renderThreadRow = (thread: (typeof projectThreads)[number]) => { const isActive = routeThreadId === thread.id; const isSelected = selectedThreadIds.has(thread.id); const isHighlighted = isActive || isSelected; - const threadStatus = resolveThreadStatusPill({ - thread, - hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, - hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, - }); + const jumpLabel = threadJumpLabelById.get(thread.id) ?? null; + const isThreadRunning = + thread.session?.status === "running" && thread.session.activeTurnId != null; + const threadStatus = threadStatuses.get(thread.id) ?? null; const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null); const terminalStatus = terminalStatusFromRunningIds( selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds, ); + const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning; + const threadMetaClassName = isConfirmingArchive + ? "pointer-events-none opacity-0" + : !isThreadRunning + ? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0" + : "pointer-events-none"; return ( - + { + setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current)); + }} + onBlurCapture={(event) => { + const currentTarget = event.currentTarget; + requestAnimationFrame(() => { + if (currentTarget.contains(document.activeElement)) { + return; + } + setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current)); + }); + }} + > } size="sm" isActive={isActive} - className={resolveThreadRowClassName({ + data-testid={`thread-row-${thread.id}`} + className={`${resolveThreadRowClassName({ isActive, isSelected, - })} + })} relative isolate`} onClick={(event) => { handleThreadClick(event, thread.id, orderedProjectThreadIds); }} onKeyDown={(event) => { if (event.key !== "Enter" && event.key !== " ") return; event.preventDefault(); - if (selectedThreadIds.size > 0) { - clearSelection(); - } - setSelectionAnchor(thread.id); - void navigate({ - to: "/$threadId", - params: { threadId: thread.id }, - }); + navigateToThread(thread.id); }} onContextMenu={(event) => { event.preventDefault(); @@ -1213,18 +1456,7 @@ export default function Sidebar() { {prStatus.tooltip} )} - {threadStatus && ( - - - {threadStatus.label} - - )} + {threadStatus && } {renamingThreadId === thread.id ? ( { @@ -1273,15 +1505,109 @@ export default function Sidebar() { /> )} - - {formatRelativeTime(thread.updatedAt ?? thread.createdAt)} - +
+ {isConfirmingArchive ? ( + + ) : !isThreadRunning ? ( + appSettings.confirmThreadArchive ? ( +
+ +
+ ) : ( + + + +
+ } + /> + Archive + + ) + ) : null} + + {showThreadJumpHints && jumpLabel ? ( + + {jumpLabel} + + ) : ( + + {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} + + )} + +
@@ -1289,7 +1615,7 @@ export default function Sidebar() { }; return ( - + <>
handleProjectTitleKeyDown(event, project.id)} onContextMenu={(event) => { event.preventDefault(); + suppressProjectClickForContextMenuRef.current = true; void handleProjectContextMenu(project.id, { x: event.clientX, y: event.clientY, @@ -1349,7 +1676,7 @@ export default function Sidebar() { /> } showOnHover - className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" + className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" onClick={(event) => { event.preventDefault(); event.stopPropagation(); @@ -1370,51 +1697,68 @@ export default function Sidebar() {
- - - {renderedThreads.map((thread) => renderThreadRow(thread))} + + {shouldShowThreadPanel && showEmptyThreadState ? ( + +
+ No threads yet +
+
+ ) : null} + {shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))} - {project.expanded && hasHiddenThreads && !isThreadListExpanded && ( - - } - data-thread-selection-safe - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - expandThreadListForProject(project.id); - }} - > + {project.expanded && hasHiddenThreads && !isThreadListExpanded && ( + + } + data-thread-selection-safe + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + expandThreadListForProject(project.id); + }} + > + + {hiddenThreadStatus && } Show more - - - )} - {project.expanded && hasHiddenThreads && isThreadListExpanded && ( - - } - data-thread-selection-safe - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - collapseThreadListForProject(project.id); - }} - > - Show less - - - )} -
-
-
+ + + + )} + {project.expanded && hasHiddenThreads && isThreadListExpanded && ( + + } + data-thread-selection-safe + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + collapseThreadListForProject(project.id); + }} + > + Show less + + + )} + + ); } const handleProjectTitleClick = useCallback( (event: React.MouseEvent, projectId: ProjectId) => { + if (suppressProjectClickForContextMenuRef.current) { + suppressProjectClickForContextMenuRef.current = false; + event.preventDefault(); + event.stopPropagation(); + return; + } if (dragInProgressRef.current) { event.preventDefault(); event.stopPropagation(); @@ -1494,12 +1838,6 @@ export default function Sidebar() { }; }, []); - const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState); - - const desktopUpdateTooltip = desktopUpdateState - ? getDesktopUpdateButtonTooltip(desktopUpdateState) - : "Update available"; - const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState); const desktopUpdateButtonAction = desktopUpdateState ? resolveDesktopUpdateButtonAction(desktopUpdateState) @@ -1510,20 +1848,9 @@ export default function Sidebar() { desktopUpdateState && showArm64IntelBuildWarning ? getArm64IntelBuildWarningDescription(desktopUpdateState) : null; - const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled - ? "cursor-not-allowed opacity-60" - : "hover:bg-accent hover:text-foreground"; - const desktopUpdateButtonClasses = - desktopUpdateState?.status === "downloaded" - ? "text-emerald-500" - : desktopUpdateState?.status === "downloading" - ? "text-sky-400" - : shouldHighlightDesktopUpdateError(desktopUpdateState) - ? "text-rose-500 animate-pulse" - : "text-amber-500 animate-pulse"; const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal") ?? - shortcutLabelForCommand(keybindings, "chat.new"); + shortcutLabelForCommand(keybindings, "chat.newLocal", sidebarShortcutLabelOptions) ?? + shortcutLabelForCommand(keybindings, "chat.new", sidebarShortcutLabelOptions); const handleDesktopUpdateButtonClick = useCallback(() => { const bridge = window.desktopBridge; @@ -1561,6 +1888,10 @@ export default function Sidebar() { } if (desktopUpdateButtonAction === "install") { + const confirmed = window.confirm( + getDesktopUpdateInstallConfirmationMessage(desktopUpdateState), + ); + if (!confirmed) return; void bridge .installUpdate() .then((result) => { @@ -1628,232 +1959,199 @@ export default function Sidebar() { return ( <> {isElectron ? ( - <> - - {wordmark} - {showDesktopUpdateButton && ( - - - - - } - /> - {desktopUpdateTooltip} - - )} - - + + {wordmark} + ) : ( {wordmark} )} - - {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( - - - - Intel build on Apple Silicon - {arm64IntelBuildWarningDescription} - {desktopUpdateButtonAction !== "none" ? ( - - - - ) : null} - - - ) : null} - -
- - Projects - -
- { - updateSettings({ sidebarProjectSortOrder: sortOrder }); - }} - onThreadSortOrderChange={(sortOrder) => { - updateSettings({ sidebarThreadSortOrder: sortOrder }); - }} - /> - - + ) : ( + <> + + {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( + + + + Intel build on Apple Silicon + {arm64IntelBuildWarningDescription} + {desktopUpdateButtonAction !== "none" ? ( + + + + ) : null} + + + ) : null} + +
+ + Projects + +
+ { + updateSettings({ sidebarProjectSortOrder: sortOrder }); + }} + onThreadSortOrderChange={(sortOrder) => { + updateSettings({ sidebarThreadSortOrder: sortOrder }); + }} + /> + + + } + > + + + + {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"} + + +
+
+ {shouldShowProjectPathEntry && ( +
+ {isElectron && ( + )} +
+ { + setNewCwd(event.target.value); + setAddProjectError(null); + }} + onKeyDown={(event) => { + if (event.key === "Enter") handleAddProject(); + if (event.key === "Escape") { + setAddingProject(false); + setAddProjectError(null); + } + }} + autoFocus /> - } - > - - - - {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"} - - -
-
- - {shouldShowProjectPathEntry && ( -
- {isElectron && ( - + +
+ {addProjectError && ( +

+ {addProjectError} +

+ )} +
)} -
- { - setNewCwd(event.target.value); - setAddProjectError(null); - }} - onKeyDown={(event) => { - if (event.key === "Enter") handleAddProject(); - if (event.key === "Escape") { - setAddingProject(false); - setAddProjectError(null); - } - }} - autoFocus - /> - -
- {addProjectError && ( -

- {addProjectError} -

- )} -
- -
-
- )} - {isManualProjectSorting ? ( - - - project.id)} - strategy={verticalListSortingStrategy} + {isManualProjectSorting ? ( + - {sortedProjects.map((project) => ( - - {(dragHandleProps) => renderProjectItem(project, dragHandleProps)} - + + renderedProject.project.id)} + strategy={verticalListSortingStrategy} + > + {renderedProjects.map((renderedProject) => ( + + {(dragHandleProps) => renderProjectItem(renderedProject, dragHandleProps)} + + ))} + + + + ) : ( + + {renderedProjects.map((renderedProject) => ( + + {renderProjectItem(renderedProject, null)} + ))} - - - - ) : ( - - {sortedProjects.map((project) => ( - - {renderProjectItem(project, null)} - - ))} + + )} + + {projects.length === 0 && !shouldShowProjectPathEntry && ( +
+ No projects yet +
+ )} +
+
+ + + + + + + void navigate({ to: "/settings" })} + > + + Settings + + - )} - - {projects.length === 0 && !shouldShowProjectPathEntry && ( -
- No projects yet -
- )} - - - - - - - - {isOnSettings ? ( - window.history.back()} - > - - Back - - ) : ( - void navigate({ to: "/settings" })} - > - - Settings - - )} - - - +
+ + )} ); } diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 0174a77088..a13ddad30d 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -50,6 +50,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
+ ) : ( + + ) + ) : 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/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index f3174030ef..9e0b895912 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -264,9 +264,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({ rowVirtualizer.measure(); }, [rowVirtualizer, timelineWidthPx]); useEffect(() => { - rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => { + rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => { const viewportHeight = instance.scrollRect?.height ?? 0; const scrollOffset = instance.scrollOffset ?? 0; + const itemIntersectsViewport = + item.end > scrollOffset && item.start < scrollOffset + viewportHeight; + if (itemIntersectsViewport) { + return false; + } const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight); return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX; }; @@ -483,6 +488,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ type="button" size="xs" variant="outline" + data-scroll-anchor-ignore onClick={() => onToggleAllDirectories(turnSummary.turnId)} > {allDirectoriesExpanded ? "Collapse all" : "Expand all"} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 9f62f7121e..6a956f6f42 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -22,6 +22,16 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray openInEditor(preferredEditor)} > {primaryOption?.Icon &&
}> (label: string, initialValue: A) { + return Atom.make(initialValue).pipe(Atom.keepAlive, Atom.withLabel(label)); +} + +function toServerConfigUpdatedPayload(config: ServerConfig): ServerConfigUpdatedPayload { + return { + issues: config.issues, + providers: config.providers, + settings: config.settings, + }; +} + +const EMPTY_AVAILABLE_EDITORS: ReadonlyArray = []; +const EMPTY_KEYBINDINGS: ServerConfig["keybindings"] = []; +const EMPTY_SERVER_PROVIDERS: ReadonlyArray = []; + +const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray => + config?.availableEditors ?? EMPTY_AVAILABLE_EDITORS; +const selectKeybindings = (config: ServerConfig | null) => config?.keybindings ?? EMPTY_KEYBINDINGS; +const selectKeybindingsConfigPath = (config: ServerConfig | null) => + config?.keybindingsConfigPath ?? null; +const selectProviders = (config: ServerConfig | null) => + config?.providers ?? EMPTY_SERVER_PROVIDERS; +const selectSettings = (config: ServerConfig | null): ServerSettings => + config?.settings ?? DEFAULT_SERVER_SETTINGS; + +export const welcomeAtom = makeStateAtom( + "server-welcome", + null, +); +export const serverConfigAtom = makeStateAtom("server-config", null); +export const serverConfigUpdatedAtom = makeStateAtom( + "server-config-updated", + null, +); +export const providersUpdatedAtom = makeStateAtom( + "server-providers-updated", + null, +); + +export function getServerConfig(): ServerConfig | null { + return appAtomRegistry.get(serverConfigAtom); +} + +export function setServerConfigSnapshot(config: ServerConfig): void { + resolveServerConfig(config); + emitProvidersUpdated({ providers: config.providers }); + emitServerConfigUpdated(toServerConfigUpdatedPayload(config), "snapshot"); +} + +export function applyServerConfigEvent(event: ServerConfigStreamEvent): void { + switch (event.type) { + case "snapshot": { + setServerConfigSnapshot(event.config); + return; + } + case "keybindingsUpdated": { + const latestServerConfig = getServerConfig(); + if (!latestServerConfig) { + return; + } + const nextConfig = { + ...latestServerConfig, + issues: event.payload.issues, + } satisfies ServerConfig; + resolveServerConfig(nextConfig); + emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), event.type); + return; + } + case "providerStatuses": { + applyProvidersUpdated(event.payload); + return; + } + case "settingsUpdated": { + applySettingsUpdated(event.payload.settings); + return; + } + } +} + +export function applyProvidersUpdated(payload: ServerProviderUpdatedPayload): void { + const latestServerConfig = getServerConfig(); + emitProvidersUpdated(payload); + + if (!latestServerConfig) { + return; + } + + const nextConfig = { + ...latestServerConfig, + providers: payload.providers, + } satisfies ServerConfig; + resolveServerConfig(nextConfig); + emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "providerStatuses"); +} + +export function applySettingsUpdated(settings: ServerSettings): void { + const latestServerConfig = getServerConfig(); + if (!latestServerConfig) { + return; + } + + const nextConfig = { + ...latestServerConfig, + settings, + } satisfies ServerConfig; + resolveServerConfig(nextConfig); + emitServerConfigUpdated(toServerConfigUpdatedPayload(nextConfig), "settingsUpdated"); +} + +export function emitWelcome(payload: ServerLifecycleWelcomePayload): void { + appAtomRegistry.set(welcomeAtom, payload); +} + +export function onWelcome(listener: (payload: ServerLifecycleWelcomePayload) => void): () => void { + return subscribeLatest(welcomeAtom, listener); +} + +export function onServerConfigUpdated( + listener: (payload: ServerConfigUpdatedPayload, source: ServerConfigUpdateSource) => void, +): () => void { + return subscribeLatest(serverConfigUpdatedAtom, (notification) => { + listener(notification.payload, notification.source); + }); +} + +export function onProvidersUpdated( + listener: (payload: ServerProviderUpdatedPayload) => void, +): () => void { + return subscribeLatest(providersUpdatedAtom, listener); +} + +export function startServerStateSync(client: ServerStateClient): () => void { + let disposed = false; + const cleanups = [ + client.subscribeLifecycle((event) => { + if (event.type === "welcome") { + emitWelcome(event.payload); + } + }), + client.subscribeConfig((event) => { + applyServerConfigEvent(event); + }), + ]; + + if (getServerConfig() === null) { + void client + .getConfig() + .then((config) => { + if (disposed || getServerConfig() !== null) { + return; + } + setServerConfigSnapshot(config); + }) + .catch(() => undefined); + } + + return () => { + disposed = true; + for (const cleanup of cleanups) { + cleanup(); + } + }; +} + +export function resetServerStateForTests() { + resetAppAtomRegistryForTests(); +} + +function resolveServerConfig(config: ServerConfig): void { + appAtomRegistry.set(serverConfigAtom, config); +} + +function emitProvidersUpdated(payload: ServerProviderUpdatedPayload): void { + appAtomRegistry.set(providersUpdatedAtom, payload); +} + +function emitServerConfigUpdated( + payload: ServerConfigUpdatedPayload, + source: ServerConfigUpdateSource, +): void { + appAtomRegistry.set(serverConfigUpdatedAtom, { payload, source }); +} + +function subscribeLatest( + atom: Atom.Atom, + listener: (value: NonNullable) => void, +): () => void { + return appAtomRegistry.subscribe( + atom, + (value) => { + if (value === null) { + return; + } + listener(value as NonNullable); + }, + { immediate: true }, + ); +} + +function useLatestAtomSubscription( + atom: Atom.Atom, + listener: (value: NonNullable) => void, +) { + useAtomSubscribe( + atom, + (value) => { + if (value === null) { + return; + } + listener(value as NonNullable); + }, + { immediate: true }, + ); +} + +export function useServerConfig(): ServerConfig | null { + return useAtomValue(serverConfigAtom); +} + +export function useServerSettings(): ServerSettings { + return useAtomValue(serverConfigAtom, selectSettings); +} + +export function useServerProviders(): ReadonlyArray { + return useAtomValue(serverConfigAtom, selectProviders); +} + +export function useServerKeybindings(): ServerConfig["keybindings"] { + return useAtomValue(serverConfigAtom, selectKeybindings); +} + +export function useServerAvailableEditors(): ReadonlyArray { + return useAtomValue(serverConfigAtom, selectAvailableEditors); +} + +export function useServerKeybindingsConfigPath(): string | null { + return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath); +} + +export function useServerWelcomeSubscription( + listener: (payload: ServerLifecycleWelcomePayload) => void, +): void { + useLatestAtomSubscription(welcomeAtom, listener); +} + +export function useServerConfigUpdatedSubscription( + listener: (notification: ServerConfigUpdatedNotification) => void, +): void { + useLatestAtomSubscription(serverConfigUpdatedAtom, listener); +} diff --git a/apps/web/src/rpc/serverStateBootstrap.tsx b/apps/web/src/rpc/serverStateBootstrap.tsx new file mode 100644 index 0000000000..c5c5c12eae --- /dev/null +++ b/apps/web/src/rpc/serverStateBootstrap.tsx @@ -0,0 +1,10 @@ +import { useEffect } from "react"; + +import { getWsRpcClient } from "../wsRpcClient"; +import { startServerStateSync } from "./serverState"; + +export function ServerStateBootstrap() { + useEffect(() => startServerStateSync(getWsRpcClient().server), []); + + return null; +} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 9ab153a8df..5d807c29f1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -9,6 +9,7 @@ import { import { describe, expect, it } from "vitest"; import { + deriveCompletionDividerBeforeEntryId, deriveActiveWorkStartedAt, deriveActivePlanState, PROVIDER_OPTIONS, @@ -956,6 +957,37 @@ describe("deriveTimelineEntries", () => { }, }); }); + + it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => { + const entries = deriveTimelineEntries( + [ + { + id: MessageId.makeUnsafe("assistant-earlier"), + role: "assistant", + text: "progress update", + createdAt: "2026-02-23T00:00:01.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("assistant-final"), + role: "assistant", + text: "final answer", + createdAt: "2026-02-23T00:00:01.000Z", + streaming: false, + }, + ], + [], + [], + ); + + expect( + deriveCompletionDividerBeforeEntryId(entries, { + assistantMessageId: MessageId.makeUnsafe("assistant-final"), + startedAt: "2026-02-23T00:00:00.000Z", + completedAt: "2026-02-23T00:00:02.000Z", + }), + ).toBe("assistant-final"); + }); }); describe("deriveWorkLogEntries context window handling", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 57ad56124e..f251a03b1a 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -830,6 +830,53 @@ export function deriveTimelineEntries( ); } +export function deriveCompletionDividerBeforeEntryId( + timelineEntries: ReadonlyArray, + latestTurn: Pick< + OrchestrationLatestTurn, + "assistantMessageId" | "startedAt" | "completedAt" + > | null, +): string | null { + if (!latestTurn?.startedAt || !latestTurn.completedAt) { + return null; + } + + if (latestTurn.assistantMessageId) { + const exactMatch = timelineEntries.find( + (timelineEntry) => + timelineEntry.kind === "message" && + timelineEntry.message.role === "assistant" && + timelineEntry.message.id === latestTurn.assistantMessageId, + ); + if (exactMatch) { + return exactMatch.id; + } + } + + const turnStartedAt = Date.parse(latestTurn.startedAt); + const turnCompletedAt = Date.parse(latestTurn.completedAt); + if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) { + return null; + } + + let inRangeMatch: string | null = null; + let fallbackMatch: string | null = null; + for (const timelineEntry of timelineEntries) { + if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") { + continue; + } + const messageAt = Date.parse(timelineEntry.message.createdAt); + if (Number.isNaN(messageAt) || messageAt < turnStartedAt) { + continue; + } + fallbackMatch = timelineEntry.id; + if (messageAt <= turnCompletedAt) { + inRangeMatch = timelineEntry.id; + } + } + return inRangeMatch ?? fallbackMatch; +} + export function inferCheckpointTurnCountByTurnId( summaries: TurnDiffSummary[], ): Record { diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 4da4f23c8c..92fa49eeee 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1,13 +1,22 @@ import { + CheckpointRef, DEFAULT_MODEL_BY_PROVIDER, + EventId, + MessageId, ProjectId, ThreadId, TurnId, + type OrchestrationEvent, type OrchestrationReadModel, } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; -import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store"; +import { + applyOrchestrationEvent, + applyOrchestrationEvents, + syncServerReadModel, + type AppState, +} from "./store"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types"; function makeThread(overrides: Partial = {}): Thread { @@ -29,6 +38,7 @@ function makeThread(overrides: Partial = {}): Thread { proposedPlans: [], error: null, createdAt: "2026-02-13T00:00:00.000Z", + archivedAt: null, latestTurn: null, branch: null, worktreePath: null, @@ -47,15 +57,41 @@ function makeState(thread: Thread): AppState { provider: "codex", model: "gpt-5-codex", }, - expanded: true, scripts: [], }, ], threads: [thread], - threadsHydrated: true, + bootstrapComplete: true, }; } +function makeEvent( + type: T, + payload: Extract["payload"], + overrides: Partial> = {}, +): Extract { + const sequence = overrides.sequence ?? 1; + return { + sequence, + eventId: EventId.makeUnsafe(`event-${sequence}`), + aggregateKind: "thread", + aggregateId: + "threadId" in payload + ? payload.threadId + : "projectId" in payload + ? payload.projectId + : ProjectId.makeUnsafe("project-1"), + occurredAt: "2026-02-27T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type, + payload, + ...overrides, + } as Extract; +} + function makeReadModelThread(overrides: Partial) { return { id: ThreadId.makeUnsafe("thread-1"), @@ -72,6 +108,7 @@ function makeReadModelThread(overrides: Partial { - it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => { - const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; - const initialState = makeState( - makeThread({ - latestTurn: { - turnId: TurnId.makeUnsafe("turn-1"), - state: "completed", - requestedAt: "2026-02-25T12:28:00.000Z", - startedAt: "2026-02-25T12:28:30.000Z", - completedAt: latestTurnCompletedAt, - assistantMessageId: null, - }, - lastVisitedAt: "2026-02-25T12:35:00.000Z", - }), - ); - - const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1")); - - const updatedThread = next.threads[0]; - expect(updatedThread).toBeDefined(); - expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z"); - expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan( - Date.parse(latestTurnCompletedAt), - ); - }); - - it("markThreadUnread does not change a thread without a completed turn", () => { - const initialState = makeState( - makeThread({ - latestTurn: null, - lastVisitedAt: "2026-02-25T12:35:00.000Z", - }), - ); - - const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1")); - - expect(next).toEqual(initialState); - }); - - it("reorderProjects moves a project to a target index", () => { - const project1 = ProjectId.makeUnsafe("project-1"); - const project2 = ProjectId.makeUnsafe("project-2"); - const project3 = ProjectId.makeUnsafe("project-3"); - const state: AppState = { - projects: [ - { - id: project1, - name: "Project 1", - cwd: "/tmp/project-1", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - { - id: project2, - name: "Project 2", - cwd: "/tmp/project-2", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - { - id: project3, - name: "Project 3", - cwd: "/tmp/project-3", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - ], - threads: [], - threadsHydrated: true, +describe("store read model sync", () => { + it("marks bootstrap complete after snapshot sync", () => { + const initialState: AppState = { + ...makeState(makeThread()), + bootstrapComplete: false, }; - const next = reorderProjects(state, project1, project3); + const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({}))); - expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]); + expect(next.bootstrapComplete).toBe(true); }); -}); -describe("store read model sync", () => { it("preserves claude model slugs without an active session", () => { const initialState = makeState(makeThread()); const readModel = makeReadModel( @@ -270,7 +228,22 @@ describe("store read model sync", () => { expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z"); }); - it("preserves the current project order when syncing incoming read model updates", () => { + it("maps archivedAt from the read model", () => { + const initialState = makeState(makeThread()); + const archivedAt = "2026-02-28T00:00:00.000Z"; + const next = syncServerReadModel( + initialState, + makeReadModel( + makeReadModelThread({ + archivedAt, + }), + ), + ); + + expect(next.threads[0]?.archivedAt).toBe(archivedAt); + }); + + it("replaces projects using snapshot order during recovery", () => { const project1 = ProjectId.makeUnsafe("project-1"); const project2 = ProjectId.makeUnsafe("project-2"); const project3 = ProjectId.makeUnsafe("project-3"); @@ -284,7 +257,6 @@ describe("store read model sync", () => { provider: "codex", model: DEFAULT_MODEL_BY_PROVIDER.codex, }, - expanded: true, scripts: [], }, { @@ -295,12 +267,11 @@ describe("store read model sync", () => { provider: "codex", model: DEFAULT_MODEL_BY_PROVIDER.codex, }, - expanded: true, scripts: [], }, ], threads: [], - threadsHydrated: true, + bootstrapComplete: true, }; const readModel: OrchestrationReadModel = { snapshotSequence: 2, @@ -327,6 +298,452 @@ describe("store read model sync", () => { const next = syncServerReadModel(initialState, readModel); - expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]); + expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]); + }); +}); + +describe("incremental orchestration updates", () => { + it("does not mark bootstrap complete for incremental events", () => { + const state: AppState = { + ...makeState(makeThread()), + bootstrapComplete: false, + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.meta-updated", { + threadId: ThreadId.makeUnsafe("thread-1"), + title: "Updated title", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.bootstrapComplete).toBe(false); + }); + + it("preserves state identity for no-op project and thread deletes", () => { + const thread = makeThread(); + const state = makeState(thread); + + const nextAfterProjectDelete = applyOrchestrationEvent( + state, + makeEvent("project.deleted", { + projectId: ProjectId.makeUnsafe("project-missing"), + deletedAt: "2026-02-27T00:00:01.000Z", + }), + ); + const nextAfterThreadDelete = applyOrchestrationEvent( + state, + makeEvent("thread.deleted", { + threadId: ThreadId.makeUnsafe("thread-missing"), + deletedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(nextAfterProjectDelete).toBe(state); + expect(nextAfterThreadDelete).toBe(state); + }); + + it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => { + const originalProjectId = ProjectId.makeUnsafe("project-1"); + const recreatedProjectId = ProjectId.makeUnsafe("project-2"); + const state: AppState = { + projects: [ + { + id: originalProjectId, + name: "Project", + cwd: "/tmp/project", + defaultModelSelection: { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }, + scripts: [], + }, + ], + threads: [], + bootstrapComplete: true, + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("project.created", { + projectId: recreatedProjectId, + title: "Project Recreated", + workspaceRoot: "/tmp/project", + defaultModelSelection: { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }, + scripts: [], + createdAt: "2026-02-27T00:00:01.000Z", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.projects).toHaveLength(1); + expect(next.projects[0]?.id).toBe(recreatedProjectId); + expect(next.projects[0]?.cwd).toBe("/tmp/project"); + expect(next.projects[0]?.name).toBe("Project Recreated"); + }); + + it("updates only the affected thread for message events", () => { + const thread1 = makeThread({ + id: ThreadId.makeUnsafe("thread-1"), + messages: [ + { + id: MessageId.makeUnsafe("message-1"), + role: "assistant", + text: "hello", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:00.000Z", + streaming: false, + }, + ], + }); + const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") }); + const state: AppState = { + ...makeState(thread1), + threads: [thread1, thread2], + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.message-sent", { + threadId: thread1.id, + messageId: MessageId.makeUnsafe("message-1"), + role: "assistant", + text: " world", + turnId: TurnId.makeUnsafe("turn-1"), + streaming: true, + createdAt: "2026-02-27T00:00:01.000Z", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.threads[0]?.messages[0]?.text).toBe("hello world"); + expect(next.threads[0]?.latestTurn?.state).toBe("running"); + expect(next.threads[1]).toBe(thread2); + }); + + it("applies replay batches in sequence and updates session state", () => { + const thread = makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-1"), + state: "running", + requestedAt: "2026-02-27T00:00:00.000Z", + startedAt: "2026-02-27T00:00:00.000Z", + completedAt: null, + assistantMessageId: null, + }, + }); + const state = makeState(thread); + + const next = applyOrchestrationEvents(state, [ + makeEvent( + "thread.session-set", + { + threadId: thread.id, + session: { + threadId: thread.id, + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.makeUnsafe("turn-1"), + lastError: null, + updatedAt: "2026-02-27T00:00:02.000Z", + }, + }, + { sequence: 2 }, + ), + makeEvent( + "thread.message-sent", + { + threadId: thread.id, + messageId: MessageId.makeUnsafe("assistant-1"), + role: "assistant", + text: "done", + turnId: TurnId.makeUnsafe("turn-1"), + streaming: false, + createdAt: "2026-02-27T00:00:03.000Z", + updatedAt: "2026-02-27T00:00:03.000Z", + }, + { sequence: 3 }, + ), + ]); + + expect(next.threads[0]?.session?.status).toBe("running"); + expect(next.threads[0]?.latestTurn?.state).toBe("completed"); + expect(next.threads[0]?.messages).toHaveLength(1); + }); + + it("does not regress latestTurn when an older turn diff completes late", () => { + const state = makeState( + makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-2"), + state: "running", + requestedAt: "2026-02-27T00:00:02.000Z", + startedAt: "2026-02-27T00:00:03.000Z", + completedAt: null, + assistantMessageId: null, + }, + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.turn-diff-completed", { + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: TurnId.makeUnsafe("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-1"), + completedAt: "2026-02-27T00:00:04.000Z", + }), + ); + + expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1); + expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn); + }); + + it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => { + const turnId = TurnId.makeUnsafe("turn-1"); + const state = makeState( + makeThread({ + latestTurn: { + turnId, + state: "completed", + requestedAt: "2026-02-27T00:00:00.000Z", + startedAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:02.000Z", + assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"), + }, + turnDiffSummaries: [ + { + turnId, + completedAt: "2026-02-27T00:00:02.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"), + assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"), + files: [{ path: "src/app.ts", additions: 1, deletions: 0 }], + }, + ], + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.message-sent", { + threadId: ThreadId.makeUnsafe("thread-1"), + messageId: MessageId.makeUnsafe("assistant-real"), + role: "assistant", + text: "final answer", + turnId, + streaming: false, + createdAt: "2026-02-27T00:00:03.000Z", + updatedAt: "2026-02-27T00:00:03.000Z", + }), + ); + + expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe( + MessageId.makeUnsafe("assistant-real"), + ); + expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe( + MessageId.makeUnsafe("assistant-real"), + ); + }); + + it("reverts messages, plans, activities, and checkpoints by retained turns", () => { + const state = makeState( + makeThread({ + messages: [ + { + id: MessageId.makeUnsafe("user-1"), + role: "user", + text: "first", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:00.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("assistant-1"), + role: "assistant", + text: "first reply", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:01.000Z", + completedAt: "2026-02-27T00:00:01.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("user-2"), + role: "user", + text: "second", + turnId: TurnId.makeUnsafe("turn-2"), + createdAt: "2026-02-27T00:00:02.000Z", + completedAt: "2026-02-27T00:00:02.000Z", + streaming: false, + }, + ], + proposedPlans: [ + { + id: "plan-1", + turnId: TurnId.makeUnsafe("turn-1"), + planMarkdown: "plan 1", + implementedAt: null, + implementationThreadId: null, + createdAt: "2026-02-27T00:00:00.000Z", + updatedAt: "2026-02-27T00:00:00.000Z", + }, + { + id: "plan-2", + turnId: TurnId.makeUnsafe("turn-2"), + planMarkdown: "plan 2", + implementedAt: null, + implementationThreadId: null, + createdAt: "2026-02-27T00:00:02.000Z", + updatedAt: "2026-02-27T00:00:02.000Z", + }, + ], + activities: [ + { + id: EventId.makeUnsafe("activity-1"), + tone: "info", + kind: "turn.plan.updated", + summary: "one", + payload: { + plan: [{ step: "one", status: "completed" }], + explanation: null, + }, + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + }, + { + id: EventId.makeUnsafe("activity-2"), + tone: "info", + kind: "turn.plan.updated", + summary: "two", + payload: { + plan: [{ step: "two", status: "completed" }], + explanation: null, + }, + turnId: TurnId.makeUnsafe("turn-2"), + createdAt: "2026-02-27T00:00:02.000Z", + }, + ], + turnDiffSummaries: [ + { + turnId: TurnId.makeUnsafe("turn-1"), + completedAt: "2026-02-27T00:00:01.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("ref-1"), + files: [], + }, + { + turnId: TurnId.makeUnsafe("turn-2"), + completedAt: "2026-02-27T00:00:03.000Z", + status: "ready", + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("ref-2"), + files: [], + }, + ], + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.reverted", { + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 1, + }), + ); + + expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([ + "user-1", + "assistant-1", + ]); + expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]); + expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([ + EventId.makeUnsafe("activity-1"), + ]); + expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([ + TurnId.makeUnsafe("turn-1"), + ]); + }); + + it("clears pending source proposed plans after revert before a new session-set event", () => { + const thread = makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-2"), + state: "completed", + requestedAt: "2026-02-27T00:00:02.000Z", + startedAt: "2026-02-27T00:00:02.000Z", + completedAt: "2026-02-27T00:00:03.000Z", + assistantMessageId: MessageId.makeUnsafe("assistant-2"), + sourceProposedPlan: { + threadId: ThreadId.makeUnsafe("thread-source"), + planId: "plan-2" as never, + }, + }, + pendingSourceProposedPlan: { + threadId: ThreadId.makeUnsafe("thread-source"), + planId: "plan-2" as never, + }, + turnDiffSummaries: [ + { + turnId: TurnId.makeUnsafe("turn-1"), + completedAt: "2026-02-27T00:00:01.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("ref-1"), + files: [], + }, + { + turnId: TurnId.makeUnsafe("turn-2"), + completedAt: "2026-02-27T00:00:03.000Z", + status: "ready", + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("ref-2"), + files: [], + }, + ], + }); + const reverted = applyOrchestrationEvent( + makeState(thread), + makeEvent("thread.reverted", { + threadId: thread.id, + turnCount: 1, + }), + ); + + expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined(); + + const next = applyOrchestrationEvent( + reverted, + makeEvent("thread.session-set", { + threadId: thread.id, + session: { + threadId: thread.id, + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.makeUnsafe("turn-3"), + lastError: null, + updatedAt: "2026-02-27T00:00:04.000Z", + }, + }), + ); + + expect(next.threads[0]?.latestTurn).toMatchObject({ + turnId: TurnId.makeUnsafe("turn-3"), + state: "running", + }); + expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined(); }); }); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 4590b2886d..eff6a6fd07 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,98 +1,36 @@ -import { Fragment, type ReactNode, createElement, useEffect } from "react"; import { + type OrchestrationEvent, + type OrchestrationMessage, + type OrchestrationProposedPlan, type ProviderKind, ThreadId, type OrchestrationReadModel, + type OrchestrationSession, + type OrchestrationCheckpointSummary, + type OrchestrationThread, type OrchestrationSessionStatus, } from "@t3tools/contracts"; import { resolveModelSlugForProvider } from "@t3tools/shared/model"; import { create } from "zustand"; import { type ChatMessage, type Project, type Thread } from "./types"; -import { Debouncer } from "@tanstack/react-pacer"; // ── State ──────────────────────────────────────────────────────────── export interface AppState { projects: Project[]; threads: Thread[]; - threadsHydrated: boolean; + bootstrapComplete: boolean; } -const PERSISTED_STATE_KEY = "t3code:renderer-state:v8"; -const LEGACY_PERSISTED_STATE_KEYS = [ - "t3code:renderer-state:v7", - "t3code:renderer-state:v6", - "t3code:renderer-state:v5", - "t3code:renderer-state:v4", - "t3code:renderer-state:v3", - "codething:renderer-state:v4", - "codething:renderer-state:v3", - "codething:renderer-state:v2", - "codething:renderer-state:v1", -] as const; - const initialState: AppState = { projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }; -const persistedExpandedProjectCwds = new Set(); -const persistedProjectOrderCwds: string[] = []; - -// ── Persist helpers ────────────────────────────────────────────────── - -function readPersistedState(): AppState { - if (typeof window === "undefined") return initialState; - try { - const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); - if (!raw) return initialState; - const parsed = JSON.parse(raw) as { - expandedProjectCwds?: string[]; - projectOrderCwds?: string[]; - }; - persistedExpandedProjectCwds.clear(); - persistedProjectOrderCwds.length = 0; - for (const cwd of parsed.expandedProjectCwds ?? []) { - if (typeof cwd === "string" && cwd.length > 0) { - persistedExpandedProjectCwds.add(cwd); - } - } - for (const cwd of parsed.projectOrderCwds ?? []) { - if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) { - persistedProjectOrderCwds.push(cwd); - } - } - return { ...initialState }; - } catch { - return initialState; - } -} - -let legacyKeysCleanedUp = false; - -function persistState(state: AppState): void { - if (typeof window === "undefined") return; - try { - window.localStorage.setItem( - PERSISTED_STATE_KEY, - JSON.stringify({ - expandedProjectCwds: state.projects - .filter((project) => project.expanded) - .map((project) => project.cwd), - projectOrderCwds: state.projects.map((project) => project.cwd), - }), - ); - if (!legacyKeysCleanedUp) { - legacyKeysCleanedUp = true; - for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { - window.localStorage.removeItem(legacyKey); - } - } - } catch { - // Ignore quota/storage errors to avoid breaking chat UX. - } -} -const debouncedPersistState = new Debouncer(persistState, { wait: 500 }); +const MAX_THREAD_MESSAGES = 2_000; +const MAX_THREAD_CHECKPOINTS = 500; +const MAX_THREAD_PROPOSED_PLANS = 200; +const MAX_THREAD_ACTIVITIES = 500; // ── Pure helpers ────────────────────────────────────────────────────── @@ -111,66 +49,295 @@ function updateThread( return changed ? next : threads; } -function mapProjectsFromReadModel( - incoming: OrchestrationReadModel["projects"], - previous: Project[], +function updateProject( + projects: Project[], + projectId: Project["id"], + updater: (project: Project) => Project, ): Project[] { - const previousById = new Map(previous.map((project) => [project.id, project] as const)); - const previousByCwd = new Map(previous.map((project) => [project.cwd, project] as const)); - const previousOrderById = new Map(previous.map((project, index) => [project.id, index] as const)); - const previousOrderByCwd = new Map( - previous.map((project, index) => [project.cwd, index] as const), - ); - const persistedOrderByCwd = new Map( - persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const), - ); - const usePersistedOrder = previous.length === 0; - - const mappedProjects = incoming.map((project) => { - const existing = previousById.get(project.id) ?? previousByCwd.get(project.workspaceRoot); - return { - id: project.id, - name: project.title, - cwd: project.workspaceRoot, - defaultModelSelection: - existing?.defaultModelSelection ?? - (project.defaultModelSelection - ? { - ...project.defaultModelSelection, - model: resolveModelSlugForProvider( - project.defaultModelSelection.provider, - project.defaultModelSelection.model, - ), - } - : null), - expanded: - existing?.expanded ?? - (persistedExpandedProjectCwds.size > 0 - ? persistedExpandedProjectCwds.has(project.workspaceRoot) - : true), - createdAt: project.createdAt, - updatedAt: project.updatedAt, - scripts: project.scripts.map((script) => ({ ...script })), - } satisfies Project; + let changed = false; + const next = projects.map((project) => { + if (project.id !== projectId) { + return project; + } + const updated = updater(project); + if (updated !== project) { + changed = true; + } + return updated; }); + return changed ? next : projects; +} - return mappedProjects - .map((project, incomingIndex) => { - const previousIndex = - previousOrderById.get(project.id) ?? previousOrderByCwd.get(project.cwd); - const persistedIndex = usePersistedOrder ? persistedOrderByCwd.get(project.cwd) : undefined; - const orderIndex = - previousIndex ?? - persistedIndex ?? - (usePersistedOrder ? persistedProjectOrderCwds.length : previous.length) + incomingIndex; - return { project, incomingIndex, orderIndex }; - }) - .toSorted((a, b) => { - const byOrder = a.orderIndex - b.orderIndex; - if (byOrder !== 0) return byOrder; - return a.incomingIndex - b.incomingIndex; - }) - .map((entry) => entry.project); +function normalizeModelSelection( + selection: T, +): T { + return { + ...selection, + model: resolveModelSlugForProvider(selection.provider, selection.model), + }; +} + +function mapProjectScripts(scripts: ReadonlyArray): Project["scripts"] { + return scripts.map((script) => ({ ...script })); +} + +function mapSession(session: OrchestrationSession): Thread["session"] { + return { + provider: toLegacyProvider(session.providerName), + status: toLegacySessionStatus(session.status), + orchestrationStatus: session.status, + activeTurnId: session.activeTurnId ?? undefined, + createdAt: session.updatedAt, + updatedAt: session.updatedAt, + ...(session.lastError ? { lastError: session.lastError } : {}), + }; +} + +function mapMessage(message: OrchestrationMessage): ChatMessage { + const attachments = message.attachments?.map((attachment) => ({ + type: "image" as const, + id: attachment.id, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)), + })); + + return { + id: message.id, + role: message.role, + text: message.text, + turnId: message.turnId, + createdAt: message.createdAt, + streaming: message.streaming, + ...(message.streaming ? {} : { completedAt: message.updatedAt }), + ...(attachments && attachments.length > 0 ? { attachments } : {}), + }; +} + +function mapProposedPlan(proposedPlan: OrchestrationProposedPlan): Thread["proposedPlans"][number] { + return { + id: proposedPlan.id, + turnId: proposedPlan.turnId, + planMarkdown: proposedPlan.planMarkdown, + implementedAt: proposedPlan.implementedAt, + implementationThreadId: proposedPlan.implementationThreadId, + createdAt: proposedPlan.createdAt, + updatedAt: proposedPlan.updatedAt, + }; +} + +function mapTurnDiffSummary( + checkpoint: OrchestrationCheckpointSummary, +): Thread["turnDiffSummaries"][number] { + return { + turnId: checkpoint.turnId, + completedAt: checkpoint.completedAt, + status: checkpoint.status, + assistantMessageId: checkpoint.assistantMessageId ?? undefined, + checkpointTurnCount: checkpoint.checkpointTurnCount, + checkpointRef: checkpoint.checkpointRef, + files: checkpoint.files.map((file) => ({ ...file })), + }; +} + +function mapThread(thread: OrchestrationThread): Thread { + return { + id: thread.id, + codexThreadId: null, + projectId: thread.projectId, + title: thread.title, + modelSelection: normalizeModelSelection(thread.modelSelection), + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + session: thread.session ? mapSession(thread.session) : null, + messages: thread.messages.map(mapMessage), + proposedPlans: thread.proposedPlans.map(mapProposedPlan), + error: thread.session?.lastError ?? null, + createdAt: thread.createdAt, + archivedAt: thread.archivedAt, + updatedAt: thread.updatedAt, + latestTurn: thread.latestTurn, + pendingSourceProposedPlan: thread.latestTurn?.sourceProposedPlan, + branch: thread.branch, + worktreePath: thread.worktreePath, + turnDiffSummaries: thread.checkpoints.map(mapTurnDiffSummary), + activities: thread.activities.map((activity) => ({ ...activity })), + }; +} + +function mapProject(project: OrchestrationReadModel["projects"][number]): Project { + return { + id: project.id, + name: project.title, + cwd: project.workspaceRoot, + defaultModelSelection: project.defaultModelSelection + ? normalizeModelSelection(project.defaultModelSelection) + : null, + createdAt: project.createdAt, + updatedAt: project.updatedAt, + scripts: mapProjectScripts(project.scripts), + }; +} + +function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") { + if (status === "error") { + return "error" as const; + } + if (status === "missing") { + return "interrupted" as const; + } + return "completed" as const; +} + +function compareActivities( + left: Thread["activities"][number], + right: Thread["activities"][number], +): number { + if (left.sequence !== undefined && right.sequence !== undefined) { + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + } else if (left.sequence !== undefined) { + return 1; + } else if (right.sequence !== undefined) { + return -1; + } + + return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); +} + +function buildLatestTurn(params: { + previous: Thread["latestTurn"]; + turnId: NonNullable["turnId"]; + state: NonNullable["state"]; + requestedAt: string; + startedAt: string | null; + completedAt: string | null; + assistantMessageId: NonNullable["assistantMessageId"]; + sourceProposedPlan?: Thread["pendingSourceProposedPlan"]; +}): NonNullable { + const resolvedPlan = + params.previous?.turnId === params.turnId + ? params.previous.sourceProposedPlan + : params.sourceProposedPlan; + return { + turnId: params.turnId, + state: params.state, + requestedAt: params.requestedAt, + startedAt: params.startedAt, + completedAt: params.completedAt, + assistantMessageId: params.assistantMessageId, + ...(resolvedPlan ? { sourceProposedPlan: resolvedPlan } : {}), + }; +} + +function rebindTurnDiffSummariesForAssistantMessage( + turnDiffSummaries: ReadonlyArray, + turnId: Thread["turnDiffSummaries"][number]["turnId"], + assistantMessageId: NonNullable["assistantMessageId"], +): Thread["turnDiffSummaries"] { + let changed = false; + const nextSummaries = turnDiffSummaries.map((summary) => { + if (summary.turnId !== turnId || summary.assistantMessageId === assistantMessageId) { + return summary; + } + changed = true; + return { + ...summary, + assistantMessageId: assistantMessageId ?? undefined, + }; + }); + return changed ? nextSummaries : [...turnDiffSummaries]; +} + +function retainThreadMessagesAfterRevert( + messages: ReadonlyArray, + retainedTurnIds: ReadonlySet, + turnCount: number, +): ChatMessage[] { + const retainedMessageIds = new Set(); + for (const message of messages) { + if (message.role === "system") { + retainedMessageIds.add(message.id); + continue; + } + if ( + message.turnId !== undefined && + message.turnId !== null && + retainedTurnIds.has(message.turnId) + ) { + retainedMessageIds.add(message.id); + } + } + + const retainedUserCount = messages.filter( + (message) => message.role === "user" && retainedMessageIds.has(message.id), + ).length; + const missingUserCount = Math.max(0, turnCount - retainedUserCount); + if (missingUserCount > 0) { + const fallbackUserMessages = messages + .filter( + (message) => + message.role === "user" && + !retainedMessageIds.has(message.id) && + (message.turnId === undefined || + message.turnId === null || + retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingUserCount); + for (const message of fallbackUserMessages) { + retainedMessageIds.add(message.id); + } + } + + const retainedAssistantCount = messages.filter( + (message) => message.role === "assistant" && retainedMessageIds.has(message.id), + ).length; + const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount); + if (missingAssistantCount > 0) { + const fallbackAssistantMessages = messages + .filter( + (message) => + message.role === "assistant" && + !retainedMessageIds.has(message.id) && + (message.turnId === undefined || + message.turnId === null || + retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingAssistantCount); + for (const message of fallbackAssistantMessages) { + retainedMessageIds.add(message.id); + } + } + + return messages.filter((message) => retainedMessageIds.has(message.id)); +} + +function retainThreadActivitiesAfterRevert( + activities: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): Thread["activities"] { + return activities.filter( + (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), + ); +} + +function retainThreadProposedPlansAfterRevert( + proposedPlans: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): Thread["proposedPlans"] { + return proposedPlans.filter( + (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId), + ); } function toLegacySessionStatus( @@ -234,165 +401,505 @@ function attachmentPreviewRoutePath(attachmentId: string): string { // ── Pure state transition functions ──────────────────────────────────── export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState { - const projects = mapProjectsFromReadModel( - readModel.projects.filter((project) => project.deletedAt === null), - state.projects, - ); - const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const)); - const threads = readModel.threads - .filter((thread) => thread.deletedAt === null) - .map((thread) => { - const existing = existingThreadById.get(thread.id); - return { - id: thread.id, - codexThreadId: null, - projectId: thread.projectId, - title: thread.title, - modelSelection: { - ...thread.modelSelection, - model: resolveModelSlugForProvider( - thread.modelSelection.provider, - thread.modelSelection.model, - ), - }, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - session: thread.session - ? { - provider: toLegacyProvider(thread.session.providerName), - status: toLegacySessionStatus(thread.session.status), - orchestrationStatus: thread.session.status, - activeTurnId: thread.session.activeTurnId ?? undefined, - createdAt: thread.session.updatedAt, - updatedAt: thread.session.updatedAt, - ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}), - } - : null, - messages: thread.messages.map((message) => { - const attachments = message.attachments?.map((attachment) => ({ - type: "image" as const, - id: attachment.id, - name: attachment.name, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)), - })); - const normalizedMessage: ChatMessage = { - id: message.id, - role: message.role, - text: message.text, - createdAt: message.createdAt, - streaming: message.streaming, - ...(message.streaming ? {} : { completedAt: message.updatedAt }), - ...(attachments && attachments.length > 0 ? { attachments } : {}), - }; - return normalizedMessage; - }), - proposedPlans: thread.proposedPlans.map((proposedPlan) => ({ - id: proposedPlan.id, - turnId: proposedPlan.turnId, - planMarkdown: proposedPlan.planMarkdown, - implementedAt: proposedPlan.implementedAt, - implementationThreadId: proposedPlan.implementationThreadId, - createdAt: proposedPlan.createdAt, - updatedAt: proposedPlan.updatedAt, - })), - error: thread.session?.lastError ?? null, - createdAt: thread.createdAt, - updatedAt: thread.updatedAt, - latestTurn: thread.latestTurn, - lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt, - branch: thread.branch, - worktreePath: thread.worktreePath, - turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({ - turnId: checkpoint.turnId, - completedAt: checkpoint.completedAt, - status: checkpoint.status, - assistantMessageId: checkpoint.assistantMessageId ?? undefined, - checkpointTurnCount: checkpoint.checkpointTurnCount, - checkpointRef: checkpoint.checkpointRef, - files: checkpoint.files.map((file) => ({ ...file })), - })), - activities: thread.activities.map((activity) => ({ ...activity })), - }; - }); + const projects = readModel.projects + .filter((project) => project.deletedAt === null) + .map(mapProject); + const threads = readModel.threads.filter((thread) => thread.deletedAt === null).map(mapThread); return { ...state, projects, threads, - threadsHydrated: true, + bootstrapComplete: true, }; } -export function markThreadVisited( - state: AppState, - threadId: ThreadId, - visitedAt?: string, -): AppState { - const at = visitedAt ?? new Date().toISOString(); - const visitedAtMs = Date.parse(at); - const threads = updateThread(state.threads, threadId, (thread) => { - const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN; - if ( - Number.isFinite(previousVisitedAtMs) && - Number.isFinite(visitedAtMs) && - previousVisitedAtMs >= visitedAtMs - ) { - return thread; +export function applyOrchestrationEvent(state: AppState, event: OrchestrationEvent): AppState { + switch (event.type) { + case "project.created": { + const existingIndex = state.projects.findIndex( + (project) => + project.id === event.payload.projectId || project.cwd === event.payload.workspaceRoot, + ); + const nextProject = mapProject({ + id: event.payload.projectId, + title: event.payload.title, + workspaceRoot: event.payload.workspaceRoot, + defaultModelSelection: event.payload.defaultModelSelection, + scripts: event.payload.scripts, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + deletedAt: null, + }); + const projects = + existingIndex >= 0 + ? state.projects.map((project, index) => + index === existingIndex ? nextProject : project, + ) + : [...state.projects, nextProject]; + return { ...state, projects }; } - return { ...thread, lastVisitedAt: at }; - }); - return threads === state.threads ? state : { ...state, threads }; + + case "project.meta-updated": { + const projects = updateProject(state.projects, event.payload.projectId, (project) => ({ + ...project, + ...(event.payload.title !== undefined ? { name: event.payload.title } : {}), + ...(event.payload.workspaceRoot !== undefined ? { cwd: event.payload.workspaceRoot } : {}), + ...(event.payload.defaultModelSelection !== undefined + ? { + defaultModelSelection: event.payload.defaultModelSelection + ? normalizeModelSelection(event.payload.defaultModelSelection) + : null, + } + : {}), + ...(event.payload.scripts !== undefined + ? { scripts: mapProjectScripts(event.payload.scripts) } + : {}), + updatedAt: event.payload.updatedAt, + })); + return projects === state.projects ? state : { ...state, projects }; + } + + case "project.deleted": { + const projects = state.projects.filter((project) => project.id !== event.payload.projectId); + return projects.length === state.projects.length ? state : { ...state, projects }; + } + + case "thread.created": { + const existing = state.threads.find((thread) => thread.id === event.payload.threadId); + const nextThread = mapThread({ + id: event.payload.threadId, + projectId: event.payload.projectId, + title: event.payload.title, + modelSelection: event.payload.modelSelection, + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + branch: event.payload.branch, + worktreePath: event.payload.worktreePath, + latestTurn: null, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }); + const threads = existing + ? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread)) + : [...state.threads, nextThread]; + return { ...state, threads }; + } + + case "thread.deleted": { + const threads = state.threads.filter((thread) => thread.id !== event.payload.threadId); + return threads.length === state.threads.length ? state : { ...state, threads }; + } + + case "thread.archived": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + archivedAt: event.payload.archivedAt, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.unarchived": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + archivedAt: null, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.meta-updated": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), + ...(event.payload.modelSelection !== undefined + ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) } + : {}), + ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), + ...(event.payload.worktreePath !== undefined + ? { worktreePath: event.payload.worktreePath } + : {}), + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.runtime-mode-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + runtimeMode: event.payload.runtimeMode, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.interaction-mode-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + interactionMode: event.payload.interactionMode, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-start-requested": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + ...(event.payload.modelSelection !== undefined + ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) } + : {}), + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + pendingSourceProposedPlan: event.payload.sourceProposedPlan, + updatedAt: event.occurredAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-interrupt-requested": { + if (event.payload.turnId === undefined) { + return state; + } + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const latestTurn = thread.latestTurn; + if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { + return thread; + } + return { + ...thread, + latestTurn: buildLatestTurn({ + previous: latestTurn, + turnId: event.payload.turnId, + state: "interrupted", + requestedAt: latestTurn.requestedAt, + startedAt: latestTurn.startedAt ?? event.payload.createdAt, + completedAt: latestTurn.completedAt ?? event.payload.createdAt, + assistantMessageId: latestTurn.assistantMessageId, + }), + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.message-sent": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const message = mapMessage({ + id: event.payload.messageId, + role: event.payload.role, + text: event.payload.text, + ...(event.payload.attachments !== undefined + ? { attachments: event.payload.attachments } + : {}), + turnId: event.payload.turnId, + streaming: event.payload.streaming, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }); + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = existingMessage + ? thread.messages.map((entry) => + entry.id !== message.id + ? entry + : { + ...entry, + text: message.streaming + ? `${entry.text}${message.text}` + : message.text.length > 0 + ? message.text + : entry.text, + streaming: message.streaming, + ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), + ...(message.streaming + ? entry.completedAt !== undefined + ? { completedAt: entry.completedAt } + : {} + : message.completedAt !== undefined + ? { completedAt: message.completedAt } + : {}), + ...(message.attachments !== undefined + ? { attachments: message.attachments } + : {}), + }, + ) + : [...thread.messages, message]; + const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES); + const turnDiffSummaries = + event.payload.role === "assistant" && event.payload.turnId !== null + ? rebindTurnDiffSummariesForAssistantMessage( + thread.turnDiffSummaries, + event.payload.turnId, + event.payload.messageId, + ) + : thread.turnDiffSummaries; + const latestTurn: Thread["latestTurn"] = + event.payload.role === "assistant" && + event.payload.turnId !== null && + (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId) + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.turnId, + state: event.payload.streaming + ? "running" + : thread.latestTurn?.state === "interrupted" + ? "interrupted" + : thread.latestTurn?.state === "error" + ? "error" + : "completed", + requestedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? thread.latestTurn.requestedAt + : event.payload.createdAt, + startedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.startedAt ?? event.payload.createdAt) + : event.payload.createdAt, + sourceProposedPlan: thread.pendingSourceProposedPlan, + completedAt: event.payload.streaming + ? thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.completedAt ?? null) + : null + : event.payload.updatedAt, + assistantMessageId: event.payload.messageId, + }) + : thread.latestTurn; + return { + ...thread, + messages: cappedMessages, + turnDiffSummaries, + latestTurn, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.session-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + session: mapSession(event.payload.session), + error: event.payload.session.lastError ?? null, + latestTurn: + event.payload.session.status === "running" && event.payload.session.activeTurnId !== null + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.session.activeTurnId, + state: "running", + requestedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.requestedAt + : event.payload.session.updatedAt, + startedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt) + : event.payload.session.updatedAt, + completedAt: null, + assistantMessageId: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.assistantMessageId + : null, + sourceProposedPlan: thread.pendingSourceProposedPlan, + }) + : thread.latestTurn, + updatedAt: event.occurredAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.session-stop-requested": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => + thread.session === null + ? thread + : { + ...thread, + session: { + ...thread.session, + status: "closed", + orchestrationStatus: "stopped", + activeTurnId: undefined, + updatedAt: event.payload.createdAt, + }, + updatedAt: event.occurredAt, + }, + ); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.proposed-plan-upserted": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const proposedPlan = mapProposedPlan(event.payload.proposedPlan); + const proposedPlans = [ + ...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id), + proposedPlan, + ] + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(-MAX_THREAD_PROPOSED_PLANS); + return { + ...thread, + proposedPlans, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-diff-completed": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const checkpoint = mapTurnDiffSummary({ + turnId: event.payload.turnId, + checkpointTurnCount: event.payload.checkpointTurnCount, + checkpointRef: event.payload.checkpointRef, + status: event.payload.status, + files: event.payload.files, + assistantMessageId: event.payload.assistantMessageId, + completedAt: event.payload.completedAt, + }); + const existing = thread.turnDiffSummaries.find( + (entry) => entry.turnId === checkpoint.turnId, + ); + if (existing && existing.status !== "missing" && checkpoint.status === "missing") { + return thread; + } + const turnDiffSummaries = [ + ...thread.turnDiffSummaries.filter((entry) => entry.turnId !== checkpoint.turnId), + checkpoint, + ] + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-MAX_THREAD_CHECKPOINTS); + const latestTurn = + thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.turnId, + state: checkpointStatusToLatestTurnState(event.payload.status), + requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt, + startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt, + completedAt: event.payload.completedAt, + assistantMessageId: event.payload.assistantMessageId, + sourceProposedPlan: thread.pendingSourceProposedPlan, + }) + : thread.latestTurn; + return { + ...thread, + turnDiffSummaries, + latestTurn, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.reverted": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const turnDiffSummaries = thread.turnDiffSummaries + .filter( + (entry) => + entry.checkpointTurnCount !== undefined && + entry.checkpointTurnCount <= event.payload.turnCount, + ) + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-MAX_THREAD_CHECKPOINTS); + const retainedTurnIds = new Set(turnDiffSummaries.map((entry) => entry.turnId)); + const messages = retainThreadMessagesAfterRevert( + thread.messages, + retainedTurnIds, + event.payload.turnCount, + ).slice(-MAX_THREAD_MESSAGES); + const proposedPlans = retainThreadProposedPlansAfterRevert( + thread.proposedPlans, + retainedTurnIds, + ).slice(-MAX_THREAD_PROPOSED_PLANS); + const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds); + const latestCheckpoint = turnDiffSummaries.at(-1) ?? null; + + return { + ...thread, + turnDiffSummaries, + messages, + proposedPlans, + activities, + pendingSourceProposedPlan: undefined, + latestTurn: + latestCheckpoint === null + ? null + : { + turnId: latestCheckpoint.turnId, + state: checkpointStatusToLatestTurnState( + (latestCheckpoint.status ?? "ready") as "ready" | "missing" | "error", + ), + requestedAt: latestCheckpoint.completedAt, + startedAt: latestCheckpoint.completedAt, + completedAt: latestCheckpoint.completedAt, + assistantMessageId: latestCheckpoint.assistantMessageId ?? null, + }, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.activity-appended": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const activities = [ + ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id), + { ...event.payload.activity }, + ] + .toSorted(compareActivities) + .slice(-MAX_THREAD_ACTIVITIES); + return { + ...thread, + activities, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.approval-response-requested": + case "thread.user-input-response-requested": + return state; + } + + return state; } -export function markThreadUnread(state: AppState, threadId: ThreadId): AppState { - const threads = updateThread(state.threads, threadId, (thread) => { - if (!thread.latestTurn?.completedAt) return thread; - const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt); - if (Number.isNaN(latestTurnCompletedAtMs)) return thread; - const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString(); - if (thread.lastVisitedAt === unreadVisitedAt) return thread; - return { ...thread, lastVisitedAt: unreadVisitedAt }; - }); - return threads === state.threads ? state : { ...state, threads }; -} - -export function toggleProject(state: AppState, projectId: Project["id"]): AppState { - return { - ...state, - projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)), - }; -} - -export function setProjectExpanded( +export function applyOrchestrationEvents( state: AppState, - projectId: Project["id"], - expanded: boolean, + events: ReadonlyArray, ): AppState { - let changed = false; - const projects = state.projects.map((p) => { - if (p.id !== projectId || p.expanded === expanded) return p; - changed = true; - return { ...p, expanded }; - }); - return changed ? { ...state, projects } : state; + if (events.length === 0) { + return state; + } + return events.reduce((nextState, event) => applyOrchestrationEvent(nextState, event), state); } -export function reorderProjects( - state: AppState, - draggedProjectId: Project["id"], - targetProjectId: Project["id"], -): AppState { - if (draggedProjectId === targetProjectId) return state; - const draggedIndex = state.projects.findIndex((project) => project.id === draggedProjectId); - const targetIndex = state.projects.findIndex((project) => project.id === targetProjectId); - if (draggedIndex < 0 || targetIndex < 0) return state; - const projects = [...state.projects]; - const [draggedProject] = projects.splice(draggedIndex, 1); - if (!draggedProject) return state; - projects.splice(targetIndex, 0, draggedProject); - return { ...state, projects }; -} +export const selectProjectById = + (projectId: Project["id"] | null | undefined) => + (state: AppState): Project | undefined => + projectId ? state.projects.find((project) => project.id === projectId) : undefined; + +export const selectThreadById = + (threadId: ThreadId | null | undefined) => + (state: AppState): Thread | undefined => + threadId ? state.threads.find((thread) => thread.id === threadId) : undefined; export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState { const threads = updateThread(state.threads, threadId, (t) => { @@ -425,44 +932,18 @@ export function setThreadBranch( interface AppStore extends AppState { syncServerReadModel: (readModel: OrchestrationReadModel) => void; - markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void; - markThreadUnread: (threadId: ThreadId) => void; - toggleProject: (projectId: Project["id"]) => void; - setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void; - reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void; + applyOrchestrationEvent: (event: OrchestrationEvent) => void; + applyOrchestrationEvents: (events: ReadonlyArray) => void; setError: (threadId: ThreadId, error: string | null) => void; setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void; } export const useStore = create((set) => ({ - ...readPersistedState(), + ...initialState, syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)), - markThreadVisited: (threadId, visitedAt) => - set((state) => markThreadVisited(state, threadId, visitedAt)), - markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)), - toggleProject: (projectId) => set((state) => toggleProject(state, projectId)), - setProjectExpanded: (projectId, expanded) => - set((state) => setProjectExpanded(state, projectId, expanded)), - reorderProjects: (draggedProjectId, targetProjectId) => - set((state) => reorderProjects(state, draggedProjectId, targetProjectId)), + applyOrchestrationEvent: (event) => set((state) => applyOrchestrationEvent(state, event)), + applyOrchestrationEvents: (events) => set((state) => applyOrchestrationEvents(state, events)), setError: (threadId, error) => set((state) => setError(state, threadId, error)), setThreadBranch: (threadId, branch, worktreePath) => set((state) => setThreadBranch(state, threadId, branch, worktreePath)), })); - -// Persist state changes with debouncing to avoid localStorage thrashing -useStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); - -// Flush pending writes synchronously before page unload to prevent data loss. -if (typeof window !== "undefined") { - window.addEventListener("beforeunload", () => { - debouncedPersistState.flush(); - }); -} - -export function StoreProvider({ children }: { children: ReactNode }) { - useEffect(() => { - persistState(useStore.getState()); - }, []); - return createElement(Fragment, null, children); -} diff --git a/apps/web/src/storeSelectors.ts b/apps/web/src/storeSelectors.ts new file mode 100644 index 0000000000..271fbb256b --- /dev/null +++ b/apps/web/src/storeSelectors.ts @@ -0,0 +1,14 @@ +import { type ThreadId } from "@t3tools/contracts"; +import { useMemo } from "react"; +import { selectProjectById, selectThreadById, useStore } from "./store"; +import { type Project, type Thread } from "./types"; + +export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined { + const selector = useMemo(() => selectProjectById(projectId), [projectId]); + return useStore(selector); +} + +export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined { + const selector = useMemo(() => selectThreadById(threadId), [threadId]); + return useStore(selector); +} diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index 1e5fb39405..db0544fcef 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -43,6 +43,32 @@ describe("extractTerminalLinks", () => { }, ]); }); + + it("finds Windows absolute paths with forward slashes", () => { + const line = "see C:/Users/someone/project/src/file.ts:42 for details"; + const path = "C:/Users/someone/project/src/file.ts:42"; + const start = line.indexOf(path); + expect(extractTerminalLinks(line)).toEqual([ + { + kind: "path", + text: path, + start, + end: start + path.length, + }, + ]); + }); + + it("trims trailing punctuation from Windows forward-slash paths", () => { + const line = "(C:/tmp/x.ts)."; + expect(extractTerminalLinks(line)).toEqual([ + { + kind: "path", + text: "C:/tmp/x.ts", + start: 1, + end: 12, + }, + ]); + }); }); describe("resolvePathLinkTarget", () => { @@ -60,6 +86,12 @@ describe("resolvePathLinkTarget", () => { resolvePathLinkTarget("/Users/julius/project/src/main.ts:12", "/Users/julius/project"), ).toBe("/Users/julius/project/src/main.ts:12"); }); + + it("keeps Windows absolute paths with forward slashes unchanged", () => { + expect( + resolvePathLinkTarget("C:/Users/julius/project/src/main.ts:12", "C:\\Users\\julius\\project"), + ).toBe("C:/Users/julius/project/src/main.ts:12"); + }); }); describe("isTerminalLinkActivation", () => { diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index 1119fc9087..e07904e180 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -11,7 +11,7 @@ export interface TerminalLinkMatch { const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g; const FILE_PATH_PATTERN = - /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g; + /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g; const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/; function trimClosingDelimiters(value: string): string { diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.ts index e7e240cf25..d618275682 100644 --- a/apps/web/src/terminalStateStore.test.ts +++ b/apps/web/src/terminalStateStore.test.ts @@ -7,9 +7,7 @@ const THREAD_ID = ThreadId.makeUnsafe("thread-1"); describe("terminalStateStore actions", () => { beforeEach(() => { - if (typeof localStorage !== "undefined") { - localStorage.clear(); - } + useTerminalStateStore.persist.clearStorage(); useTerminalStateStore.setState({ terminalStateByThreadId: {} }); }); diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.ts index b2cea6d560..62e0883516 100644 --- a/apps/web/src/terminalStateStore.ts +++ b/apps/web/src/terminalStateStore.ts @@ -8,6 +8,7 @@ import type { ThreadId } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; +import { resolveStorage } from "./lib/storage"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -27,6 +28,10 @@ interface ThreadTerminalState { const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1"; +function createTerminalStateStorage() { + return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined); +} + function normalizeTerminalIds(terminalIds: string[]): string[] { const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))]; return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID]; @@ -480,6 +485,7 @@ interface TerminalStateStoreState { hasRunningSubprocess: boolean, ) => void; clearTerminalState: (threadId: ThreadId) => void; + removeTerminalState: (threadId: ThreadId) => void; removeOrphanedTerminalStates: (activeThreadIds: Set) => void; } @@ -525,6 +531,15 @@ export const useTerminalStateStore = create()( ), clearTerminalState: (threadId) => updateTerminal(threadId, () => createDefaultThreadTerminalState()), + removeTerminalState: (threadId) => + set((state) => { + if (state.terminalStateByThreadId[threadId] === undefined) { + return state; + } + const next = { ...state.terminalStateByThreadId }; + delete next[threadId]; + return { terminalStateByThreadId: next }; + }), removeOrphanedTerminalStates: (activeThreadIds) => set((state) => { const orphanedIds = Object.keys(state.terminalStateByThreadId).filter( @@ -542,7 +557,7 @@ export const useTerminalStateStore = create()( { name: TERMINAL_STATE_STORAGE_KEY, version: 1, - storage: createJSONStorage(() => localStorage), + storage: createJSONStorage(createTerminalStateStorage), partialize: (state) => ({ terminalStateByThreadId: state.terminalStateByThreadId, }), diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index a75ab21019..453c070166 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -66,3 +66,8 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: st const days = Math.floor(hours / 24); return { value: `${days}d`, suffix: "ago" }; } + +export function formatRelativeTimeLabel(isoDate: string) { + const relative = formatRelativeTime(isoDate); + return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value; +} diff --git a/apps/web/src/truncateTitle.test.ts b/apps/web/src/truncateTitle.test.ts deleted file mode 100644 index d7d61c5da1..0000000000 --- a/apps/web/src/truncateTitle.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { truncateTitle } from "./truncateTitle"; - -describe("truncateTitle", () => { - it("trims surrounding whitespace", () => { - expect(truncateTitle(" hello world ")).toBe("hello world"); - }); - - it("returns trimmed text when within max length", () => { - expect(truncateTitle("alpha", 10)).toBe("alpha"); - }); - - it("appends ellipsis when text exceeds max length", () => { - expect(truncateTitle("abcdefghij", 5)).toBe("abcde..."); - }); -}); diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index de06f95538..0ebf150310 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -45,6 +45,7 @@ export interface ChatMessage { role: "user" | "assistant" | "system"; text: string; attachments?: ChatAttachment[]; + turnId?: TurnId | null; createdAt: string; completedAt?: string | undefined; streaming: boolean; @@ -82,7 +83,6 @@ export interface Project { name: string; cwd: string; defaultModelSelection: ModelSelection | null; - expanded: boolean; createdAt?: string | undefined; updatedAt?: string | undefined; scripts: ProjectScript[]; @@ -101,9 +101,10 @@ export interface Thread { proposedPlans: ProposedPlan[]; error: string | null; createdAt: string; + archivedAt: string | null; updatedAt?: string | undefined; latestTurn: OrchestrationLatestTurn | null; - lastVisitedAt?: string | undefined; + pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"]; branch: string | null; worktreePath: string | null; turnDiffSummaries: TurnDiffSummary[]; diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts new file mode 100644 index 0000000000..b0b19f763a --- /dev/null +++ b/apps/web/src/uiStateStore.test.ts @@ -0,0 +1,192 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; + +import { + clearThreadUi, + markThreadUnread, + reorderProjects, + setProjectExpanded, + syncProjects, + syncThreads, + type UiState, +} from "./uiStateStore"; + +function makeUiState(overrides: Partial = {}): UiState { + return { + projectExpandedById: {}, + projectOrder: [], + threadLastVisitedAtById: {}, + ...overrides, + }; +} + +describe("uiStateStore pure functions", () => { + it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => { + const threadId = ThreadId.makeUnsafe("thread-1"); + const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; + const initialState = makeUiState({ + threadLastVisitedAtById: { + [threadId]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt); + + expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z"); + }); + + it("markThreadUnread does not change a thread without a completed turn", () => { + const threadId = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [threadId]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = markThreadUnread(initialState, threadId, null); + + expect(next).toBe(initialState); + }); + + it("reorderProjects moves a project to a target index", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const project2 = ProjectId.makeUnsafe("project-2"); + const project3 = ProjectId.makeUnsafe("project-3"); + const initialState = makeUiState({ + projectOrder: [project1, project2, project3], + }); + + const next = reorderProjects(initialState, project1, project3); + + expect(next.projectOrder).toEqual([project2, project3, project1]); + }); + + it("syncProjects preserves current project order during snapshot recovery", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const project2 = ProjectId.makeUnsafe("project-2"); + const project3 = ProjectId.makeUnsafe("project-3"); + const initialState = makeUiState({ + projectExpandedById: { + [project1]: true, + [project2]: false, + }, + projectOrder: [project2, project1], + }); + + const next = syncProjects(initialState, [ + { id: project1, cwd: "/tmp/project-1" }, + { id: project2, cwd: "/tmp/project-2" }, + { id: project3, cwd: "/tmp/project-3" }, + ]); + + expect(next.projectOrder).toEqual([project2, project1, project3]); + expect(next.projectExpandedById[project2]).toBe(false); + }); + + it("syncProjects preserves manual order when a project is recreated with the same cwd", () => { + const oldProject1 = ProjectId.makeUnsafe("project-1"); + const oldProject2 = ProjectId.makeUnsafe("project-2"); + const recreatedProject2 = ProjectId.makeUnsafe("project-2b"); + const initialState = syncProjects( + makeUiState({ + projectExpandedById: { + [oldProject1]: true, + [oldProject2]: false, + }, + projectOrder: [oldProject2, oldProject1], + }), + [ + { id: oldProject1, cwd: "/tmp/project-1" }, + { id: oldProject2, cwd: "/tmp/project-2" }, + ], + ); + + const next = syncProjects(initialState, [ + { id: oldProject1, cwd: "/tmp/project-1" }, + { id: recreatedProject2, cwd: "/tmp/project-2" }, + ]); + + expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]); + expect(next.projectExpandedById[recreatedProject2]).toBe(false); + }); + + it("syncProjects returns a new state when only project cwd changes", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const initialState = syncProjects( + makeUiState({ + projectExpandedById: { + [project1]: false, + }, + projectOrder: [project1], + }), + [{ id: project1, cwd: "/tmp/project-1" }], + ); + + const next = syncProjects(initialState, [{ id: project1, cwd: "/tmp/project-1-renamed" }]); + + expect(next).not.toBe(initialState); + expect(next.projectOrder).toEqual([project1]); + expect(next.projectExpandedById[project1]).toBe(false); + }); + + it("syncThreads prunes missing thread UI state", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const thread2 = ThreadId.makeUnsafe("thread-2"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [thread1]: "2026-02-25T12:35:00.000Z", + [thread2]: "2026-02-25T12:36:00.000Z", + }, + }); + + const next = syncThreads(initialState, [{ id: thread1 }]); + + expect(next.threadLastVisitedAtById).toEqual({ + [thread1]: "2026-02-25T12:35:00.000Z", + }); + }); + + it("syncThreads seeds visit state for unseen snapshot threads", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState(); + + const next = syncThreads(initialState, [ + { + id: thread1, + seedVisitedAt: "2026-02-25T12:35:00.000Z", + }, + ]); + + expect(next.threadLastVisitedAtById).toEqual({ + [thread1]: "2026-02-25T12:35:00.000Z", + }); + }); + + it("setProjectExpanded updates expansion without touching order", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const initialState = makeUiState({ + projectExpandedById: { + [project1]: true, + }, + projectOrder: [project1], + }); + + const next = setProjectExpanded(initialState, project1, false); + + expect(next.projectExpandedById[project1]).toBe(false); + expect(next.projectOrder).toEqual([project1]); + }); + + it("clearThreadUi removes visit state for deleted threads", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [thread1]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = clearThreadUi(initialState, thread1); + + expect(next.threadLastVisitedAtById).toEqual({}); + }); +}); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts new file mode 100644 index 0000000000..342f2db18f --- /dev/null +++ b/apps/web/src/uiStateStore.ts @@ -0,0 +1,417 @@ +import { Debouncer } from "@tanstack/react-pacer"; +import { type ProjectId, type ThreadId } from "@t3tools/contracts"; +import { create } from "zustand"; + +const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; +const LEGACY_PERSISTED_STATE_KEYS = [ + "t3code:renderer-state:v8", + "t3code:renderer-state:v7", + "t3code:renderer-state:v6", + "t3code:renderer-state:v5", + "t3code:renderer-state:v4", + "t3code:renderer-state:v3", + "codething:renderer-state:v4", + "codething:renderer-state:v3", + "codething:renderer-state:v2", + "codething:renderer-state:v1", +] as const; + +interface PersistedUiState { + expandedProjectCwds?: string[]; + projectOrderCwds?: string[]; +} + +export interface UiProjectState { + projectExpandedById: Record; + projectOrder: ProjectId[]; +} + +export interface UiThreadState { + threadLastVisitedAtById: Record; +} + +export interface UiState extends UiProjectState, UiThreadState {} + +export interface SyncProjectInput { + id: ProjectId; + cwd: string; +} + +export interface SyncThreadInput { + id: ThreadId; + seedVisitedAt?: string | undefined; +} + +const initialState: UiState = { + projectExpandedById: {}, + projectOrder: [], + threadLastVisitedAtById: {}, +}; + +const persistedExpandedProjectCwds = new Set(); +const persistedProjectOrderCwds: string[] = []; +const currentProjectCwdById = new Map(); +let legacyKeysCleanedUp = false; + +function readPersistedState(): UiState { + if (typeof window === "undefined") { + return initialState; + } + try { + const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); + if (!raw) { + for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { + const legacyRaw = window.localStorage.getItem(legacyKey); + if (!legacyRaw) { + continue; + } + hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState); + return initialState; + } + return initialState; + } + hydratePersistedProjectState(JSON.parse(raw) as PersistedUiState); + return initialState; + } catch { + return initialState; + } +} + +function hydratePersistedProjectState(parsed: PersistedUiState): void { + persistedExpandedProjectCwds.clear(); + persistedProjectOrderCwds.length = 0; + for (const cwd of parsed.expandedProjectCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0) { + persistedExpandedProjectCwds.add(cwd); + } + } + for (const cwd of parsed.projectOrderCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) { + persistedProjectOrderCwds.push(cwd); + } + } +} + +function persistState(state: UiState): void { + if (typeof window === "undefined") { + return; + } + try { + const expandedProjectCwds = Object.entries(state.projectExpandedById) + .filter(([, expanded]) => expanded) + .flatMap(([projectId]) => { + const cwd = currentProjectCwdById.get(projectId as ProjectId); + return cwd ? [cwd] : []; + }); + const projectOrderCwds = state.projectOrder.flatMap((projectId) => { + const cwd = currentProjectCwdById.get(projectId); + return cwd ? [cwd] : []; + }); + window.localStorage.setItem( + PERSISTED_STATE_KEY, + JSON.stringify({ + expandedProjectCwds, + projectOrderCwds, + } satisfies PersistedUiState), + ); + if (!legacyKeysCleanedUp) { + legacyKeysCleanedUp = true; + for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { + window.localStorage.removeItem(legacyKey); + } + } + } catch { + // Ignore quota/storage errors to avoid breaking chat UX. + } +} + +const debouncedPersistState = new Debouncer(persistState, { wait: 500 }); + +function recordsEqual(left: Record, right: Record): boolean { + const leftEntries = Object.entries(left); + const rightEntries = Object.entries(right); + if (leftEntries.length !== rightEntries.length) { + return false; + } + for (const [key, value] of leftEntries) { + if (right[key] !== value) { + return false; + } + } + return true; +} + +function projectOrdersEqual(left: readonly ProjectId[], right: readonly ProjectId[]): boolean { + return ( + left.length === right.length && left.every((projectId, index) => projectId === right[index]) + ); +} + +export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState { + const previousProjectCwdById = new Map(currentProjectCwdById); + const previousProjectIdByCwd = new Map( + [...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const), + ); + currentProjectCwdById.clear(); + for (const project of projects) { + currentProjectCwdById.set(project.id, project.cwd); + } + const cwdMappingChanged = + previousProjectCwdById.size !== currentProjectCwdById.size || + projects.some((project) => previousProjectCwdById.get(project.id) !== project.cwd); + + const nextExpandedById: Record = {}; + const previousExpandedById = state.projectExpandedById; + const persistedOrderByCwd = new Map( + persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const), + ); + const mappedProjects = projects.map((project, index) => { + const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd); + const expanded = + previousExpandedById[project.id] ?? + (previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ?? + (persistedExpandedProjectCwds.size > 0 + ? persistedExpandedProjectCwds.has(project.cwd) + : true); + nextExpandedById[project.id] = expanded; + return { + id: project.id, + cwd: project.cwd, + incomingIndex: index, + }; + }); + + const nextProjectOrder = + state.projectOrder.length > 0 + ? (() => { + const nextProjectIdByCwd = new Map( + mappedProjects.map((project) => [project.cwd, project.id] as const), + ); + const usedProjectIds = new Set(); + const orderedProjectIds: ProjectId[] = []; + + for (const projectId of state.projectOrder) { + const matchedProjectId = + (projectId in nextExpandedById ? projectId : undefined) ?? + (() => { + const previousCwd = previousProjectCwdById.get(projectId); + return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined; + })(); + if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) { + continue; + } + usedProjectIds.add(matchedProjectId); + orderedProjectIds.push(matchedProjectId); + } + + for (const project of mappedProjects) { + if (usedProjectIds.has(project.id)) { + continue; + } + orderedProjectIds.push(project.id); + } + + return orderedProjectIds; + })() + : mappedProjects + .map((project) => ({ + id: project.id, + incomingIndex: project.incomingIndex, + orderIndex: + persistedOrderByCwd.get(project.cwd) ?? + persistedProjectOrderCwds.length + project.incomingIndex, + })) + .toSorted((left, right) => { + const byOrder = left.orderIndex - right.orderIndex; + if (byOrder !== 0) { + return byOrder; + } + return left.incomingIndex - right.incomingIndex; + }) + .map((project) => project.id); + + if ( + recordsEqual(state.projectExpandedById, nextExpandedById) && + projectOrdersEqual(state.projectOrder, nextProjectOrder) && + !cwdMappingChanged + ) { + return state; + } + + return { + ...state, + projectExpandedById: nextExpandedById, + projectOrder: nextProjectOrder, + }; +} + +export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState { + const retainedThreadIds = new Set(threads.map((thread) => thread.id)); + const nextThreadLastVisitedAtById = Object.fromEntries( + Object.entries(state.threadLastVisitedAtById).filter(([threadId]) => + retainedThreadIds.has(threadId as ThreadId), + ), + ); + for (const thread of threads) { + if ( + nextThreadLastVisitedAtById[thread.id] === undefined && + thread.seedVisitedAt !== undefined && + thread.seedVisitedAt.length > 0 + ) { + nextThreadLastVisitedAtById[thread.id] = thread.seedVisitedAt; + } + } + if (recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById)) { + return state; + } + return { + ...state, + threadLastVisitedAtById: nextThreadLastVisitedAtById, + }; +} + +export function markThreadVisited(state: UiState, threadId: ThreadId, visitedAt?: string): UiState { + const at = visitedAt ?? new Date().toISOString(); + const visitedAtMs = Date.parse(at); + const previousVisitedAt = state.threadLastVisitedAtById[threadId]; + const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN; + if ( + Number.isFinite(previousVisitedAtMs) && + Number.isFinite(visitedAtMs) && + previousVisitedAtMs >= visitedAtMs + ) { + return state; + } + return { + ...state, + threadLastVisitedAtById: { + ...state.threadLastVisitedAtById, + [threadId]: at, + }, + }; +} + +export function markThreadUnread( + state: UiState, + threadId: ThreadId, + latestTurnCompletedAt: string | null | undefined, +): UiState { + if (!latestTurnCompletedAt) { + return state; + } + const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt); + if (Number.isNaN(latestTurnCompletedAtMs)) { + return state; + } + const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString(); + if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) { + return state; + } + return { + ...state, + threadLastVisitedAtById: { + ...state.threadLastVisitedAtById, + [threadId]: unreadVisitedAt, + }, + }; +} + +export function clearThreadUi(state: UiState, threadId: ThreadId): UiState { + if (!(threadId in state.threadLastVisitedAtById)) { + return state; + } + const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById }; + delete nextThreadLastVisitedAtById[threadId]; + return { + ...state, + threadLastVisitedAtById: nextThreadLastVisitedAtById, + }; +} + +export function toggleProject(state: UiState, projectId: ProjectId): UiState { + const expanded = state.projectExpandedById[projectId] ?? true; + return { + ...state, + projectExpandedById: { + ...state.projectExpandedById, + [projectId]: !expanded, + }, + }; +} + +export function setProjectExpanded( + state: UiState, + projectId: ProjectId, + expanded: boolean, +): UiState { + if ((state.projectExpandedById[projectId] ?? true) === expanded) { + return state; + } + return { + ...state, + projectExpandedById: { + ...state.projectExpandedById, + [projectId]: expanded, + }, + }; +} + +export function reorderProjects( + state: UiState, + draggedProjectId: ProjectId, + targetProjectId: ProjectId, +): UiState { + if (draggedProjectId === targetProjectId) { + return state; + } + const draggedIndex = state.projectOrder.findIndex((projectId) => projectId === draggedProjectId); + const targetIndex = state.projectOrder.findIndex((projectId) => projectId === targetProjectId); + if (draggedIndex < 0 || targetIndex < 0) { + return state; + } + const projectOrder = [...state.projectOrder]; + const [draggedProject] = projectOrder.splice(draggedIndex, 1); + if (!draggedProject) { + return state; + } + projectOrder.splice(targetIndex, 0, draggedProject); + return { + ...state, + projectOrder, + }; +} + +interface UiStateStore extends UiState { + syncProjects: (projects: readonly SyncProjectInput[]) => void; + syncThreads: (threads: readonly SyncThreadInput[]) => void; + markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void; + markThreadUnread: (threadId: ThreadId, latestTurnCompletedAt: string | null | undefined) => void; + clearThreadUi: (threadId: ThreadId) => void; + toggleProject: (projectId: ProjectId) => void; + setProjectExpanded: (projectId: ProjectId, expanded: boolean) => void; + reorderProjects: (draggedProjectId: ProjectId, targetProjectId: ProjectId) => void; +} + +export const useUiStateStore = create((set) => ({ + ...readPersistedState(), + syncProjects: (projects) => set((state) => syncProjects(state, projects)), + syncThreads: (threads) => set((state) => syncThreads(state, threads)), + markThreadVisited: (threadId, visitedAt) => + set((state) => markThreadVisited(state, threadId, visitedAt)), + markThreadUnread: (threadId, latestTurnCompletedAt) => + set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)), + clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)), + toggleProject: (projectId) => set((state) => toggleProject(state, projectId)), + setProjectExpanded: (projectId, expanded) => + set((state) => setProjectExpanded(state, projectId, expanded)), + reorderProjects: (draggedProjectId, targetProjectId) => + set((state) => reorderProjects(state, draggedProjectId, targetProjectId)), +})); + +useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); + +if (typeof window !== "undefined") { + window.addEventListener("beforeunload", () => { + debouncedPersistState.flush(); + }); +} diff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.ts index 574675ae11..723661ccbb 100644 --- a/apps/web/src/worktreeCleanup.test.ts +++ b/apps/web/src/worktreeCleanup.test.ts @@ -23,6 +23,7 @@ function makeThread(overrides: Partial = {}): Thread { proposedPlans: [], error: null, createdAt: "2026-02-13T00:00:00.000Z", + archivedAt: null, latestTurn: null, branch: null, worktreePath: null, diff --git a/apps/web/src/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.ts index 9e612543d0..c9bcc7ffd2 100644 --- a/apps/web/src/wsNativeApi.test.ts +++ b/apps/web/src/wsNativeApi.test.ts @@ -1,23 +1,19 @@ import { CommandId, - type ContextMenuItem, + DEFAULT_SERVER_SETTINGS, + type DesktopBridge, EventId, - ORCHESTRATION_WS_CHANNELS, - ORCHESTRATION_WS_METHODS, - type OrchestrationEvent, ProjectId, - ThreadId, - type WsPushChannel, - type WsPushData, - type WsPushMessage, - WS_CHANNELS, - WS_METHODS, - type WsPush, + type OrchestrationEvent, + type ServerConfig, type ServerProvider, + type TerminalEvent, + ThreadId, } from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const requestMock = vi.fn<(...args: Array) => Promise>(); +import type { ContextMenuItem } from "@t3tools/contracts"; + const showContextMenuFallbackMock = vi.fn< ( @@ -25,39 +21,75 @@ const showContextMenuFallbackMock = position?: { x: number; y: number }, ) => Promise >(); -const channelListeners = new Map void>>(); -const latestPushByChannel = new Map(); -const subscribeMock = vi.fn< - ( - channel: string, - listener: (message: WsPush) => void, - options?: { replayLatest?: boolean }, - ) => () => void ->((channel, listener, options) => { - const listeners = channelListeners.get(channel) ?? new Set<(message: WsPush) => void>(); + +function registerListener(listeners: Set<(event: T) => void>, listener: (event: T) => void) { listeners.add(listener); - channelListeners.set(channel, listeners); - const latest = latestPushByChannel.get(channel); - if (latest && options?.replayLatest) { - listener(latest); - } return () => { listeners.delete(listener); - if (listeners.size === 0) { - channelListeners.delete(channel); - } }; -}); +} -vi.mock("./wsTransport", () => { +const terminalEventListeners = new Set<(event: TerminalEvent) => void>(); +const orchestrationEventListeners = new Set<(event: OrchestrationEvent) => void>(); + +const rpcClientMock = { + dispose: vi.fn(), + terminal: { + open: vi.fn(), + write: vi.fn(), + resize: vi.fn(), + clear: vi.fn(), + restart: vi.fn(), + close: vi.fn(), + onEvent: vi.fn((listener: (event: TerminalEvent) => void) => + registerListener(terminalEventListeners, listener), + ), + }, + projects: { + searchEntries: vi.fn(), + writeFile: vi.fn(), + }, + shell: { + openInEditor: vi.fn(), + }, + git: { + pull: vi.fn(), + status: vi.fn(), + runStackedAction: vi.fn(), + listBranches: vi.fn(), + createWorktree: vi.fn(), + removeWorktree: vi.fn(), + createBranch: vi.fn(), + checkout: vi.fn(), + init: vi.fn(), + resolvePullRequest: vi.fn(), + preparePullRequestThread: vi.fn(), + }, + server: { + getConfig: vi.fn(), + refreshProviders: vi.fn(), + upsertKeybinding: vi.fn(), + getSettings: vi.fn(), + updateSettings: vi.fn(), + subscribeConfig: vi.fn(), + subscribeLifecycle: vi.fn(), + }, + orchestration: { + getSnapshot: vi.fn(), + dispatchCommand: vi.fn(), + getTurnDiff: vi.fn(), + getFullThreadDiff: vi.fn(), + replayEvents: vi.fn(), + onDomainEvent: vi.fn((listener: (event: OrchestrationEvent) => void) => + registerListener(orchestrationEventListeners, listener), + ), + }, +}; + +vi.mock("./wsRpcClient", () => { return { - WsTransport: class MockWsTransport { - request = requestMock; - subscribe = subscribeMock; - getLatestPush(channel: string) { - return latestPushByChannel.get(channel) ?? null; - } - }, + getWsRpcClient: () => rpcClientMock, + __resetWsRpcClientForTests: vi.fn(), }; }); @@ -65,20 +97,9 @@ vi.mock("./contextMenuFallback", () => ({ showContextMenuFallback: showContextMenuFallbackMock, })); -let nextPushSequence = 1; - -function emitPush(channel: C, data: WsPushData): void { - const listeners = channelListeners.get(channel); - const message = { - type: "push" as const, - sequence: nextPushSequence++, - channel, - data, - } as WsPushMessage; - latestPushByChannel.set(channel, message); - if (!listeners) return; +function emitEvent(listeners: Set<(event: T) => void>, event: T) { for (const listener of listeners) { - listener(message); + listener(event); } } @@ -92,6 +113,32 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn return testGlobal.window; } +function makeDesktopBridge(overrides: Partial = {}): DesktopBridge { + return { + getWsUrl: () => null, + pickFolder: async () => null, + confirm: async () => true, + setTheme: async () => undefined, + showContextMenu: async () => null, + openExternal: async () => true, + onMenuAction: () => () => undefined, + getUpdateState: async () => { + throw new Error("getUpdateState not implemented in test"); + }, + checkForUpdate: async () => { + throw new Error("checkForUpdate not implemented in test"); + }, + downloadUpdate: async () => { + throw new Error("downloadUpdate not implemented in test"); + }, + installUpdate: async () => { + throw new Error("installUpdate not implemented in test"); + }, + onUpdateState: () => () => undefined, + ...overrides, + }; +} + const defaultProviders: ReadonlyArray = [ { provider: "codex", @@ -99,20 +146,28 @@ const defaultProviders: ReadonlyArray = [ installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", models: [], }, ]; +const baseServerConfig: ServerConfig = { + cwd: "/tmp/workspace", + keybindingsConfigPath: "/tmp/workspace/.config/keybindings.json", + keybindings: [], + issues: [], + providers: defaultProviders, + availableEditors: ["cursor"], + settings: DEFAULT_SERVER_SETTINGS, +}; + beforeEach(() => { vi.resetModules(); - requestMock.mockReset(); + vi.clearAllMocks(); showContextMenuFallbackMock.mockReset(); - subscribeMock.mockClear(); - channelListeners.clear(); - latestPushByChannel.clear(); - nextPushSequence = 1; + terminalEventListeners.clear(); + orchestrationEventListeners.clear(); Reflect.deleteProperty(getWindowForTest(), "desktopBridge"); }); @@ -121,149 +176,27 @@ afterEach(() => { }); describe("wsNativeApi", () => { - it("delivers and caches valid server.welcome payloads", async () => { - const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi"); + it("forwards server config fetches directly to the RPC client", async () => { + rpcClientMock.server.getConfig.mockResolvedValue(baseServerConfig); + const { createWsNativeApi } = await import("./wsNativeApi"); - createWsNativeApi(); - const listener = vi.fn(); - onServerWelcome(listener); + const api = createWsNativeApi(); - const payload = { cwd: "/tmp/workspace", projectName: "t3-code" }; - emitPush(WS_CHANNELS.serverWelcome, payload); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith(expect.objectContaining(payload)); - - const lateListener = vi.fn(); - onServerWelcome(lateListener); - - expect(lateListener).toHaveBeenCalledTimes(1); - expect(lateListener).toHaveBeenCalledWith(expect.objectContaining(payload)); + await expect(api.server.getConfig()).resolves.toEqual(baseServerConfig); + expect(rpcClientMock.server.getConfig).toHaveBeenCalledWith(); + expect(rpcClientMock.server.subscribeConfig).not.toHaveBeenCalled(); + expect(rpcClientMock.server.subscribeLifecycle).not.toHaveBeenCalled(); }); - it("preserves bootstrap ids from server.welcome payloads", async () => { - const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi"); - - createWsNativeApi(); - const listener = vi.fn(); - onServerWelcome(listener); - - emitPush(WS_CHANNELS.serverWelcome, { - cwd: "/tmp/workspace", - projectName: "t3-code", - bootstrapProjectId: ProjectId.makeUnsafe("project-1"), - bootstrapThreadId: ThreadId.makeUnsafe("thread-1"), - }); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith( - expect.objectContaining({ - cwd: "/tmp/workspace", - projectName: "t3-code", - bootstrapProjectId: "project-1", - bootstrapThreadId: "thread-1", - }), - ); - }); - - it("delivers successive server.welcome payloads to active listeners", async () => { - const { createWsNativeApi, onServerWelcome } = await import("./wsNativeApi"); - - createWsNativeApi(); - const listener = vi.fn(); - onServerWelcome(listener); - - emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/one", projectName: "one" }); - emitPush(WS_CHANNELS.serverWelcome, { cwd: "/tmp/workspace", projectName: "t3-code" }); - - expect(listener).toHaveBeenCalledTimes(2); - expect(listener).toHaveBeenLastCalledWith( - expect.objectContaining({ - cwd: "/tmp/workspace", - projectName: "t3-code", - }), - ); - }); - - it("delivers and caches valid server.configUpdated payloads", async () => { - const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi"); - - createWsNativeApi(); - const listener = vi.fn(); - onServerConfigUpdated(listener); - - const payload = { - issues: [ - { - kind: "keybindings.invalid-entry", - index: 1, - message: "Entry at index 1 is invalid.", - }, - ], - } as const; - emitPush(WS_CHANNELS.serverConfigUpdated, payload); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith(payload); - - const lateListener = vi.fn(); - onServerConfigUpdated(lateListener); - expect(lateListener).toHaveBeenCalledTimes(1); - expect(lateListener).toHaveBeenCalledWith(payload); - }); - - it("delivers successive server.configUpdated payloads to active listeners", async () => { - const { createWsNativeApi, onServerConfigUpdated } = await import("./wsNativeApi"); - - createWsNativeApi(); - const listener = vi.fn(); - onServerConfigUpdated(listener); - - emitPush(WS_CHANNELS.serverConfigUpdated, { - issues: [{ kind: "keybindings.malformed-config", message: "bad json" }], - }); - emitPush(WS_CHANNELS.serverConfigUpdated, { - issues: [], - }); - - expect(listener).toHaveBeenCalledTimes(2); - expect(listener).toHaveBeenLastCalledWith({ - issues: [], - }); - }); - - it("delivers and caches valid server.providersUpdated payloads", async () => { - const { createWsNativeApi, onServerProvidersUpdated } = await import("./wsNativeApi"); - - createWsNativeApi(); - const listener = vi.fn(); - onServerProvidersUpdated(listener); - - const payload = { - providers: defaultProviders, - } as const; - emitPush(WS_CHANNELS.serverProvidersUpdated, payload); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith(payload); - - const lateListener = vi.fn(); - onServerProvidersUpdated(lateListener); - expect(lateListener).toHaveBeenCalledTimes(1); - expect(lateListener).toHaveBeenCalledWith(payload); - }); - - it("forwards valid terminal and orchestration events", async () => { + it("forwards terminal and orchestration stream events", async () => { const { createWsNativeApi } = await import("./wsNativeApi"); const api = createWsNativeApi(); const onTerminalEvent = vi.fn(); const onDomainEvent = vi.fn(); - const onActionProgress = vi.fn(); api.terminal.onEvent(onTerminalEvent); api.orchestration.onDomainEvent(onDomainEvent); - api.git.onActionProgress(onActionProgress); const terminalEvent = { threadId: "thread-1", @@ -272,7 +205,7 @@ describe("wsNativeApi", () => { type: "output", data: "hello", } as const; - emitPush(WS_CHANNELS.terminalEvent, terminalEvent); + emitEvent(terminalEventListeners, terminalEvent); const orchestrationEvent = { sequence: 1, @@ -289,39 +222,23 @@ describe("wsNativeApi", () => { projectId: ProjectId.makeUnsafe("project-1"), title: "Project", workspaceRoot: "/tmp/workspace", - defaultModelSelection: null, + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, scripts: [], createdAt: "2026-02-24T00:00:00.000Z", updatedAt: "2026-02-24T00:00:00.000Z", }, } satisfies Extract; - emitPush(ORCHESTRATION_WS_CHANNELS.domainEvent, orchestrationEvent); - emitPush(WS_CHANNELS.gitActionProgress, { - actionId: "action-1", - cwd: "/repo", - action: "commit", - kind: "phase_started", - phase: "commit", - label: "Committing...", - }); + emitEvent(orchestrationEventListeners, orchestrationEvent); - expect(onTerminalEvent).toHaveBeenCalledTimes(1); expect(onTerminalEvent).toHaveBeenCalledWith(terminalEvent); - expect(onDomainEvent).toHaveBeenCalledTimes(1); expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent); - expect(onActionProgress).toHaveBeenCalledTimes(1); - expect(onActionProgress).toHaveBeenCalledWith({ - actionId: "action-1", - cwd: "/repo", - action: "commit", - kind: "phase_started", - phase: "commit", - label: "Committing...", - }); }); - it("wraps orchestration dispatch commands in the command envelope", async () => { - requestMock.mockResolvedValue(undefined); + it("sends orchestration dispatch commands as the direct RPC payload", async () => { + rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 }); const { createWsNativeApi } = await import("./wsNativeApi"); const api = createWsNativeApi(); @@ -339,13 +256,11 @@ describe("wsNativeApi", () => { } as const; await api.orchestration.dispatchCommand(command); - expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.dispatchCommand, { - command, - }); + expect(rpcClientMock.orchestration.dispatchCommand).toHaveBeenCalledWith(command); }); - it("forwards workspace file writes to the websocket project method", async () => { - requestMock.mockResolvedValue({ relativePath: "plan.md" }); + it("forwards workspace file writes to the project RPC", async () => { + rpcClientMock.projects.writeFile.mockResolvedValue({ relativePath: "plan.md" }); const { createWsNativeApi } = await import("./wsNativeApi"); const api = createWsNativeApi(); @@ -355,43 +270,15 @@ describe("wsNativeApi", () => { contents: "# Plan\n", }); - expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, { + expect(rpcClientMock.projects.writeFile).toHaveBeenCalledWith({ cwd: "/tmp/project", relativePath: "plan.md", contents: "# Plan\n", }); }); - it("uses no client timeout for git.runStackedAction", async () => { - requestMock.mockResolvedValue({ - action: "commit", - branch: { status: "skipped_not_requested" }, - commit: { status: "created", commitSha: "abc1234", subject: "Test" }, - push: { status: "skipped_not_requested" }, - pr: { status: "skipped_not_requested" }, - }); - const { createWsNativeApi } = await import("./wsNativeApi"); - - const api = createWsNativeApi(); - await api.git.runStackedAction({ - actionId: "action-1", - cwd: "/repo", - action: "commit", - }); - - expect(requestMock).toHaveBeenCalledWith( - WS_METHODS.gitRunStackedAction, - { - actionId: "action-1", - cwd: "/repo", - action: "commit", - }, - { timeoutMs: null }, - ); - }); - - it("forwards full-thread diff requests to the orchestration websocket method", async () => { - requestMock.mockResolvedValue({ diff: "patch" }); + it("forwards full-thread diff requests to the orchestration RPC", async () => { + rpcClientMock.orchestration.getFullThreadDiff.mockResolvedValue({ diff: "patch" }); const { createWsNativeApi } = await import("./wsNativeApi"); const api = createWsNativeApi(); @@ -400,55 +287,66 @@ describe("wsNativeApi", () => { toTurnCount: 1, }); - expect(requestMock).toHaveBeenCalledWith(ORCHESTRATION_WS_METHODS.getFullThreadDiff, { + expect(rpcClientMock.orchestration.getFullThreadDiff).toHaveBeenCalledWith({ threadId: "thread-1", toTurnCount: 1, }); }); - it("forwards context menu metadata to desktop bridge", async () => { - const showContextMenu = vi.fn().mockResolvedValue("delete"); - Object.defineProperty(getWindowForTest(), "desktopBridge", { - configurable: true, - writable: true, - value: { - showContextMenu, + it("forwards provider refreshes directly to the RPC client", async () => { + const nextProviders: ReadonlyArray = [ + { + ...defaultProviders[0]!, + checkedAt: "2026-01-03T00:00:00.000Z", }, - }); - + ]; + rpcClientMock.server.refreshProviders.mockResolvedValue({ providers: nextProviders }); const { createWsNativeApi } = await import("./wsNativeApi"); - const api = createWsNativeApi(); - await api.contextMenu.show( - [ - { id: "rename", label: "Rename thread" }, - { id: "delete", label: "Delete", destructive: true }, - ], - { x: 200, y: 300 }, - ); - expect(showContextMenu).toHaveBeenCalledWith( - [ - { id: "rename", label: "Rename thread" }, - { id: "delete", label: "Delete", destructive: true }, - ], - { x: 200, y: 300 }, - ); + const api = createWsNativeApi(); + + await expect(api.server.refreshProviders()).resolves.toEqual({ providers: nextProviders }); + expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith(); }); - it("uses fallback context menu when desktop bridge is unavailable", async () => { - showContextMenuFallbackMock.mockResolvedValue("delete"); - Reflect.deleteProperty(getWindowForTest(), "desktopBridge"); + it("forwards server settings updates directly to the RPC client", async () => { + const nextSettings = { + ...DEFAULT_SERVER_SETTINGS, + enableAssistantStreaming: true, + }; + rpcClientMock.server.updateSettings.mockResolvedValue(nextSettings); + const { createWsNativeApi } = await import("./wsNativeApi"); + + const api = createWsNativeApi(); + + await expect(api.server.updateSettings({ enableAssistantStreaming: true })).resolves.toEqual( + nextSettings, + ); + expect(rpcClientMock.server.updateSettings).toHaveBeenCalledWith({ + enableAssistantStreaming: true, + }); + }); + + it("forwards context menu metadata to the desktop bridge", async () => { + const showContextMenu = vi.fn().mockResolvedValue("delete"); + getWindowForTest().desktopBridge = makeDesktopBridge({ showContextMenu }); const { createWsNativeApi } = await import("./wsNativeApi"); const api = createWsNativeApi(); - await api.contextMenu.show([{ id: "delete", label: "Delete", destructive: true }], { - x: 20, - y: 30, - }); + const items = [{ id: "delete", label: "Delete" }] as const; - expect(showContextMenuFallbackMock).toHaveBeenCalledWith( - [{ id: "delete", label: "Delete", destructive: true }], - { x: 20, y: 30 }, - ); + await expect(api.contextMenu.show(items)).resolves.toBe("delete"); + expect(showContextMenu).toHaveBeenCalledWith(items, undefined); + }); + + it("falls back to the browser context menu helper when the desktop bridge is missing", async () => { + showContextMenuFallbackMock.mockResolvedValue("rename"); + const { createWsNativeApi } = await import("./wsNativeApi"); + + const api = createWsNativeApi(); + const items = [{ id: "rename", label: "Rename" }] as const; + + await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename"); + expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 }); }); }); diff --git a/apps/web/src/wsNativeApi.ts b/apps/web/src/wsNativeApi.ts index 7024ffdb47..31160dfa1c 100644 --- a/apps/web/src/wsNativeApi.ts +++ b/apps/web/src/wsNativeApi.ts @@ -1,136 +1,23 @@ -import { - type GitActionProgressEvent, - ORCHESTRATION_WS_CHANNELS, - ORCHESTRATION_WS_METHODS, - type ContextMenuItem, - type NativeApi, - ServerConfigUpdatedPayload, - ServerProviderUpdatedPayload, - WS_CHANNELS, - WS_METHODS, - type WsWelcomePayload, -} from "@t3tools/contracts"; +import { type ContextMenuItem, type NativeApi } from "@t3tools/contracts"; import { showContextMenuFallback } from "./contextMenuFallback"; -import { WsTransport } from "./wsTransport"; +import { resetServerStateForTests } from "./rpc/serverState"; +import { __resetWsRpcClientForTests, getWsRpcClient } from "./wsRpcClient"; -let instance: { api: NativeApi; transport: WsTransport } | null = null; -const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>(); -const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>(); -const providersUpdatedListeners = new Set<(payload: ServerProviderUpdatedPayload) => void>(); -const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>(); +let instance: { api: NativeApi } | null = null; -/** - * Subscribe to the server welcome message. If a welcome was already received - * before this call, the listener fires synchronously with the cached payload. - * This avoids the race between WebSocket connect and React effect registration. - */ -export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void { - welcomeListeners.add(listener); - - const latestWelcome = instance?.transport.getLatestPush(WS_CHANNELS.serverWelcome)?.data ?? null; - if (latestWelcome) { - try { - listener(latestWelcome); - } catch { - // Swallow listener errors - } - } - - return () => { - welcomeListeners.delete(listener); - }; -} - -/** - * Subscribe to server config update events. Replays the latest update for - * late subscribers to avoid missing config validation feedback. - */ -export function onServerConfigUpdated( - listener: (payload: ServerConfigUpdatedPayload) => void, -): () => void { - serverConfigUpdatedListeners.add(listener); - - const latestConfig = - instance?.transport.getLatestPush(WS_CHANNELS.serverConfigUpdated)?.data ?? null; - if (latestConfig) { - try { - listener(latestConfig); - } catch { - // Swallow listener errors - } - } - - return () => { - serverConfigUpdatedListeners.delete(listener); - }; -} - -export function onServerProvidersUpdated( - listener: (payload: ServerProviderUpdatedPayload) => void, -): () => void { - providersUpdatedListeners.add(listener); - - const latestProviders = - instance?.transport.getLatestPush(WS_CHANNELS.serverProvidersUpdated)?.data ?? null; - if (latestProviders) { - try { - listener(latestProviders); - } catch { - // Swallow listener errors - } - } - - return () => { - providersUpdatedListeners.delete(listener); - }; +export function __resetWsNativeApiForTests() { + instance = null; + __resetWsRpcClientForTests(); + resetServerStateForTests(); } export function createWsNativeApi(): NativeApi { - if (instance) return instance.api; + if (instance) { + return instance.api; + } - const transport = new WsTransport(); - - transport.subscribe(WS_CHANNELS.serverWelcome, (message) => { - const payload = message.data; - for (const listener of welcomeListeners) { - try { - listener(payload); - } catch { - // Swallow listener errors - } - } - }); - transport.subscribe(WS_CHANNELS.serverConfigUpdated, (message) => { - const payload = message.data; - for (const listener of serverConfigUpdatedListeners) { - try { - listener(payload); - } catch { - // Swallow listener errors - } - } - }); - transport.subscribe(WS_CHANNELS.serverProvidersUpdated, (message) => { - const payload = message.data; - for (const listener of providersUpdatedListeners) { - try { - listener(payload); - } catch { - // Swallow listener errors - } - } - }); - transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => { - const payload = message.data; - for (const listener of gitActionProgressListeners) { - try { - listener(payload); - } catch { - // Swallow listener errors - } - } - }); + const rpcClient = getWsRpcClient(); const api: NativeApi = { dialogs: { @@ -146,22 +33,20 @@ export function createWsNativeApi(): NativeApi { }, }, terminal: { - open: (input) => transport.request(WS_METHODS.terminalOpen, input), - write: (input) => transport.request(WS_METHODS.terminalWrite, input), - resize: (input) => transport.request(WS_METHODS.terminalResize, input), - clear: (input) => transport.request(WS_METHODS.terminalClear, input), - restart: (input) => transport.request(WS_METHODS.terminalRestart, input), - close: (input) => transport.request(WS_METHODS.terminalClose, input), - onEvent: (callback) => - transport.subscribe(WS_CHANNELS.terminalEvent, (message) => callback(message.data)), + open: (input) => rpcClient.terminal.open(input as never), + write: (input) => rpcClient.terminal.write(input as never), + resize: (input) => rpcClient.terminal.resize(input as never), + clear: (input) => rpcClient.terminal.clear(input as never), + restart: (input) => rpcClient.terminal.restart(input as never), + close: (input) => rpcClient.terminal.close(input as never), + onEvent: (callback) => rpcClient.terminal.onEvent(callback), }, projects: { - searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input), - writeFile: (input) => transport.request(WS_METHODS.projectsWriteFile, input), + searchEntries: rpcClient.projects.searchEntries, + writeFile: rpcClient.projects.writeFile, }, shell: { - openInEditor: (cwd, editor) => - transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }), + openInEditor: (cwd, editor) => rpcClient.shell.openInEditor({ cwd, editor }), openExternal: async (url) => { if (window.desktopBridge) { const opened = await window.desktopBridge.openExternal(url); @@ -171,31 +56,20 @@ export function createWsNativeApi(): NativeApi { return; } - // Some mobile browsers can return null here even when the tab opens. - // Avoid false negatives and let the browser handle popup policy. window.open(url, "_blank", "noopener,noreferrer"); }, }, git: { - pull: (input) => transport.request(WS_METHODS.gitPull, input), - status: (input) => transport.request(WS_METHODS.gitStatus, input), - runStackedAction: (input) => - transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }), - listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input), - createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input), - removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input), - createBranch: (input) => transport.request(WS_METHODS.gitCreateBranch, input), - checkout: (input) => transport.request(WS_METHODS.gitCheckout, input), - init: (input) => transport.request(WS_METHODS.gitInit, input), - resolvePullRequest: (input) => transport.request(WS_METHODS.gitResolvePullRequest, input), - preparePullRequestThread: (input) => - transport.request(WS_METHODS.gitPreparePullRequestThread, input), - onActionProgress: (callback) => { - gitActionProgressListeners.add(callback); - return () => { - gitActionProgressListeners.delete(callback); - }; - }, + pull: rpcClient.git.pull, + status: rpcClient.git.status, + listBranches: rpcClient.git.listBranches, + createWorktree: rpcClient.git.createWorktree, + removeWorktree: rpcClient.git.removeWorktree, + createBranch: rpcClient.git.createBranch, + checkout: rpcClient.git.checkout, + init: rpcClient.git.init, + resolvePullRequest: rpcClient.git.resolvePullRequest, + preparePullRequestThread: rpcClient.git.preparePullRequestThread, }, contextMenu: { show: async ( @@ -209,28 +83,25 @@ export function createWsNativeApi(): NativeApi { }, }, server: { - getConfig: () => transport.request(WS_METHODS.serverGetConfig), - refreshProviders: () => transport.request(WS_METHODS.serverRefreshProviders), - upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input), - getSettings: () => transport.request(WS_METHODS.serverGetSettings), - updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }), + getConfig: rpcClient.server.getConfig, + refreshProviders: rpcClient.server.refreshProviders, + upsertKeybinding: rpcClient.server.upsertKeybinding, + getSettings: rpcClient.server.getSettings, + updateSettings: rpcClient.server.updateSettings, }, orchestration: { - getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot), - dispatchCommand: (command) => - transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, { command }), - getTurnDiff: (input) => transport.request(ORCHESTRATION_WS_METHODS.getTurnDiff, input), - getFullThreadDiff: (input) => - transport.request(ORCHESTRATION_WS_METHODS.getFullThreadDiff, input), + getSnapshot: rpcClient.orchestration.getSnapshot, + dispatchCommand: rpcClient.orchestration.dispatchCommand, + getTurnDiff: rpcClient.orchestration.getTurnDiff, + getFullThreadDiff: rpcClient.orchestration.getFullThreadDiff, replayEvents: (fromSequenceExclusive) => - transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }), - onDomainEvent: (callback) => - transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (message) => - callback(message.data), - ), + rpcClient.orchestration + .replayEvents({ fromSequenceExclusive }) + .then((events) => [...events]), + onDomainEvent: (callback) => rpcClient.orchestration.onDomainEvent(callback), }, }; - instance = { api, transport }; + instance = { api }; return api; } diff --git a/apps/web/src/wsRpcClient.ts b/apps/web/src/wsRpcClient.ts new file mode 100644 index 0000000000..60f51ba707 --- /dev/null +++ b/apps/web/src/wsRpcClient.ts @@ -0,0 +1,207 @@ +import { + type GitActionProgressEvent, + type GitRunStackedActionInput, + type GitRunStackedActionResult, + type NativeApi, + ORCHESTRATION_WS_METHODS, + type ServerSettingsPatch, + WS_METHODS, +} from "@t3tools/contracts"; +import { Effect, Stream } from "effect"; + +import { type WsRpcProtocolClient } from "./rpc/protocol"; +import { WsTransport } from "./wsTransport"; + +type RpcTag = keyof WsRpcProtocolClient & string; +type RpcMethod = WsRpcProtocolClient[TTag]; +type RpcInput = Parameters>[0]; + +type RpcUnaryMethod = + RpcMethod extends (input: any, options?: any) => Effect.Effect + ? (input: RpcInput) => Promise + : never; + +type RpcUnaryNoArgMethod = + RpcMethod extends (input: any, options?: any) => Effect.Effect + ? () => Promise + : never; + +type RpcStreamMethod = + RpcMethod extends (input: any, options?: any) => Stream.Stream + ? (listener: (event: TEvent) => void) => () => void + : never; + +interface GitRunStackedActionOptions { + readonly onProgress?: (event: GitActionProgressEvent) => void; +} + +export interface WsRpcClient { + readonly dispose: () => Promise; + readonly terminal: { + readonly open: RpcUnaryMethod; + readonly write: RpcUnaryMethod; + readonly resize: RpcUnaryMethod; + readonly clear: RpcUnaryMethod; + readonly restart: RpcUnaryMethod; + readonly close: RpcUnaryMethod; + readonly onEvent: RpcStreamMethod; + }; + readonly projects: { + readonly searchEntries: RpcUnaryMethod; + readonly writeFile: RpcUnaryMethod; + }; + readonly shell: { + readonly openInEditor: (input: { + readonly cwd: Parameters[0]; + readonly editor: Parameters[1]; + }) => ReturnType; + }; + readonly git: { + readonly pull: RpcUnaryMethod; + readonly status: RpcUnaryMethod; + readonly runStackedAction: ( + input: GitRunStackedActionInput, + options?: GitRunStackedActionOptions, + ) => Promise; + readonly listBranches: RpcUnaryMethod; + readonly createWorktree: RpcUnaryMethod; + readonly removeWorktree: RpcUnaryMethod; + readonly createBranch: RpcUnaryMethod; + readonly checkout: RpcUnaryMethod; + readonly init: RpcUnaryMethod; + readonly resolvePullRequest: RpcUnaryMethod; + readonly preparePullRequestThread: RpcUnaryMethod< + typeof WS_METHODS.gitPreparePullRequestThread + >; + }; + readonly server: { + readonly getConfig: RpcUnaryNoArgMethod; + readonly refreshProviders: RpcUnaryNoArgMethod; + readonly upsertKeybinding: RpcUnaryMethod; + readonly getSettings: RpcUnaryNoArgMethod; + readonly updateSettings: ( + patch: ServerSettingsPatch, + ) => ReturnType>; + readonly subscribeConfig: RpcStreamMethod; + readonly subscribeLifecycle: RpcStreamMethod; + }; + readonly orchestration: { + readonly getSnapshot: RpcUnaryNoArgMethod; + readonly dispatchCommand: RpcUnaryMethod; + readonly getTurnDiff: RpcUnaryMethod; + readonly getFullThreadDiff: RpcUnaryMethod; + readonly replayEvents: RpcUnaryMethod; + readonly onDomainEvent: RpcStreamMethod; + }; +} + +let sharedWsRpcClient: WsRpcClient | null = null; + +export function getWsRpcClient(): WsRpcClient { + if (sharedWsRpcClient) { + return sharedWsRpcClient; + } + sharedWsRpcClient = createWsRpcClient(); + return sharedWsRpcClient; +} + +export async function __resetWsRpcClientForTests() { + await sharedWsRpcClient?.dispose(); + sharedWsRpcClient = null; +} + +export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { + return { + dispose: () => transport.dispose(), + terminal: { + open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)), + write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)), + resize: (input) => transport.request((client) => client[WS_METHODS.terminalResize](input)), + clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)), + restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)), + close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)), + onEvent: (listener) => + transport.subscribe((client) => client[WS_METHODS.subscribeTerminalEvents]({}), listener), + }, + projects: { + searchEntries: (input) => + transport.request((client) => client[WS_METHODS.projectsSearchEntries](input)), + writeFile: (input) => + transport.request((client) => client[WS_METHODS.projectsWriteFile](input)), + }, + shell: { + openInEditor: (input) => + transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)), + }, + git: { + pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)), + status: (input) => transport.request((client) => client[WS_METHODS.gitStatus](input)), + runStackedAction: async (input, options) => { + let result: GitRunStackedActionResult | null = null; + + await transport.requestStream( + (client) => client[WS_METHODS.gitRunStackedAction](input), + (event) => { + options?.onProgress?.(event); + if (event.kind === "action_finished") { + result = event.result; + } + }, + ); + + if (result) { + return result; + } + + throw new Error("Git action stream completed without a final result."); + }, + listBranches: (input) => + transport.request((client) => client[WS_METHODS.gitListBranches](input)), + createWorktree: (input) => + transport.request((client) => client[WS_METHODS.gitCreateWorktree](input)), + removeWorktree: (input) => + transport.request((client) => client[WS_METHODS.gitRemoveWorktree](input)), + createBranch: (input) => + transport.request((client) => client[WS_METHODS.gitCreateBranch](input)), + checkout: (input) => transport.request((client) => client[WS_METHODS.gitCheckout](input)), + init: (input) => transport.request((client) => client[WS_METHODS.gitInit](input)), + resolvePullRequest: (input) => + transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)), + preparePullRequestThread: (input) => + transport.request((client) => client[WS_METHODS.gitPreparePullRequestThread](input)), + }, + server: { + getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})), + refreshProviders: () => + transport.request((client) => client[WS_METHODS.serverRefreshProviders]({})), + upsertKeybinding: (input) => + transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)), + getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})), + updateSettings: (patch) => + transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })), + subscribeConfig: (listener) => + transport.subscribe((client) => client[WS_METHODS.subscribeServerConfig]({}), listener), + subscribeLifecycle: (listener) => + transport.subscribe((client) => client[WS_METHODS.subscribeServerLifecycle]({}), listener), + }, + orchestration: { + getSnapshot: () => + transport.request((client) => client[ORCHESTRATION_WS_METHODS.getSnapshot]({})), + dispatchCommand: (input) => + transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)), + getTurnDiff: (input) => + transport.request((client) => client[ORCHESTRATION_WS_METHODS.getTurnDiff](input)), + getFullThreadDiff: (input) => + transport.request((client) => client[ORCHESTRATION_WS_METHODS.getFullThreadDiff](input)), + replayEvents: (input) => + transport + .request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input)) + .then((events) => [...events]), + onDomainEvent: (listener) => + transport.subscribe( + (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}), + listener, + ), + }, + }; +} diff --git a/apps/web/src/wsTransport.test.ts b/apps/web/src/wsTransport.test.ts index e66ed7fc0d..2f64f2a692 100644 --- a/apps/web/src/wsTransport.test.ts +++ b/apps/web/src/wsTransport.test.ts @@ -1,10 +1,11 @@ -import { WS_CHANNELS } from "@t3tools/contracts"; +import { WS_METHODS } from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { WsTransport } from "./wsTransport"; type WsEventType = "open" | "message" | "close" | "error"; -type WsListener = (event?: { data?: unknown }) => void; +type WsEvent = { code?: number; data?: unknown; reason?: string; type?: string }; +type WsListener = (event?: WsEvent) => void; const sockets: MockWebSocket[] = []; @@ -16,9 +17,11 @@ class MockWebSocket { readyState = MockWebSocket.CONNECTING; readonly sent: string[] = []; + readonly url: string; private readonly listeners = new Map>(); - constructor(_url: string) { + constructor(url: string) { + this.url = url; sockets.push(this); } @@ -28,25 +31,29 @@ class MockWebSocket { this.listeners.set(type, listeners); } + removeEventListener(type: WsEventType, listener: WsListener) { + this.listeners.get(type)?.delete(listener); + } + send(data: string) { this.sent.push(data); } - close() { + close(code = 1000, reason = "") { this.readyState = MockWebSocket.CLOSED; - this.emit("close"); + this.emit("close", { code, reason, type: "close" }); } open() { this.readyState = MockWebSocket.OPEN; - this.emit("open"); + this.emit("open", { type: "open" }); } serverMessage(data: unknown) { - this.emit("message", { data }); + this.emit("message", { data, type: "message" }); } - private emit(type: WsEventType, event?: { data?: unknown }) { + private emit(type: WsEventType, event?: WsEvent) { const listeners = this.listeners.get(type); if (!listeners) return; for (const listener of listeners) { @@ -65,13 +72,33 @@ function getSocket(): MockWebSocket { return socket; } +async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise { + const startedAt = Date.now(); + for (;;) { + try { + assertion(); + return; + } catch (error) { + if (Date.now() - startedAt >= timeoutMs) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + } +} + beforeEach(() => { sockets.length = 0; Object.defineProperty(globalThis, "window", { configurable: true, value: { - location: { hostname: "localhost", port: "3020" }, + location: { + origin: "http://localhost:3020", + hostname: "localhost", + port: "3020", + protocol: "http:", + }, desktopBridge: undefined, }, }); @@ -85,172 +112,332 @@ afterEach(() => { }); describe("WsTransport", () => { - it("routes valid push envelopes to channel listeners", () => { + it("normalizes root websocket urls to /ws and preserves query params", async () => { + const transport = new WsTransport("ws://localhost:3020/?token=secret-token"); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + expect(getSocket().url).toBe("ws://localhost:3020/ws?token=secret-token"); + await transport.dispose(); + }); + + it("uses wss when falling back to an https page origin", async () => { + Object.assign(window.location, { + origin: "https://app.example.com", + hostname: "app.example.com", + port: "", + protocol: "https:", + }); + + const transport = new WsTransport(); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + expect(getSocket().url).toBe("wss://app.example.com/ws"); + await transport.dispose(); + }); + + it("sends unary RPC requests and resolves successful exits", async () => { const transport = new WsTransport("ws://localhost:3020"); - const socket = getSocket(); - socket.open(); - const listener = vi.fn(); - transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener); - - socket.serverMessage( - JSON.stringify({ - type: "push", - sequence: 1, - channel: WS_CHANNELS.serverConfigUpdated, - data: { issues: [] }, + const requestPromise = transport.request((client) => + client[WS_METHODS.serverUpsertKeybinding]({ + command: "terminal.toggle", + key: "ctrl+k", }), ); - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith({ - type: "push", + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { + _tag: string; + id: string; + payload: unknown; + tag: string; + }; + expect(requestMessage).toMatchObject({ + _tag: "Request", + tag: WS_METHODS.serverUpsertKeybinding, + payload: { + command: "terminal.toggle", + key: "ctrl+k", + }, + }); + + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: { + keybindings: [], + issues: [], + }, + }, + }), + ); + + await expect(requestPromise).resolves.toEqual({ + keybindings: [], + issues: [], + }); + + await transport.dispose(); + }); + + it("delivers stream chunks to subscribers", async () => { + const transport = new WsTransport("ws://localhost:3020"); + const listener = vi.fn(); + + const unsubscribe = transport.subscribe( + (client) => client[WS_METHODS.subscribeServerLifecycle]({}), + listener, + ); + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string; tag: string }; + expect(requestMessage.tag).toBe(WS_METHODS.subscribeServerLifecycle); + + const welcomeEvent = { + version: 1, sequence: 1, - channel: WS_CHANNELS.serverConfigUpdated, - data: { issues: [] }, - }); + type: "welcome", + payload: { + cwd: "/tmp/workspace", + projectName: "workspace", + }, + }; - transport.dispose(); - }); - - it("resolves pending requests for valid response envelopes", async () => { - const transport = new WsTransport("ws://localhost:3020"); - const socket = getSocket(); - socket.open(); - - const requestPromise = transport.request("projects.list"); - const sent = socket.sent.at(-1); - if (!sent) { - throw new Error("Expected request envelope to be sent"); - } - - const requestEnvelope = JSON.parse(sent) as { id: string }; socket.serverMessage( JSON.stringify({ - id: requestEnvelope.id, - result: { projects: [] }, + _tag: "Chunk", + requestId: requestMessage.id, + values: [welcomeEvent], }), ); - await expect(requestPromise).resolves.toEqual({ projects: [] }); + await waitFor(() => { + expect(listener).toHaveBeenCalledWith(welcomeEvent); + }); - transport.dispose(); + unsubscribe(); + await transport.dispose(); }); - it("drops malformed envelopes without crashing transport", () => { - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + it("re-subscribes stream listeners after the stream exits", async () => { const transport = new WsTransport("ws://localhost:3020"); - const socket = getSocket(); - socket.open(); - const listener = vi.fn(); - transport.subscribe(WS_CHANNELS.serverConfigUpdated, listener); - socket.serverMessage("{ invalid-json"); - socket.serverMessage( - JSON.stringify({ - type: "push", - sequence: 2, - channel: 42, - data: { bad: true }, - }), + const unsubscribe = transport.subscribe( + (client) => client[WS_METHODS.subscribeServerLifecycle]({}), + listener, ); - socket.serverMessage( - JSON.stringify({ - type: "push", - sequence: 3, - channel: WS_CHANNELS.serverConfigUpdated, - data: { issues: [] }, - }), - ); - - expect(listener).toHaveBeenCalledTimes(1); - expect(listener).toHaveBeenCalledWith({ - type: "push", - sequence: 3, - channel: WS_CHANNELS.serverConfigUpdated, - data: { issues: [] }, + await waitFor(() => { + expect(sockets).toHaveLength(1); }); - expect(warnSpy).toHaveBeenCalledTimes(2); - expect(warnSpy).toHaveBeenNthCalledWith( - 1, - "Dropped inbound WebSocket envelope", - "SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)", - ); - expect(warnSpy).toHaveBeenNthCalledWith( - 2, - "Dropped inbound WebSocket envelope", - expect.stringContaining('Expected "server.configUpdated"'), - ); - transport.dispose(); - }); - - it("queues requests until the websocket opens", async () => { - const transport = new WsTransport("ws://localhost:3020"); const socket = getSocket(); - - const requestPromise = transport.request("projects.list"); - expect(socket.sent).toHaveLength(0); - socket.open(); - expect(socket.sent).toHaveLength(1); - const requestEnvelope = JSON.parse(socket.sent[0] ?? "{}") as { id: string }; + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const firstRequest = JSON.parse(socket.sent[0] ?? "{}") as { id: string }; socket.serverMessage( JSON.stringify({ - id: requestEnvelope.id, - result: { projects: [] }, + _tag: "Chunk", + requestId: firstRequest.id, + values: [ + { + version: 1, + sequence: 1, + type: "welcome", + payload: { + cwd: "/tmp/one", + projectName: "one", + }, + }, + ], + }), + ); + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: firstRequest.id, + exit: { + _tag: "Success", + value: null, + }, }), ); - await expect(requestPromise).resolves.toEqual({ projects: [] }); - transport.dispose(); - }); + await waitFor(() => { + const nextRequest = socket.sent + .map((message) => JSON.parse(message) as { _tag?: string; id?: string }) + .find((message) => message._tag === "Request" && message.id !== firstRequest.id); + expect(nextRequest).toBeDefined(); + }); - it("does not create a timeout for requests with timeoutMs null", async () => { - const timeoutSpy = vi.spyOn(globalThis, "setTimeout"); - const transport = new WsTransport("ws://localhost:3020"); - const socket = getSocket(); - socket.open(); - - const requestPromise = transport.request( - "git.runStackedAction", - { cwd: "/repo" }, - { timeoutMs: null }, - ); - const sent = socket.sent.at(-1); - if (!sent) { - throw new Error("Expected request envelope to be sent"); + const secondRequest = socket.sent + .map((message) => JSON.parse(message) as { _tag?: string; id?: string; tag?: string }) + .find( + (message): message is { _tag: "Request"; id: string; tag: string } => + message._tag === "Request" && message.id !== firstRequest.id, + ); + if (!secondRequest) { + throw new Error("Expected a resubscribe request"); } - const requestEnvelope = JSON.parse(sent) as { id: string }; + expect(secondRequest.tag).toBe(WS_METHODS.subscribeServerLifecycle); + expect(secondRequest.id).not.toBe(firstRequest.id); + const secondEvent = { + version: 1, + sequence: 2, + type: "welcome", + payload: { + cwd: "/tmp/two", + projectName: "two", + }, + }; socket.serverMessage( JSON.stringify({ - id: requestEnvelope.id, - result: { ok: true }, + _tag: "Chunk", + requestId: secondRequest.id, + values: [secondEvent], }), ); - await expect(requestPromise).resolves.toEqual({ ok: true }); - expect(timeoutSpy.mock.calls.some(([callback]) => typeof callback === "function")).toBe(false); + await waitFor(() => { + expect(listener).toHaveBeenLastCalledWith(secondEvent); + }); - transport.dispose(); + unsubscribe(); + await transport.dispose(); }); - it("rejects pending requests when the websocket closes", async () => { + it("streams finite request events without re-subscribing", async () => { const transport = new WsTransport("ws://localhost:3020"); + const listener = vi.fn(); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); const socket = getSocket(); socket.open(); - const requestPromise = transport.request( - "git.runStackedAction", - { cwd: "/repo" }, - { timeoutMs: null }, + const requestPromise = transport.requestStream( + (client) => + client[WS_METHODS.gitRunStackedAction]({ + actionId: "action-1", + cwd: "/repo", + action: "commit", + }), + listener, ); - socket.close(); + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); - await expect(requestPromise).rejects.toThrow("WebSocket connection closed."); - transport.dispose(); + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string }; + const progressEvent = { + actionId: "action-1", + cwd: "/repo", + action: "commit", + kind: "phase_started", + phase: "commit", + label: "Committing...", + } as const; + + socket.serverMessage( + JSON.stringify({ + _tag: "Chunk", + requestId: requestMessage.id, + values: [progressEvent], + }), + ); + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: null, + }, + }), + ); + + await expect(requestPromise).resolves.toBeUndefined(); + expect(listener).toHaveBeenCalledWith(progressEvent); + expect( + socket.sent.filter((message) => { + const parsed = JSON.parse(message) as { _tag?: string; tag?: string }; + return parsed._tag === "Request" && parsed.tag === WS_METHODS.gitRunStackedAction; + }), + ).toHaveLength(1); + await transport.dispose(); + }); + + it("closes the client scope on the transport runtime before disposing the runtime", async () => { + const callOrder: string[] = []; + let resolveClose!: () => void; + const closePromise = new Promise((resolve) => { + resolveClose = resolve; + }); + + const runtime = { + runPromise: vi.fn(async () => { + callOrder.push("close:start"); + await closePromise; + callOrder.push("close:done"); + return undefined; + }), + dispose: vi.fn(async () => { + callOrder.push("runtime:dispose"); + }), + }; + const transport = { + disposed: false, + clientScope: {} as never, + runtime, + } as unknown as WsTransport; + + WsTransport.prototype.dispose.call(transport); + + expect(runtime.runPromise).toHaveBeenCalledTimes(1); + expect(runtime.dispose).not.toHaveBeenCalled(); + expect((transport as unknown as { disposed: boolean }).disposed).toBe(true); + + resolveClose(); + + await waitFor(() => { + expect(runtime.dispose).toHaveBeenCalledTimes(1); + }); + + expect(callOrder).toEqual(["close:start", "close:done", "runtime:dispose"]); }); }); diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/wsTransport.ts index 12c9a6d958..70042261d5 100644 --- a/apps/web/src/wsTransport.ts +++ b/apps/web/src/wsTransport.ts @@ -1,309 +1,131 @@ +import { Duration, Effect, Exit, ManagedRuntime, Option, Scope, Stream } from "effect"; + import { - type WsPush, - type WsPushChannel, - type WsPushMessage, - WebSocketResponse, - type WsResponse as WsResponseMessage, - WsResponse as WsResponseSchema, -} from "@t3tools/contracts"; -import { decodeUnknownJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson"; -import { Result, Schema } from "effect"; - -type PushListener = (message: WsPushMessage) => void; - -interface PendingRequest { - resolve: (result: unknown) => void; - reject: (error: Error) => void; - timeout: ReturnType | null; -} + createWsRpcProtocolLayer, + makeWsRpcProtocolClient, + type WsRpcProtocolClient, +} from "./rpc/protocol"; +import { RpcClient } from "effect/unstable/rpc"; interface SubscribeOptions { - readonly replayLatest?: boolean; + readonly retryDelay?: Duration.Input; } interface RequestOptions { - readonly timeoutMs?: number | null; + readonly timeout?: Option.Option; } -type TransportState = "connecting" | "open" | "reconnecting" | "closed" | "disposed"; +const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250); -const REQUEST_TIMEOUT_MS = 60_000; -const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000]; -const decodeWsResponse = decodeUnknownJsonResult(WsResponseSchema); -const isWebSocketResponseEnvelope = Schema.is(WebSocketResponse); - -const isWsPushMessage = (value: WsResponseMessage): value is WsPush => - "type" in value && value.type === "push"; - -interface WsRequestEnvelope { - id: string; - body: { - _tag: string; - [key: string]: unknown; - }; -} - -function asError(value: unknown, fallback: string): Error { - if (value instanceof Error) { - return value; +function formatErrorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; } - return new Error(fallback); + return String(error); } export class WsTransport { - private ws: WebSocket | null = null; - private nextId = 1; - private readonly pending = new Map(); - private readonly listeners = new Map void>>(); - private readonly latestPushByChannel = new Map(); - private readonly outboundQueue: string[] = []; - private reconnectAttempt = 0; - private reconnectTimer: ReturnType | null = null; + private readonly runtime: ManagedRuntime.ManagedRuntime; + private readonly clientScope: Scope.Closeable; + private readonly clientPromise: Promise; private disposed = false; - private state: TransportState = "connecting"; - private readonly url: string; constructor(url?: string) { - const bridgeUrl = window.desktopBridge?.getWsUrl(); - const envUrl = import.meta.env.VITE_WS_URL as string | undefined; - this.url = - url ?? - (bridgeUrl && bridgeUrl.length > 0 - ? bridgeUrl - : envUrl && envUrl.length > 0 - ? envUrl - : `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`); - this.connect(); + this.runtime = ManagedRuntime.make(createWsRpcProtocolLayer(url)); + this.clientScope = this.runtime.runSync(Scope.make()); + this.clientPromise = this.runtime.runPromise( + Scope.provide(this.clientScope)(makeWsRpcProtocolClient), + ); } - async request( - method: string, - params?: unknown, - options?: RequestOptions, - ): Promise { - if (typeof method !== "string" || method.length === 0) { - throw new Error("Request method is required"); + async request( + execute: (client: WsRpcProtocolClient) => Effect.Effect, + _options?: RequestOptions, + ): Promise { + if (this.disposed) { + throw new Error("Transport disposed"); } - const id = String(this.nextId++); - const body = params != null ? { ...params, _tag: method } : { _tag: method }; - const message: WsRequestEnvelope = { id, body }; - const encoded = JSON.stringify(message); - - return new Promise((resolve, reject) => { - const timeoutMs = options?.timeoutMs === undefined ? REQUEST_TIMEOUT_MS : options.timeoutMs; - const timeout = - timeoutMs === null - ? null - : setTimeout(() => { - this.pending.delete(id); - reject(new Error(`Request timed out: ${method}`)); - }, timeoutMs); - - this.pending.set(id, { - resolve: resolve as (result: unknown) => void, - reject, - timeout, - }); - - this.send(encoded); - }); + const client = await this.clientPromise; + return await this.runtime.runPromise(Effect.suspend(() => execute(client))); } - subscribe( - channel: C, - listener: PushListener, + async requestStream( + connect: (client: WsRpcProtocolClient) => Stream.Stream, + listener: (value: TValue) => void, + ): Promise { + if (this.disposed) { + throw new Error("Transport disposed"); + } + + const client = await this.clientPromise; + await this.runtime.runPromise( + Stream.runForEach(connect(client), (value) => + Effect.sync(() => { + try { + listener(value); + } catch { + // Swallow listener errors so the stream can finish cleanly. + } + }), + ), + ); + } + + subscribe( + connect: (client: WsRpcProtocolClient) => Stream.Stream, + listener: (value: TValue) => void, options?: SubscribeOptions, ): () => void { - let channelListeners = this.listeners.get(channel); - if (!channelListeners) { - channelListeners = new Set<(message: WsPush) => void>(); - this.listeners.set(channel, channelListeners); + if (this.disposed) { + return () => undefined; } - const wrappedListener = (message: WsPush) => { - listener(message as WsPushMessage); - }; - channelListeners.add(wrappedListener); - - if (options?.replayLatest) { - const latest = this.latestPushByChannel.get(channel); - if (latest) { - wrappedListener(latest); - } - } + let active = true; + const retryDelayMs = options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS; + const cancel = this.runtime.runCallback( + Effect.promise(() => this.clientPromise).pipe( + Effect.flatMap((client) => + Stream.runForEach(connect(client), (value) => + Effect.sync(() => { + if (!active) { + return; + } + try { + listener(value); + } catch { + // Swallow listener errors so the stream stays live. + } + }), + ), + ), + Effect.catch((error) => { + if (!active || this.disposed) { + return Effect.interrupt; + } + return Effect.sync(() => { + console.warn("WebSocket RPC subscription disconnected", { + error: formatErrorMessage(error), + }); + }).pipe(Effect.andThen(Effect.sleep(retryDelayMs))); + }), + Effect.forever, + ), + ); return () => { - channelListeners?.delete(wrappedListener); - if (channelListeners?.size === 0) { - this.listeners.delete(channel); - } + active = false; + cancel(); }; } - getLatestPush(channel: C): WsPushMessage | null { - const latest = this.latestPushByChannel.get(channel); - return latest ? (latest as WsPushMessage) : null; - } - - getState(): TransportState { - return this.state; - } - - dispose() { + async dispose() { + if (this.disposed) { + return; + } this.disposed = true; - this.state = "disposed"; - if (this.reconnectTimer !== null) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - for (const pending of this.pending.values()) { - if (pending.timeout !== null) { - clearTimeout(pending.timeout); - } - pending.reject(new Error("Transport disposed")); - } - this.pending.clear(); - this.outboundQueue.length = 0; - this.ws?.close(); - this.ws = null; - } - - private connect() { - if (this.disposed) { - return; - } - - this.state = this.reconnectAttempt > 0 ? "reconnecting" : "connecting"; - const ws = new WebSocket(this.url); - - ws.addEventListener("open", () => { - this.ws = ws; - this.state = "open"; - this.reconnectAttempt = 0; - this.flushQueue(); + await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)).finally(() => { + this.runtime.dispose(); }); - - ws.addEventListener("message", (event) => { - this.handleMessage(event.data); - }); - - ws.addEventListener("close", () => { - if (this.ws === ws) { - this.ws = null; - this.outboundQueue.length = 0; - for (const [id, pending] of this.pending.entries()) { - if (pending.timeout !== null) { - clearTimeout(pending.timeout); - } - this.pending.delete(id); - pending.reject(new Error("WebSocket connection closed.")); - } - } - if (this.disposed) { - this.state = "disposed"; - return; - } - this.state = "closed"; - this.scheduleReconnect(); - }); - - ws.addEventListener("error", (event) => { - // Log WebSocket errors for debugging (close event will follow) - console.warn("WebSocket connection error", { type: event.type, url: this.url }); - }); - } - - private handleMessage(raw: unknown) { - const result = decodeWsResponse(raw); - if (Result.isFailure(result)) { - console.warn("Dropped inbound WebSocket envelope", formatSchemaError(result.failure)); - return; - } - - const message = result.success; - if (isWsPushMessage(message)) { - this.latestPushByChannel.set(message.channel, message); - const channelListeners = this.listeners.get(message.channel); - if (channelListeners) { - for (const listener of channelListeners) { - try { - listener(message); - } catch { - // Swallow listener errors - } - } - } - return; - } - - if (!isWebSocketResponseEnvelope(message)) { - return; - } - - const pending = this.pending.get(message.id); - if (!pending) { - return; - } - - if (pending.timeout !== null) { - clearTimeout(pending.timeout); - } - this.pending.delete(message.id); - - if (message.error) { - pending.reject(new Error(message.error.message)); - return; - } - - pending.resolve(message.result); - } - - private send(encodedMessage: string) { - if (this.disposed) { - return; - } - - this.outboundQueue.push(encodedMessage); - try { - this.flushQueue(); - } catch { - // Swallow: flushQueue has queued the message for retry on reconnect - } - } - - private flushQueue() { - if (this.ws?.readyState !== WebSocket.OPEN) { - return; - } - - while (this.outboundQueue.length > 0) { - const message = this.outboundQueue.shift(); - if (!message) { - continue; - } - try { - this.ws.send(message); - } catch (error) { - this.outboundQueue.unshift(message); - throw asError(error, "Failed to send WebSocket request."); - } - } - } - - private scheduleReconnect() { - if (this.disposed || this.reconnectTimer !== null) { - return; - } - - const delay = - RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ?? - RECONNECT_DELAYS_MS[0]!; - - this.reconnectAttempt += 1; - this.reconnectTimer = setTimeout(() => { - this.reconnectTimer = null; - this.connect(); - }, delay); } } diff --git a/apps/web/test/wsRpcHarness.ts b/apps/web/test/wsRpcHarness.ts new file mode 100644 index 0000000000..dcb6dc7252 --- /dev/null +++ b/apps/web/test/wsRpcHarness.ts @@ -0,0 +1,169 @@ +import { Effect, Exit, PubSub, Scope, Stream } from "effect"; +import { WS_METHODS, WsRpcGroup } from "@t3tools/contracts"; +import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; + +type RpcServerInstance = RpcServer.RpcServer; + +type BrowserWsClient = { + send: (data: string) => void; +}; + +export type NormalizedWsRpcRequestBody = { + _tag: string; + [key: string]: unknown; +}; + +type UnaryResolverResult = unknown | Promise; + +interface BrowserWsRpcHarnessOptions { + readonly resolveUnary?: (request: NormalizedWsRpcRequestBody) => UnaryResolverResult; + readonly getInitialStreamValues?: ( + request: NormalizedWsRpcRequestBody, + ) => ReadonlyArray | undefined; +} + +const STREAM_METHODS = new Set([ + WS_METHODS.gitRunStackedAction, + WS_METHODS.subscribeOrchestrationDomainEvents, + WS_METHODS.subscribeTerminalEvents, + WS_METHODS.subscribeServerConfig, + WS_METHODS.subscribeServerLifecycle, +]); + +const ALL_RPC_METHODS = Array.from(WsRpcGroup.requests.keys()); + +function normalizeRequest(tag: string, payload: unknown): NormalizedWsRpcRequestBody { + if (payload && typeof payload === "object" && !Array.isArray(payload)) { + return { + _tag: tag, + ...(payload as Record), + }; + } + return { _tag: tag, payload }; +} + +function asEffect(result: UnaryResolverResult): Effect.Effect { + if (result instanceof Promise) { + return Effect.promise(() => result); + } + return Effect.succeed(result); +} + +export class BrowserWsRpcHarness { + readonly requests: Array = []; + + private readonly parser = RpcSerialization.json.makeUnsafe(); + private client: BrowserWsClient | null = null; + private scope: Scope.Closeable | null = null; + private serverReady: Promise | null = null; + private resolveUnary: NonNullable = () => ({}); + private getInitialStreamValues: NonNullable< + BrowserWsRpcHarnessOptions["getInitialStreamValues"] + > = () => []; + private streamPubSubs = new Map>(); + + async reset(options?: BrowserWsRpcHarnessOptions): Promise { + await this.disconnect(); + this.requests.length = 0; + this.resolveUnary = options?.resolveUnary ?? (() => ({})); + this.getInitialStreamValues = options?.getInitialStreamValues ?? (() => []); + this.initializeStreamPubSubs(); + } + + connect(client: BrowserWsClient): void { + if (this.scope) { + void Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined); + } + if (this.streamPubSubs.size === 0) { + this.initializeStreamPubSubs(); + } + this.client = client; + this.scope = Effect.runSync(Scope.make()); + this.serverReady = Effect.runPromise( + Scope.provide(this.scope)( + RpcServer.makeNoSerialization(WsRpcGroup, this.makeServerOptions()), + ).pipe(Effect.provide(this.makeLayer())), + ) as Promise; + } + + async disconnect(): Promise { + if (this.scope) { + await Effect.runPromise(Scope.close(this.scope, Exit.void)).catch(() => undefined); + this.scope = null; + } + for (const pubsub of this.streamPubSubs.values()) { + Effect.runSync(PubSub.shutdown(pubsub)); + } + this.streamPubSubs.clear(); + this.serverReady = null; + this.client = null; + } + + private initializeStreamPubSubs(): void { + this.streamPubSubs = new Map( + Array.from(STREAM_METHODS, (method) => [method, Effect.runSync(PubSub.unbounded())]), + ); + } + + async onMessage(rawData: string): Promise { + const server = await this.serverReady; + if (!server) { + throw new Error("RPC test server is not connected"); + } + const messages = this.parser.decode(rawData); + for (const message of messages) { + await Effect.runPromise(server.write(0, message as never)); + } + } + + emitStreamValue(method: string, value: unknown): void { + const pubsub = this.streamPubSubs.get(method); + if (!pubsub) { + throw new Error(`No stream registered for ${method}`); + } + Effect.runSync(PubSub.publish(pubsub, value)); + } + + private makeLayer() { + const handlers: Record unknown> = {}; + for (const method of ALL_RPC_METHODS) { + handlers[method] = STREAM_METHODS.has(method) + ? (payload) => this.handleStream(method, payload) + : (payload) => this.handleUnary(method, payload); + } + return WsRpcGroup.toLayer(handlers as never); + } + + private makeServerOptions() { + return { + onFromServer: (response: unknown) => + Effect.sync(() => { + if (!this.client) { + return; + } + const encoded = this.parser.encode(response); + if (typeof encoded === "string") { + this.client.send(encoded); + } + }), + }; + } + + private handleUnary(method: string, payload: unknown) { + const request = normalizeRequest(method, payload); + this.requests.push(request); + return asEffect(this.resolveUnary(request)); + } + + private handleStream(method: string, payload: unknown) { + const request = normalizeRequest(method, payload); + this.requests.push(request); + const pubsub = this.streamPubSubs.get(method); + if (!pubsub) { + throw new Error(`No stream registered for ${method}`); + } + return Stream.fromIterable(this.getInitialStreamValues(request) ?? []).pipe( + Stream.concat(Stream.fromPubSub(pubsub)), + ); + } +} diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index a500ba56c1..178f4bcbab 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -21,5 +21,5 @@ } ] }, - "include": ["src", "vite.config.ts"] + "include": ["src", "vite.config.ts", "test"] } diff --git a/bun.lock b/bun.lock index 857d3a83c7..af243cf4eb 100644 --- a/bun.lock +++ b/bun.lock @@ -14,7 +14,7 @@ }, "apps/desktop": { "name": "@t3tools/desktop", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "effect": "catalog:", "electron": "40.6.0", @@ -27,7 +27,6 @@ "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:", - "wait-on": "^8.0.2", }, }, "apps/marketing": { @@ -43,19 +42,19 @@ }, "apps/server": { "name": "t3", - "version": "0.0.14", + "version": "0.0.15", "bin": { - "t3": "./dist/index.mjs", + "t3": "./dist/bin.mjs", }, "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", }, "devDependencies": { "@effect/language-service": "catalog:", @@ -65,7 +64,6 @@ "@t3tools/web": "workspace:*", "@types/bun": "catalog:", "@types/node": "catalog:", - "@types/ws": "^8.5.13", "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:", @@ -73,13 +71,14 @@ }, "apps/web": { "name": "@t3tools/web", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "@base-ui/react": "^1.2.0", "@dnd-kit/core": "^6.3.1", "@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", @@ -124,7 +123,7 @@ }, "packages/contracts": { "name": "@t3tools/contracts", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "effect": "catalog:", }, @@ -169,17 +168,22 @@ }, }, }, + "trustedDependencies": [ + "node-pty", + ], "overrides": { "vite": "^8.0.0", }, "catalog": { - "@effect/language-service": "0.75.1", - "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", - "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", - "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", + "@effect/atom-react": "4.0.0-beta.43", + "@effect/language-service": "0.84.2", + "@effect/platform-bun": "4.0.0-beta.43", + "@effect/platform-node": "4.0.0-beta.43", + "@effect/sql-sqlite-bun": "4.0.0-beta.43", + "@effect/vitest": "4.0.0-beta.43", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", - "effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", + "effect": "4.0.0-beta.43", "tsdown": "^0.20.3", "typescript": "^5.7.3", "vitest": "^4.0.0", @@ -265,15 +269,19 @@ "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], - "@effect/language-service": ["@effect/language-service@0.75.1", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-g9xD2tAQgRFpYC2YgpZq02VeSL5fBbFJ0B/g1o+14NuNmwtaYJc7SjiLWAA9eyhJHosNrn6h1Ye+Kx6j5mN0AA=="], + "@effect/atom-react": ["@effect/atom-react@4.0.0-beta.43", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "react": "^19.2.4", "scheduler": "*" } }, "sha512-xSrRbGXuo4d0g4ph66TQST1GNSjtQZrZj8V7OiAQFuzMYcZ0kwRIPUUFwOBtbWHK43/zNENdNWOnlXh/iYM1dw=="], - "@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }], + "@effect/language-service": ["@effect/language-service@0.84.2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25" } }], + "@effect/platform-bun": ["@effect/platform-bun@4.0.0-beta.43", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-nMZ9JsD6CzJNQ+5pDUFbPw7PSZdQdTQ092MbYrocVtvlf6qEFU/hji3ITvRIOX7eabyQ8AUyp55qFPQUeq+GIA=="], - "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25" } }], + "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.43", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43", "ioredis": "^5.7.0" } }, "sha512-Uq6E1rjaIpjHauzjwoB2HzAg3battYt2Boy8XO50GoHiWCXKE6WapYZ0/AnaBx5v5qg2sOfqpuiLsUf9ZgxOkA=="], - "@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25", "vitest": "^3.0.0 || ^4.0.0" } }], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.43", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-A9q0GEb61pYcQ06Dr6gXj1nKlDI3KHsar1sk3qb1ZY+kVSR64tBAylI8zGon23KY+NPtTUj/sEIToB7jc3Qt5w=="], + + "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.43", "", { "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-Ryb7x0rBjW5NHegbzvz9y2Yv4KpwZ1UiPk7/Rv+Mkux74Qkjdmotmrvy9P+M5A9TZyL2Av+GpaLTPJKsL0PG+Q=="], + + "@effect/vitest": ["@effect/vitest@4.0.0-beta.43", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-XN2LAwiUWPqbV2jrsYYRjrVydQ8MIgwr83MVImtUaOQco4vk43+8OHlXQMRN/u2HnGK29KT+O2yTMMBdk2Q6Sw=="], "@electron/get": ["@electron/get@2.0.3", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="], @@ -361,18 +369,6 @@ "@formkit/auto-animate": ["@formkit/auto-animate@0.9.0", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="], - "@hapi/address": ["@hapi/address@5.1.1", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="], - - "@hapi/formula": ["@hapi/formula@3.0.2", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="], - - "@hapi/hoek": ["@hapi/hoek@11.0.7", "", {}, "sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ=="], - - "@hapi/pinpoint": ["@hapi/pinpoint@2.0.1", "", {}, "sha512-EKQmr16tM8s16vTT3cA5L0kZZcTMU5DUOZTuvpnY738m+jyP3JIUj+Mm1xc1rsLkGBQ/gVnfKYPwOmPg1tUR4Q=="], - - "@hapi/tlds": ["@hapi/tlds@1.1.6", "", {}, "sha512-xdi7A/4NZokvV0ewovme3aUO5kQhW9pQ2YD1hRqZGhhSi5rBv4usHYidVocXSi9eihYsznZxLtAiEYYUL6VBGw=="], - - "@hapi/topo": ["@hapi/topo@6.0.2", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg=="], - "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="], @@ -861,10 +857,6 @@ "astro": ["astro@6.0.5", "", { "dependencies": { "@astrojs/compiler": "^3.0.0", "@astrojs/internal-helpers": "0.8.0", "@astrojs/markdown-remark": "7.0.0", "@astrojs/telemetry": "3.3.0", "@capsizecss/unpack": "^4.0.0", "@clack/prompts": "^1.0.1", "@oslojs/encoding": "^1.1.0", "@rollup/pluginutils": "^5.3.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^1.1.1", "devalue": "^5.6.3", "diff": "^8.0.3", "dlv": "^1.1.3", "dset": "^3.1.4", "es-module-lexer": "^2.0.0", "esbuild": "^0.27.3", "flattie": "^1.1.1", "fontace": "~0.4.1", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.2.0", "js-yaml": "^4.1.1", "magic-string": "^0.30.21", "magicast": "^0.5.2", "mrmime": "^2.0.1", "neotraverse": "^0.6.18", "obug": "^2.1.1", "p-limit": "^7.3.0", "p-queue": "^9.1.0", "package-manager-detector": "^1.6.0", "piccolore": "^0.1.3", "picomatch": "^4.0.3", "rehype": "^13.0.2", "semver": "^7.7.4", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "svgo": "^4.0.0", "tinyclip": "^0.1.6", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tsconfck": "^3.1.6", "ultrahtml": "^1.6.0", "unifont": "~0.7.4", "unist-util-visit": "^5.1.0", "unstorage": "^1.17.4", "vfile": "^6.0.3", "vite": "^7.3.1", "vitefu": "^1.1.2", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.3.6" }, "optionalDependencies": { "sharp": "^0.34.0" }, "bin": { "astro": "bin/astro.mjs" } }, "sha512-JnLCwaoCaRXIHuIB8yNztJrd7M3hXrHUMAoQmeXtEBKxRu/738REhaCZ1lapjrS9HlpHsWTu3JUXTERB/0PA7g=="], - "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], - - "axios": ["axios@1.13.6", "", { "dependencies": { "follow-redirects": "^1.15.11", "form-data": "^4.0.5", "proxy-from-env": "^1.1.0" } }, "sha512-ChTCHMouEe2kn713WHbQGcuYrr6fXTBiu460OTwWrWob16g1bXn4vtz07Ope7ewMozJAnEquLk5lWQWtBig9DQ=="], - "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], @@ -901,8 +893,6 @@ "cacheable-request": ["cacheable-request@7.0.4", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="], - "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], - "caniuse-lite": ["caniuse-lite@1.0.30001779", "", {}, "sha512-U5og2PN7V4DMgF50YPNtnZJGWVLFjjsN3zb6uMT5VGYIewieDj1upwfuVNXf4Kor+89c3iCRJnSzMD5LmTvsfA=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], @@ -937,8 +927,6 @@ "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], - "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], - "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], "commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], @@ -983,8 +971,6 @@ "defu": ["defu@6.1.4", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="], - "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], - "denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="], "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], @@ -1015,9 +1001,7 @@ "dts-resolver": ["dts-resolver@2.1.3", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="], - "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], - - "effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }], + "effect": ["effect@4.0.0-beta.43", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="], "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], @@ -1045,10 +1029,6 @@ "es-module-lexer": ["es-module-lexer@2.0.0", "", {}, "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw=="], - "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], - - "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], - "es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="], "esbuild": ["esbuild@0.27.4", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.4", "@esbuild/android-arm": "0.27.4", "@esbuild/android-arm64": "0.27.4", "@esbuild/android-x64": "0.27.4", "@esbuild/darwin-arm64": "0.27.4", "@esbuild/darwin-x64": "0.27.4", "@esbuild/freebsd-arm64": "0.27.4", "@esbuild/freebsd-x64": "0.27.4", "@esbuild/linux-arm": "0.27.4", "@esbuild/linux-arm64": "0.27.4", "@esbuild/linux-ia32": "0.27.4", "@esbuild/linux-loong64": "0.27.4", "@esbuild/linux-mips64el": "0.27.4", "@esbuild/linux-ppc64": "0.27.4", "@esbuild/linux-riscv64": "0.27.4", "@esbuild/linux-s390x": "0.27.4", "@esbuild/linux-x64": "0.27.4", "@esbuild/netbsd-arm64": "0.27.4", "@esbuild/netbsd-x64": "0.27.4", "@esbuild/openbsd-arm64": "0.27.4", "@esbuild/openbsd-x64": "0.27.4", "@esbuild/openharmony-arm64": "0.27.4", "@esbuild/sunos-x64": "0.27.4", "@esbuild/win32-arm64": "0.27.4", "@esbuild/win32-ia32": "0.27.4", "@esbuild/win32-x64": "0.27.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ=="], @@ -1087,28 +1067,18 @@ "flattie": ["flattie@1.1.1", "", {}, "sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ=="], - "follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="], - "fontace": ["fontace@0.4.1", "", { "dependencies": { "fontkitten": "^1.0.2" } }, "sha512-lDMvbAzSnHmbYMTEld5qdtvNH2/pWpICOqpean9IgC7vUbUJc3k+k5Dokp85CegamqQpFbXf0rAVkbzpyTA8aw=="], "fontkitten": ["fontkitten@1.0.3", "", { "dependencies": { "tiny-inflate": "^1.0.3" } }, "sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw=="], - "form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="], - "fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="], "fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], - "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], - "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], - "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], - - "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], - "get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="], "get-tsconfig": ["get-tsconfig@4.13.6", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="], @@ -1133,12 +1103,6 @@ "has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="], - "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], - - "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], - - "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], - "hast-util-from-html": ["hast-util-from-html@2.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.1.0", "hast-util-from-parse5": "^8.0.0", "parse5": "^7.0.0", "vfile": "^6.0.0", "vfile-message": "^4.0.0" } }, "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw=="], "hast-util-from-parse5": ["hast-util-from-parse5@8.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "hastscript": "^9.0.0", "property-information": "^7.0.0", "vfile": "^6.0.0", "vfile-location": "^5.0.0", "web-namespaces": "^2.0.0" } }, "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg=="], @@ -1219,8 +1183,6 @@ "jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="], - "joi": ["joi@18.0.2", "", { "dependencies": { "@hapi/address": "^5.1.1", "@hapi/formula": "^3.0.2", "@hapi/hoek": "^11.0.7", "@hapi/pinpoint": "^2.0.1", "@hapi/tlds": "^1.1.1", "@hapi/topo": "^6.0.2", "@standard-schema/spec": "^1.0.0" } }, "sha512-RuCOQMIt78LWnktPoeBL0GErkNaJPTBGcYuyaBvUOQSpcpcLfWrHPPihYdOGbV5pam9VTWbeoF7TsGiHugcjGA=="], - "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="], @@ -1275,8 +1237,6 @@ "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], - "lodash": ["lodash@4.17.23", "", {}, "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w=="], - "lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="], "lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="], @@ -1303,8 +1263,6 @@ "matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="], - "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], - "mdast-util-definitions": ["mdast-util-definitions@6.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-scTllyX6pnYNZH/AIp/0ePz6s4cZtARxImwoPJ7kS42n+MnVsI4XbnG6d4ibehRIldYMWM2LD7ImQblVhUejVQ=="], "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="], @@ -1397,14 +1355,8 @@ "mime": ["mime@4.1.0", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="], - "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], - - "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - "mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="], - "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], @@ -1513,8 +1465,6 @@ "property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="], - "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], - "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], "pure-rand": ["pure-rand@8.1.0", "", {}, "sha512-53B3MB8wetRdD6JZ4W/0gDKaOvKwuXrEmV1auQc0hASWge8rieKV4PCCVNVbJ+i24miiubb4c/B+dg8Ho0ikYw=="], @@ -1597,8 +1547,6 @@ "run-applescript": ["run-applescript@7.1.0", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="], - "rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="], - "sax": ["sax@1.5.0", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="], "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], @@ -1837,8 +1785,6 @@ "vscode-uri": ["vscode-uri@3.1.0", "", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="], - "wait-on": ["wait-on@8.0.5", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="], - "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], @@ -1905,14 +1851,6 @@ "@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], - "@effect/platform-node/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/platform-node-shared/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/sql-sqlite-bun/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - - "@effect/vitest/effect": ["effect@4.0.0-beta.33", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-ln9emWPd1SemokSdOV43r2CbH1j8GTe9qbPvttmh9/j2OR0WNmj7UpjbN34llQgF9QV4IdcN6QdV2w8G7B7RyQ=="], - "@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], "@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], diff --git a/docs/effect-fn-checklist.md b/docs/effect-fn-checklist.md new file mode 100644 index 0000000000..1addfdf4dd --- /dev/null +++ b/docs/effect-fn-checklist.md @@ -0,0 +1,198 @@ +# Effect.fn Refactor Checklist + +Generated from a repo scan for non-test wrapper-style candidates matching either `=> Effect.gen(function* ...)` or `return Effect.gen(function* ...)`. + +Refactor Method: + +```ts +// Old +function old () { + return Effect.gen(function* () { + ... + }); +} + +const old2 = () => Effect.gen(function* () { + ... +}); +``` + +```ts +// New +const new = Effect.fn('functionName')(function* () { + ... +}) +``` + +- Use `Effect.fn('name')(function* (input: Input): Effect.fn.Return {})` to annotate the return type of the function if needed. + +- The 2nd argument works as a pipe, and it gets the effect and input as arguments: + +```ts +Effect.fn("name")( + function* (input: Input): Effect.fn.Return {}, + (effect, input) => Effect.catch(effect, (reason) => Effect.logWarning("Err", { input, reason })), +); +``` + +## Summary + +- Total non-test candidates: `322` + +## Suggested Order + +- [ ] `apps/server/src/provider/Layers/ProviderService.ts` +- [x] `apps/server/src/provider/Layers/ClaudeAdapter.ts` +- [x] `apps/server/src/provider/Layers/CodexAdapter.ts` +- [x] `apps/server/src/git/Layers/GitCore.ts` +- [x] `apps/server/src/git/Layers/GitManager.ts` +- [x] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` +- [x] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` +- [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` +- [ ] `apps/server/src/provider/Layers/EventNdjsonLogger.ts` +- [ ] `Everything else` + +## Checklist + +### `apps/server/src/provider/Layers/ClaudeAdapter.ts` (`62`) + +- [x] [buildUserMessageEffect](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L554) +- [x] [makeClaudeAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L913) +- [x] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2414) +- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2887) +- [x] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2975) +- [x] [readThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2984) +- [x] [rollbackThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2990) +- [x] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L3039) +- [x] Internal helpers and callback wrappers in this file + +### `apps/server/src/git/Layers/GitCore.ts` (`58`) + +- [x] [makeGitCore](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L513) +- [x] [handleTraceLine](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L324) +- [x] [emitCompleteLines](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L455) +- [x] [commit](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1190) +- [x] [pushCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1223) +- [x] [pullCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1323) +- [x] [checkoutBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1727) +- [x] Service methods and callback wrappers in this file + +### `apps/server/src/git/Layers/GitManager.ts` (`28`) + +- [x] [configurePullRequestHeadUpstream](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L387) +- [x] [materializePullRequestHeadBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L428) +- [x] [findOpenPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L576) +- [x] [findLatestPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L602) +- [x] [runCommitStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L728) +- [x] [runPrStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L842) +- [x] [runFeatureBranchStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L1106) +- [x] Remaining helpers and nested callback wrappers in this file + +### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`) + +- [x] [runProjectorForEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161) +- [x] [applyProjectsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357) +- [x] [applyThreadsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415) +- [x] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250` +- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264` +- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305` +- [x] Remaining apply helpers in this file + +### `apps/server/src/provider/Layers/ProviderService.ts` (`24`) + +- [ ] [makeProviderService](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L134) +- [ ] [recoverSessionForThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L196) +- [ ] [resolveRoutableSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L255) +- [ ] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L284) +- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L347) +- [ ] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L393) +- [ ] [respondToRequest](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L411) +- [ ] [respondToUserInput](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L430) +- [ ] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L445) +- [ ] [listSessions](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L466) +- [ ] [rollbackConversation](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L516) +- [ ] [runStopAll](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L538) + +### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`) + +- [x] [finalizeAssistantMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680) +- [x] [upsertProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722) +- [x] [finalizeBufferedProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761) +- [x] [clearTurnStateForSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800) +- [x] [processRuntimeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908) +- [x] Nested callback wrappers in this file + +### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`) + +- [x] [makeCodexAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1317) +- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1399) +- [x] [writeNativeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1546) +- [x] [listener](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1555) +- [x] Remaining nested callback wrappers in this file + +### `apps/server/src/checkpointing/Layers/CheckpointStore.ts` (`10`) + +- [ ] [captureCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L89) +- [ ] [restoreCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L183) +- [ ] [diffCheckpoints](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L220) +- [ ] [deleteCheckpointRefs](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L252) +- [ ] Nested callback wrappers in this file + +### `apps/server/src/provider/Layers/EventNdjsonLogger.ts` (`9`) + +- [ ] [toLogMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L77) +- [ ] [makeThreadWriter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L102) +- [ ] [makeEventNdjsonLogger](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L174) +- [ ] [write](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L231) +- [ ] [close](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L247) +- [ ] Flush and writer-resolution callback wrappers in this file + +### `apps/server/scripts/cli.ts` (`8`) + +- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L125) +- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L170) +- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L221) +- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L239) + +### `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` (`7`) + +- [ ] [processEnvelope](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L64) +- [ ] [dispatch](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L218) +- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L162) +- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L200) + +### `apps/server/src/orchestration/projector.ts` (`5`) + +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L242) +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L336) +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L397) +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L446) +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L478) + +### Smaller clusters + +- [ ] [packages/shared/src/DrainableWorker.ts](/Users/julius/Development/Work/codething-mvp/packages/shared/src/DrainableWorker.ts) (`4`) +- [ ] [apps/server/src/wsServer/pushBus.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer/pushBus.ts) (`4`) +- [ ] [apps/server/src/wsServer.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer.ts) (`4`) +- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`) +- [ ] [apps/server/src/persistence/Layers/Sqlite.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Layers/Sqlite.ts) (`4`) +- [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`) +- [ ] [apps/server/src/main.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/main.ts) (`4`) +- [ ] [apps/server/src/keybindings.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/keybindings.ts) (`4`) +- [ ] [apps/server/src/git/Layers/CodexTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/CodexTextGeneration.ts) (`4`) +- [ ] [apps/server/src/serverLayers.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/serverLayers.ts) (`3`) +- [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`) +- [ ] [apps/server/src/telemetry/Identify.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Identify.ts) (`2`) +- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`) +- [ ] [apps/server/src/provider/Layers/CodexProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexProvider.ts) (`2`) +- [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`) +- [ ] [apps/server/src/persistence/NodeSqliteClient.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/NodeSqliteClient.ts) (`2`) +- [ ] [apps/server/src/persistence/Migrations.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Migrations.ts) (`2`) +- [ ] [apps/server/src/open.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/open.ts) (`2`) +- [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`) +- [ ] [apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts) (`2`) +- [ ] [apps/server/src/provider/makeManagedServerProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/makeManagedServerProvider.ts) (`1`) + +``` + +``` diff --git a/package.json b/package.json index 02e71cf097..a26a359c03 100644 --- a/package.json +++ b/package.json @@ -8,11 +8,13 @@ "scripts" ], "catalog": { - "effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", - "@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", - "@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", - "@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", - "@effect/language-service": "0.75.1", + "effect": "4.0.0-beta.43", + "@effect/atom-react": "4.0.0-beta.43", + "@effect/platform-bun": "4.0.0-beta.43", + "@effect/platform-node": "4.0.0-beta.43", + "@effect/sql-sqlite-bun": "4.0.0-beta.43", + "@effect/vitest": "4.0.0-beta.43", + "@effect/language-service": "0.84.2", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", "tsdown": "^0.20.3", @@ -30,6 +32,7 @@ "start": "turbo run start --filter=t3", "start:desktop": "turbo run start --filter=@t3tools/desktop", "start:marketing": "turbo run preview --filter=@t3tools/marketing", + "start:mock-update-server": "bun run scripts/mock-update-server.ts", "build": "turbo run build", "build:marketing": "turbo run build --filter=@t3tools/marketing", "build:desktop": "turbo run build --filter=@t3tools/desktop --filter=t3", @@ -69,5 +72,8 @@ "workerDirectory": [ "apps/web/public" ] - } + }, + "trustedDependencies": [ + "node-pty" + ] } diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 29d0c1398f..fe03c205a5 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/contracts", - "version": "0.0.14", + "version": "0.0.15", "private": true, "files": [ "dist" diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts index 0ebd4fe5ae..60ff5908c1 100644 --- a/packages/contracts/src/editor.ts +++ b/packages/contracts/src/editor.ts @@ -2,11 +2,18 @@ import { Schema } from "effect"; import { TrimmedNonEmptyString } from "./baseSchemas"; export const EDITORS = [ - { id: "cursor", label: "Cursor", command: "cursor" }, - { id: "vscode", label: "VS Code", command: "code" }, - { id: "zed", label: "Zed", command: "zed" }, - { id: "antigravity", label: "Antigravity", command: "agy" }, - { id: "file-manager", label: "File Manager", command: null }, + { id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true }, + { id: "vscode", label: "VS Code", command: "code", supportsGoto: true }, + { + id: "vscode-insiders", + label: "VS Code Insiders", + command: "code-insiders", + supportsGoto: true, + }, + { id: "vscodium", label: "VSCodium", command: "codium", supportsGoto: true }, + { id: "zed", label: "Zed", command: "zed", supportsGoto: false }, + { id: "antigravity", label: "Antigravity", command: "agy", supportsGoto: false }, + { id: "file-manager", label: "File Manager", command: null, supportsGoto: false }, ] as const; export const EditorId = Schema.Literals(EDITORS.map((e) => e.id)); @@ -17,3 +24,8 @@ export const OpenInEditorInput = Schema.Struct({ editor: EditorId, }); export type OpenInEditorInput = typeof OpenInEditorInput.Type; + +export class OpenError extends Schema.TaggedErrorClass()("OpenError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect), +}) {} diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index f8b65abf2c..65504fabc1 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -223,6 +223,60 @@ export const GitPullResult = Schema.Struct({ }); export type GitPullResult = typeof GitPullResult.Type; +// RPC / domain errors +export class GitCommandError extends Schema.TaggedErrorClass()("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}`; + } +} + +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}`; + } +} + +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}`; + } +} + +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}`; + } +} + +export const GitManagerServiceError = Schema.Union([ + GitManagerError, + GitCommandError, + GitHubCliError, + TextGenerationError, +]); +export type GitManagerServiceError = typeof GitManagerServiceError.Type; + const GitActionProgressBase = Schema.Struct({ actionId: TrimmedNonEmptyStringSchema, cwd: TrimmedNonEmptyStringSchema, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d6c1d6d75a..c08717ea03 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -5,7 +5,6 @@ export * from "./provider"; export * from "./providerRuntime"; export * from "./threadUsage"; export * from "./model"; -export * from "./ws"; export * from "./keybindings"; export * from "./server"; export * from "./settings"; @@ -16,3 +15,4 @@ export * from "./toolLifecycle"; export * from "./userInput"; export * from "./editor"; export * from "./project"; +export * from "./rpc"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 1d282ae721..3114f6f5be 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1,6 +1,5 @@ import type { GitCheckoutInput, - GitActionProgressEvent, GitCreateBranchInput, GitPreparePullRequestThreadInput, GitPreparePullRequestThreadResult, @@ -14,8 +13,6 @@ import type { GitPullResult, GitRemoveWorktreeInput, GitResolvePullRequestResult, - GitRunStackedActionInput, - GitRunStackedActionResult, GitStatusInput, GitStatusResult, } from "./git"; @@ -57,6 +54,7 @@ export interface ContextMenuItem { id: T; label: string; destructive?: boolean; + disabled?: boolean; } export type DesktopUpdateStatus = @@ -100,6 +98,11 @@ export interface DesktopUpdateActionResult { state: DesktopUpdateState; } +export interface DesktopUpdateCheckResult { + checked: boolean; + state: DesktopUpdateState; +} + export interface DesktopBridge { getWsUrl: () => string | null; pickFolder: () => Promise; @@ -112,6 +115,7 @@ export interface DesktopBridge { openExternal: (url: string) => Promise; onMenuAction: (listener: (action: string) => void) => () => void; getUpdateState: () => Promise; + checkForUpdate: () => Promise; downloadUpdate: () => Promise; installUpdate: () => Promise; onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void; @@ -123,12 +127,12 @@ export interface NativeApi { confirm: (message: string) => Promise; }; terminal: { - open: (input: TerminalOpenInput) => Promise; - write: (input: TerminalWriteInput) => Promise; - resize: (input: TerminalResizeInput) => Promise; - clear: (input: TerminalClearInput) => Promise; - restart: (input: TerminalRestartInput) => Promise; - close: (input: TerminalCloseInput) => Promise; + open: (input: typeof TerminalOpenInput.Encoded) => Promise; + write: (input: typeof TerminalWriteInput.Encoded) => Promise; + resize: (input: typeof TerminalResizeInput.Encoded) => Promise; + clear: (input: typeof TerminalClearInput.Encoded) => Promise; + restart: (input: typeof TerminalRestartInput.Encoded) => Promise; + close: (input: typeof TerminalCloseInput.Encoded) => Promise; onEvent: (callback: (event: TerminalEvent) => void) => () => void; }; projects: { @@ -154,8 +158,6 @@ export interface NativeApi { // Stacked action API pull: (input: GitPullInput) => Promise; status: (input: GitStatusInput) => Promise; - runStackedAction: (input: GitRunStackedActionInput) => Promise; - onActionProgress: (callback: (event: GitActionProgressEvent) => void) => () => void; }; contextMenu: { show: ( diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 1b99362c53..c3a7d9f00e 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -46,6 +46,12 @@ it.effect("parses keybinding rules", () => command: "chat.newLocal", }); assert.strictEqual(parsedLocal.command, "chat.newLocal"); + + const parsedThreadPrevious = yield* decode(KeybindingRule, { + key: "mod+shift+[", + command: "thread.previous", + }); + assert.strictEqual(parsedThreadPrevious.command, "thread.previous"); }), ); @@ -120,8 +126,19 @@ it.effect("parses resolved keybindings arrays", () => modKey: true, }, }, + { + command: "thread.jump.3", + shortcut: { + key: "3", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + }, ]); - assert.lengthOf(parsed, 1); + assert.lengthOf(parsed, 2); }), ); diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 48821b1824..b08fff8679 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -7,6 +7,26 @@ export const MAX_WHEN_EXPRESSION_DEPTH = 64; export const MAX_SCRIPT_ID_LENGTH = 24; export const MAX_KEYBINDINGS_COUNT = 256; +export const THREAD_JUMP_KEYBINDING_COMMANDS = [ + "thread.jump.1", + "thread.jump.2", + "thread.jump.3", + "thread.jump.4", + "thread.jump.5", + "thread.jump.6", + "thread.jump.7", + "thread.jump.8", + "thread.jump.9", +] as const; +export type ThreadJumpKeybindingCommand = (typeof THREAD_JUMP_KEYBINDING_COMMANDS)[number]; + +export const THREAD_KEYBINDING_COMMANDS = [ + "thread.previous", + "thread.next", + ...THREAD_JUMP_KEYBINDING_COMMANDS, +] as const; +export type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number]; + const STATIC_KEYBINDING_COMMANDS = [ "terminal.toggle", "terminal.split", @@ -16,6 +36,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "chat.new", "chat.newLocal", "editor.openFavorite", + ...THREAD_KEYBINDING_COMMANDS, ] as const; export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([ @@ -64,24 +85,27 @@ export const KeybindingShortcut = Schema.Struct({ }); export type KeybindingShortcut = typeof KeybindingShortcut.Type; -export const KeybindingWhenNode: Schema.Schema = Schema.Union([ +const KeybindingWhenNodeRef = Schema.suspend( + (): Schema.Codec => KeybindingWhenNode, +); +export const KeybindingWhenNode = Schema.Union([ Schema.Struct({ type: Schema.Literal("identifier"), name: Schema.NonEmptyString, }), Schema.Struct({ type: Schema.Literal("not"), - node: Schema.suspend((): Schema.Schema => KeybindingWhenNode), + node: KeybindingWhenNodeRef, }), Schema.Struct({ type: Schema.Literal("and"), - left: Schema.suspend((): Schema.Schema => KeybindingWhenNode), - right: Schema.suspend((): Schema.Schema => KeybindingWhenNode), + left: KeybindingWhenNodeRef, + right: KeybindingWhenNodeRef, }), Schema.Struct({ type: Schema.Literal("or"), - left: Schema.suspend((): Schema.Schema => KeybindingWhenNode), - right: Schema.suspend((): Schema.Schema => KeybindingWhenNode), + left: KeybindingWhenNodeRef, + right: KeybindingWhenNodeRef, }), ]); export type KeybindingWhenNode = @@ -101,3 +125,16 @@ export const ResolvedKeybindingsConfig = Schema.Array(ResolvedKeybindingRule).ch Schema.isMaxLength(MAX_KEYBINDINGS_COUNT), ); export type ResolvedKeybindingsConfig = typeof ResolvedKeybindingsConfig.Type; + +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}`; + } +} diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 68ca110473..e62a957e05 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -18,6 +18,7 @@ export const ClaudeModelOptions = Schema.Struct({ thinking: Schema.optional(Schema.Boolean), effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)), fastMode: Schema.optional(Schema.Boolean), + contextWindow: Schema.optional(Schema.String), }); export type ClaudeModelOptions = typeof ClaudeModelOptions.Type; @@ -34,17 +35,23 @@ export const EffortOption = Schema.Struct({ }); export type EffortOption = typeof EffortOption.Type; +export const ContextWindowOption = Schema.Struct({ + value: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + isDefault: Schema.optional(Schema.Boolean), +}); +export type ContextWindowOption = typeof ContextWindowOption.Type; + export const ModelCapabilities = Schema.Struct({ reasoningEffortLevels: Schema.Array(EffortOption), supportsFastMode: Schema.Boolean, supportsThinkingToggle: Schema.Boolean, + contextWindowOptions: Schema.Array(ContextWindowOption), promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString), }); export type ModelCapabilities = typeof ModelCapabilities.Type; -export type ModelSlug = string & {}; - -export const DEFAULT_MODEL_BY_PROVIDER: Record = { +export const DEFAULT_MODEL_BY_PROVIDER: Record = { codex: "gpt-5.4", claudeAgent: "claude-sonnet-4-6", }; @@ -57,7 +64,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record> = { +export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record> = { codex: { "5.4": "gpt-5.4", "5.3": "gpt-5.3-codex", diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 19cef5a392..06bb35038d 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -5,6 +5,8 @@ import { Effect, Schema } from "effect"; import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, + OrchestrationCommand, + OrchestrationEvent, OrchestrationGetTurnDiffInput, OrchestrationLatestTurn, ProjectCreatedPayload, @@ -32,6 +34,8 @@ const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLa const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan); const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession); const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload); +const decodeOrchestrationCommand = Schema.decodeUnknownEffect(OrchestrationCommand); +const decodeOrchestrationEvent = Schema.decodeUnknownEffect(OrchestrationEvent); const decodeThreadMetaUpdatedPayload = Schema.decodeUnknownEffect(ThreadMetaUpdatedPayload); it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () => @@ -227,6 +231,66 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () => }), ); +it.effect("decodes thread archive and unarchive commands", () => + Effect.gen(function* () { + const archive = yield* decodeOrchestrationCommand({ + type: "thread.archive", + commandId: "cmd-archive-1", + threadId: "thread-1", + }); + const unarchive = yield* decodeOrchestrationCommand({ + type: "thread.unarchive", + commandId: "cmd-unarchive-1", + threadId: "thread-1", + }); + + assert.strictEqual(archive.type, "thread.archive"); + assert.strictEqual(unarchive.type, "thread.unarchive"); + }), +); + +it.effect("decodes thread archived and unarchived events", () => + Effect.gen(function* () { + const archived = yield* decodeOrchestrationEvent({ + sequence: 1, + eventId: "event-archive-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.archived", + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: "cmd-archive-1", + causationEventId: null, + correlationId: "cmd-archive-1", + metadata: {}, + payload: { + threadId: "thread-1", + archivedAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }); + const unarchived = yield* decodeOrchestrationEvent({ + sequence: 2, + eventId: "event-unarchive-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.unarchived", + occurredAt: "2026-01-02T00:00:00.000Z", + commandId: "cmd-unarchive-1", + causationEventId: null, + correlationId: "cmd-unarchive-1", + metadata: {}, + payload: { + threadId: "thread-1", + updatedAt: "2026-01-02T00:00:00.000Z", + }, + }); + + assert.strictEqual(archived.type, "thread.archived"); + assert.strictEqual(archived.payload.archivedAt, "2026-01-01T00:00:00.000Z"); + assert.strictEqual(unarchived.type, "thread.unarchived"); + }), +); + it.effect("accepts provider-scoped model options in thread.turn.start", () => Effect.gen(function* () { const parsed = yield* decodeThreadTurnStartCommand({ @@ -255,6 +319,25 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () => }), ); +it.effect("accepts a title seed in thread.turn.start", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadTurnStartCommand({ + type: "thread.turn.start", + commandId: "cmd-turn-title-seed", + threadId: "thread-1", + message: { + messageId: "msg-title-seed", + role: "user", + text: "hello", + attachments: [], + }, + titleSeed: "Investigate reconnect failures", + createdAt: "2026-01-01T00:00:00.000Z", + }); + assert.strictEqual(parsed.titleSeed, "Investigate reconnect failures"); + }), +); + it.effect("accepts a source proposed plan reference in thread.turn.start", () => Effect.gen(function* () { const parsed = yield* decodeThreadTurnStartCommand({ @@ -314,6 +397,18 @@ it.effect("decodes thread.turn-start-requested source proposed plan metadata whe }), ); +it.effect("decodes thread.turn-start-requested title seed when present", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadTurnStartRequestedPayload({ + threadId: "thread-2", + messageId: "msg-2", + titleSeed: "Investigate reconnect failures", + createdAt: "2026-01-01T00:00:00.000Z", + }); + assert.strictEqual(parsed.titleSeed, "Investigate reconnect failures"); + }), +); + it.effect("decodes latest turn source proposed plan metadata when present", () => Effect.gen(function* () { const parsed = yield* decodeOrchestrationLatestTurn({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 166bac0b7b..4120f852ce 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -27,10 +27,6 @@ export const ORCHESTRATION_WS_METHODS = { replayEvents: "orchestration.replayEvents", } as const; -export const ORCHESTRATION_WS_CHANNELS = { - domainEvent: "orchestration.domainEvent", -} as const; - export const ProviderKind = Schema.Literals(["codex", "claudeAgent"]); export type ProviderKind = typeof ProviderKind.Type; export const ProviderApprovalPolicy = Schema.Literals([ @@ -46,6 +42,7 @@ export const ProviderSandboxMode = Schema.Literals([ "danger-full-access", ]); export type ProviderSandboxMode = typeof ProviderSandboxMode.Type; + export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex"; export const CodexModelSelection = Schema.Struct({ @@ -465,6 +462,7 @@ export const OrchestrationThread = Schema.Struct({ latestTurn: Schema.NullOr(OrchestrationLatestTurn), createdAt: IsoDateTime, updatedAt: IsoDateTime, + archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)), deletedAt: Schema.NullOr(IsoDateTime), messages: Schema.Array(OrchestrationMessage), proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(Schema.withDecodingDefault(() => [])), @@ -530,6 +528,18 @@ const ThreadDeleteCommand = Schema.Struct({ threadId: ThreadId, }); +const ThreadArchiveCommand = Schema.Struct({ + type: Schema.Literal("thread.archive"), + commandId: CommandId, + threadId: ThreadId, +}); + +const ThreadUnarchiveCommand = Schema.Struct({ + type: Schema.Literal("thread.unarchive"), + commandId: CommandId, + threadId: ThreadId, +}); + const ThreadMetaUpdateCommand = Schema.Struct({ type: Schema.Literal("thread.meta.update"), commandId: CommandId, @@ -567,6 +577,7 @@ export const ThreadTurnStartCommand = Schema.Struct({ attachments: Schema.Array(ChatAttachment), }), modelSelection: Schema.optional(ModelSelection), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)), interactionMode: ProviderInteractionMode.pipe( Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE), @@ -586,6 +597,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({ attachments: Schema.Array(UploadChatAttachment), }), modelSelection: Schema.optional(ModelSelection), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, sourceProposedPlan: Schema.optional(SourceProposedPlanReference), @@ -639,6 +651,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([ ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, + ThreadArchiveCommand, + ThreadUnarchiveCommand, ThreadMetaUpdateCommand, ThreadRuntimeModeSetCommand, ThreadInteractionModeSetCommand, @@ -658,6 +672,8 @@ export const ClientOrchestrationCommand = Schema.Union([ ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, + ThreadArchiveCommand, + ThreadUnarchiveCommand, ThreadMetaUpdateCommand, ThreadRuntimeModeSetCommand, ThreadInteractionModeSetCommand, @@ -758,6 +774,8 @@ export const OrchestrationEventType = Schema.Literals([ "project.deleted", "thread.created", "thread.deleted", + "thread.archived", + "thread.unarchived", "thread.meta-updated", "thread.runtime-mode-set", "thread.interaction-mode-set", @@ -824,6 +842,17 @@ export const ThreadDeletedPayload = Schema.Struct({ deletedAt: IsoDateTime, }); +export const ThreadArchivedPayload = Schema.Struct({ + threadId: ThreadId, + archivedAt: IsoDateTime, + updatedAt: IsoDateTime, +}); + +export const ThreadUnarchivedPayload = Schema.Struct({ + threadId: ThreadId, + updatedAt: IsoDateTime, +}); + export const ThreadMetaUpdatedPayload = Schema.Struct({ threadId: ThreadId, title: Schema.optional(TrimmedNonEmptyString), @@ -863,7 +892,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ threadId: ThreadId, messageId: MessageId, modelSelection: Schema.optional(ModelSelection), - assistantDeliveryMode: Schema.optional(AssistantDeliveryMode), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)), interactionMode: ProviderInteractionMode.pipe( Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE), @@ -981,6 +1010,16 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.deleted"), payload: ThreadDeletedPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.archived"), + payload: ThreadArchivedPayload, + }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.unarchived"), + payload: ThreadUnarchivedPayload, + }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.meta-updated"), @@ -1176,3 +1215,43 @@ export const OrchestrationRpcSchemas = { output: OrchestrationReplayEventsResult, }, } as const; + +export class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass()( + "OrchestrationGetSnapshotError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} + +export class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass()( + "OrchestrationDispatchCommandError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} + +export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass()( + "OrchestrationGetTurnDiffError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} + +export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass()( + "OrchestrationGetFullThreadDiffError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} + +export class OrchestrationReplayEventsError extends Schema.TaggedErrorClass()( + "OrchestrationReplayEventsError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 0903253301..2851120d1d 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -26,6 +26,14 @@ export const ProjectSearchEntriesResult = Schema.Struct({ }); export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type; +export class ProjectSearchEntriesError extends Schema.TaggedErrorClass()( + "ProjectSearchEntriesError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} + export const ProjectWriteFileInput = Schema.Struct({ cwd: TrimmedNonEmptyString, relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)), @@ -37,3 +45,11 @@ export const ProjectWriteFileResult = Schema.Struct({ relativePath: TrimmedNonEmptyString, }); export type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type; + +export class ProjectWriteFileError extends Schema.TaggedErrorClass()( + "ProjectWriteFileError", + { + message: TrimmedNonEmptyString, + cause: Schema.optional(Schema.Defect), + }, +) {} diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts new file mode 100644 index 0000000000..34968e66ec --- /dev/null +++ b/packages/contracts/src/rpc.ts @@ -0,0 +1,359 @@ +import { Schema } from "effect"; +import * as Rpc from "effect/unstable/rpc/Rpc"; +import * as RpcGroup from "effect/unstable/rpc/RpcGroup"; + +import { OpenError, OpenInEditorInput } from "./editor"; +import { + GitActionProgressEvent, + GitCheckoutInput, + GitCommandError, + GitCreateBranchInput, + GitCreateWorktreeInput, + GitCreateWorktreeResult, + GitInitInput, + GitListBranchesInput, + GitListBranchesResult, + GitManagerServiceError, + GitPreparePullRequestThreadInput, + GitPreparePullRequestThreadResult, + GitPullInput, + GitPullRequestRefInput, + GitPullResult, + GitRemoveWorktreeInput, + GitResolvePullRequestResult, + GitRunStackedActionInput, + GitStatusInput, + GitStatusResult, +} from "./git"; +import { KeybindingsConfigError } from "./keybindings"; +import { + ClientOrchestrationCommand, + OrchestrationEvent, + ORCHESTRATION_WS_METHODS, + OrchestrationDispatchCommandError, + OrchestrationGetFullThreadDiffError, + OrchestrationGetFullThreadDiffInput, + OrchestrationGetSnapshotError, + OrchestrationGetSnapshotInput, + OrchestrationGetTurnDiffError, + OrchestrationGetTurnDiffInput, + OrchestrationReplayEventsError, + OrchestrationReplayEventsInput, + OrchestrationRpcSchemas, +} from "./orchestration"; +import { + ProjectSearchEntriesError, + ProjectSearchEntriesInput, + ProjectSearchEntriesResult, + ProjectWriteFileError, + ProjectWriteFileInput, + ProjectWriteFileResult, +} from "./project"; +import { + TerminalClearInput, + TerminalCloseInput, + TerminalError, + TerminalEvent, + TerminalOpenInput, + TerminalResizeInput, + TerminalRestartInput, + TerminalSessionSnapshot, + TerminalWriteInput, +} from "./terminal"; +import { + ServerConfigStreamEvent, + ServerConfig, + ServerLifecycleStreamEvent, + ServerProviderUpdatedPayload, + ServerUpsertKeybindingInput, + ServerUpsertKeybindingResult, +} from "./server"; +import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings"; + +export const WS_METHODS = { + // Project registry methods + projectsList: "projects.list", + projectsAdd: "projects.add", + projectsRemove: "projects.remove", + projectsSearchEntries: "projects.searchEntries", + projectsWriteFile: "projects.writeFile", + + // Shell methods + shellOpenInEditor: "shell.openInEditor", + + // Git methods + gitPull: "git.pull", + gitStatus: "git.status", + gitRunStackedAction: "git.runStackedAction", + gitListBranches: "git.listBranches", + gitCreateWorktree: "git.createWorktree", + gitRemoveWorktree: "git.removeWorktree", + gitCreateBranch: "git.createBranch", + gitCheckout: "git.checkout", + gitInit: "git.init", + gitResolvePullRequest: "git.resolvePullRequest", + gitPreparePullRequestThread: "git.preparePullRequestThread", + + // Terminal methods + terminalOpen: "terminal.open", + terminalWrite: "terminal.write", + terminalResize: "terminal.resize", + terminalClear: "terminal.clear", + terminalRestart: "terminal.restart", + terminalClose: "terminal.close", + + // Server meta + serverGetConfig: "server.getConfig", + serverRefreshProviders: "server.refreshProviders", + serverUpsertKeybinding: "server.upsertKeybinding", + serverGetSettings: "server.getSettings", + serverUpdateSettings: "server.updateSettings", + + // Streaming subscriptions + subscribeOrchestrationDomainEvents: "subscribeOrchestrationDomainEvents", + subscribeTerminalEvents: "subscribeTerminalEvents", + subscribeServerConfig: "subscribeServerConfig", + subscribeServerLifecycle: "subscribeServerLifecycle", +} as const; + +export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, { + payload: ServerUpsertKeybindingInput, + success: ServerUpsertKeybindingResult, + error: KeybindingsConfigError, +}); + +export const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, { + payload: Schema.Struct({}), + success: ServerConfig, + error: Schema.Union([KeybindingsConfigError, ServerSettingsError]), +}); + +export const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, { + payload: Schema.Struct({}), + success: ServerProviderUpdatedPayload, +}); + +export const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, { + payload: Schema.Struct({}), + success: ServerSettings, + error: ServerSettingsError, +}); + +export const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, { + payload: Schema.Struct({ patch: ServerSettingsPatch }), + success: ServerSettings, + error: ServerSettingsError, +}); + +export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, { + payload: ProjectSearchEntriesInput, + success: ProjectSearchEntriesResult, + error: ProjectSearchEntriesError, +}); + +export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, { + payload: ProjectWriteFileInput, + success: ProjectWriteFileResult, + error: ProjectWriteFileError, +}); + +export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, { + payload: OpenInEditorInput, + error: OpenError, +}); + +export const WsGitStatusRpc = Rpc.make(WS_METHODS.gitStatus, { + payload: GitStatusInput, + success: GitStatusResult, + error: GitManagerServiceError, +}); + +export const WsGitPullRpc = Rpc.make(WS_METHODS.gitPull, { + payload: GitPullInput, + success: GitPullResult, + error: GitCommandError, +}); + +export const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, { + payload: GitRunStackedActionInput, + success: GitActionProgressEvent, + error: GitManagerServiceError, + stream: true, +}); + +export const WsGitResolvePullRequestRpc = Rpc.make(WS_METHODS.gitResolvePullRequest, { + payload: GitPullRequestRefInput, + success: GitResolvePullRequestResult, + error: GitManagerServiceError, +}); + +export const WsGitPreparePullRequestThreadRpc = Rpc.make(WS_METHODS.gitPreparePullRequestThread, { + payload: GitPreparePullRequestThreadInput, + success: GitPreparePullRequestThreadResult, + error: GitManagerServiceError, +}); + +export const WsGitListBranchesRpc = Rpc.make(WS_METHODS.gitListBranches, { + payload: GitListBranchesInput, + success: GitListBranchesResult, + error: GitCommandError, +}); + +export const WsGitCreateWorktreeRpc = Rpc.make(WS_METHODS.gitCreateWorktree, { + payload: GitCreateWorktreeInput, + success: GitCreateWorktreeResult, + error: GitCommandError, +}); + +export const WsGitRemoveWorktreeRpc = Rpc.make(WS_METHODS.gitRemoveWorktree, { + payload: GitRemoveWorktreeInput, + error: GitCommandError, +}); + +export const WsGitCreateBranchRpc = Rpc.make(WS_METHODS.gitCreateBranch, { + payload: GitCreateBranchInput, + error: GitCommandError, +}); + +export const WsGitCheckoutRpc = Rpc.make(WS_METHODS.gitCheckout, { + payload: GitCheckoutInput, + error: GitCommandError, +}); + +export const WsGitInitRpc = Rpc.make(WS_METHODS.gitInit, { + payload: GitInitInput, + error: GitCommandError, +}); + +export const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, { + payload: TerminalOpenInput, + success: TerminalSessionSnapshot, + error: TerminalError, +}); + +export const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, { + payload: TerminalWriteInput, + error: TerminalError, +}); + +export const WsTerminalResizeRpc = Rpc.make(WS_METHODS.terminalResize, { + payload: TerminalResizeInput, + error: TerminalError, +}); + +export const WsTerminalClearRpc = Rpc.make(WS_METHODS.terminalClear, { + payload: TerminalClearInput, + error: TerminalError, +}); + +export const WsTerminalRestartRpc = Rpc.make(WS_METHODS.terminalRestart, { + payload: TerminalRestartInput, + success: TerminalSessionSnapshot, + error: TerminalError, +}); + +export const WsTerminalCloseRpc = Rpc.make(WS_METHODS.terminalClose, { + payload: TerminalCloseInput, + error: TerminalError, +}); + +export const WsOrchestrationGetSnapshotRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getSnapshot, { + payload: OrchestrationGetSnapshotInput, + success: OrchestrationRpcSchemas.getSnapshot.output, + error: OrchestrationGetSnapshotError, +}); + +export const WsOrchestrationDispatchCommandRpc = Rpc.make( + ORCHESTRATION_WS_METHODS.dispatchCommand, + { + payload: ClientOrchestrationCommand, + success: OrchestrationRpcSchemas.dispatchCommand.output, + error: OrchestrationDispatchCommandError, + }, +); + +export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, { + payload: OrchestrationGetTurnDiffInput, + success: OrchestrationRpcSchemas.getTurnDiff.output, + error: OrchestrationGetTurnDiffError, +}); + +export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make( + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + { + payload: OrchestrationGetFullThreadDiffInput, + success: OrchestrationRpcSchemas.getFullThreadDiff.output, + error: OrchestrationGetFullThreadDiffError, + }, +); + +export const WsOrchestrationReplayEventsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.replayEvents, { + payload: OrchestrationReplayEventsInput, + success: OrchestrationRpcSchemas.replayEvents.output, + error: OrchestrationReplayEventsError, +}); + +export const WsSubscribeOrchestrationDomainEventsRpc = Rpc.make( + WS_METHODS.subscribeOrchestrationDomainEvents, + { + payload: Schema.Struct({}), + success: OrchestrationEvent, + stream: true, + }, +); + +export const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, { + payload: Schema.Struct({}), + success: TerminalEvent, + stream: true, +}); + +export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, { + payload: Schema.Struct({}), + success: ServerConfigStreamEvent, + error: Schema.Union([KeybindingsConfigError, ServerSettingsError]), + stream: true, +}); + +export const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecycle, { + payload: Schema.Struct({}), + success: ServerLifecycleStreamEvent, + stream: true, +}); + +export const WsRpcGroup = RpcGroup.make( + WsServerGetConfigRpc, + WsServerRefreshProvidersRpc, + WsServerUpsertKeybindingRpc, + WsServerGetSettingsRpc, + WsServerUpdateSettingsRpc, + WsProjectsSearchEntriesRpc, + WsProjectsWriteFileRpc, + WsShellOpenInEditorRpc, + WsGitStatusRpc, + WsGitPullRpc, + WsGitRunStackedActionRpc, + WsGitResolvePullRequestRpc, + WsGitPreparePullRequestThreadRpc, + WsGitListBranchesRpc, + WsGitCreateWorktreeRpc, + WsGitRemoveWorktreeRpc, + WsGitCreateBranchRpc, + WsGitCheckoutRpc, + WsGitInitRpc, + WsTerminalOpenRpc, + WsTerminalWriteRpc, + WsTerminalResizeRpc, + WsTerminalClearRpc, + WsTerminalRestartRpc, + WsTerminalCloseRpc, + WsSubscribeOrchestrationDomainEventsRpc, + WsSubscribeTerminalEventsRpc, + WsSubscribeServerConfigRpc, + WsSubscribeServerLifecycleRpc, + WsOrchestrationGetSnapshotRpc, + WsOrchestrationDispatchCommandRpc, + WsOrchestrationGetTurnDiffRpc, + WsOrchestrationGetFullThreadDiffRpc, + WsOrchestrationReplayEventsRpc, +); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 78d0879cd2..d4038deb3a 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -1,5 +1,11 @@ import { Schema } from "effect"; -import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas"; +import { + IsoDateTime, + NonNegativeInt, + ProjectId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas"; import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings"; import { EditorId } from "./editor"; import { ModelCapabilities } from "./model"; @@ -35,6 +41,13 @@ export const ServerProviderAuthStatus = Schema.Literals([ ]); export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type; +export const ServerProviderAuth = Schema.Struct({ + status: ServerProviderAuthStatus, + type: Schema.optional(TrimmedNonEmptyString), + label: Schema.optional(TrimmedNonEmptyString), +}); +export type ServerProviderAuth = typeof ServerProviderAuth.Type; + export const ServerProviderModel = Schema.Struct({ slug: TrimmedNonEmptyString, name: TrimmedNonEmptyString, @@ -49,14 +62,15 @@ export const ServerProvider = Schema.Struct({ installed: Schema.Boolean, version: Schema.NullOr(TrimmedNonEmptyString), status: ServerProviderState, - authStatus: ServerProviderAuthStatus, + auth: ServerProviderAuth, checkedAt: IsoDateTime, message: Schema.optional(TrimmedNonEmptyString), models: Schema.Array(ServerProviderModel), }); export type ServerProvider = typeof ServerProvider.Type; -const ServerProviders = Schema.Array(ServerProvider); +export const ServerProviders = Schema.Array(ServerProvider); +export type ServerProviders = typeof ServerProviders.Type; export const ServerConfig = Schema.Struct({ cwd: TrimmedNonEmptyString, @@ -80,10 +94,101 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T export const ServerConfigUpdatedPayload = Schema.Struct({ issues: ServerConfigIssues, + providers: ServerProviders, settings: Schema.optional(ServerSettings), }); export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type; +export const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({ + issues: ServerConfigIssues, +}); +export type ServerConfigKeybindingsUpdatedPayload = + typeof ServerConfigKeybindingsUpdatedPayload.Type; + +export const ServerConfigProviderStatusesPayload = Schema.Struct({ + providers: ServerProviders, +}); +export type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type; + +export const ServerConfigSettingsUpdatedPayload = Schema.Struct({ + settings: ServerSettings, +}); +export type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type; + +export const ServerConfigStreamSnapshotEvent = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("snapshot"), + config: ServerConfig, +}); +export type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type; + +export const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("keybindingsUpdated"), + payload: ServerConfigKeybindingsUpdatedPayload, +}); +export type ServerConfigStreamKeybindingsUpdatedEvent = + typeof ServerConfigStreamKeybindingsUpdatedEvent.Type; + +export const ServerConfigStreamProviderStatusesEvent = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("providerStatuses"), + payload: ServerConfigProviderStatusesPayload, +}); +export type ServerConfigStreamProviderStatusesEvent = + typeof ServerConfigStreamProviderStatusesEvent.Type; + +export const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("settingsUpdated"), + payload: ServerConfigSettingsUpdatedPayload, +}); +export type ServerConfigStreamSettingsUpdatedEvent = + typeof ServerConfigStreamSettingsUpdatedEvent.Type; + +export const ServerConfigStreamEvent = Schema.Union([ + ServerConfigStreamSnapshotEvent, + ServerConfigStreamKeybindingsUpdatedEvent, + ServerConfigStreamProviderStatusesEvent, + ServerConfigStreamSettingsUpdatedEvent, +]); +export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type; + +export const ServerLifecycleReadyPayload = Schema.Struct({ + at: IsoDateTime, +}); +export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type; + +export const ServerLifecycleWelcomePayload = Schema.Struct({ + cwd: TrimmedNonEmptyString, + projectName: TrimmedNonEmptyString, + bootstrapProjectId: Schema.optional(ProjectId), + bootstrapThreadId: Schema.optional(ThreadId), +}); +export type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type; + +export const ServerLifecycleStreamWelcomeEvent = Schema.Struct({ + version: Schema.Literal(1), + sequence: NonNegativeInt, + type: Schema.Literal("welcome"), + payload: ServerLifecycleWelcomePayload, +}); +export type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type; + +export const ServerLifecycleStreamReadyEvent = Schema.Struct({ + version: Schema.Literal(1), + sequence: NonNegativeInt, + type: Schema.Literal("ready"), + payload: ServerLifecycleReadyPayload, +}); +export type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type; + +export const ServerLifecycleStreamEvent = Schema.Union([ + ServerLifecycleStreamWelcomeEvent, + ServerLifecycleStreamReadyEvent, +]); +export type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type; + export const ServerProviderUpdatedPayload = Schema.Struct({ providers: ServerProviders, }); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 8ce01f630c..c28b566daa 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -24,6 +24,7 @@ export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type; export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at"; export const ClientSettingsSchema = Schema.Struct({ + confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)), diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)), sidebarProjectSortOrder: SidebarProjectSortOrder.pipe( @@ -92,6 +93,19 @@ export type ServerSettings = typeof ServerSettings.Type; export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({}); +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}`; + } +} + // ── Unified type ───────────────────────────────────────────────────── export type UnifiedSettings = ServerSettings & ClientSettings; @@ -111,6 +125,7 @@ const ClaudeModelOptionsPatch = Schema.Struct({ thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking), effort: Schema.optionalKey(ClaudeModelOptions.fields.effort), fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode), + contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow), }); const ModelSelectionPatch = Schema.Union([ diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index b0493d95c2..4344706bc2 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe( export const TerminalThreadInput = Schema.Struct({ threadId: TrimmedNonEmptyStringSchema, }); -export type TerminalThreadInput = Schema.Codec.Encoded; +export type TerminalThreadInput = typeof TerminalThreadInput.Type; const TerminalSessionInput = Schema.Struct({ ...TerminalThreadInput.fields, @@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({ terminalId: Schema.optional(TerminalIdSchema), deleteHistory: Schema.optional(Schema.Boolean), }); -export type TerminalCloseInput = Schema.Codec.Encoded; +export type TerminalCloseInput = typeof TerminalCloseInput.Type; export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]); export type TerminalSessionStatus = typeof TerminalSessionStatus.Type; @@ -149,3 +149,74 @@ export const TerminalEvent = Schema.Union([ TerminalActivityEvent, ]); export type TerminalEvent = typeof TerminalEvent.Type; + +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([ + TerminalCwdError, + TerminalHistoryError, + TerminalSessionLookupError, + TerminalNotRunningError, +]); +export type TerminalError = typeof TerminalError.Type; diff --git a/packages/contracts/src/ws.test.ts b/packages/contracts/src/ws.test.ts deleted file mode 100644 index 0d8d4dbec2..0000000000 --- a/packages/contracts/src/ws.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { assert, it } from "@effect/vitest"; -import { Effect, Schema } from "effect"; - -import { ORCHESTRATION_WS_CHANNELS, ORCHESTRATION_WS_METHODS } from "./orchestration"; -import { WebSocketRequest, WsResponse, WS_CHANNELS, WS_METHODS } from "./ws"; - -const decodeWebSocketRequest = Schema.decodeUnknownEffect(WebSocketRequest); -const decodeWsResponse = Schema.decodeUnknownEffect(WsResponse); - -it.effect("accepts getTurnDiff requests when fromTurnCount <= toTurnCount", () => - Effect.gen(function* () { - const parsed = yield* decodeWebSocketRequest({ - id: "req-1", - body: { - _tag: ORCHESTRATION_WS_METHODS.getTurnDiff, - threadId: "thread-1", - fromTurnCount: 1, - toTurnCount: 2, - }, - }); - assert.strictEqual(parsed.body._tag, ORCHESTRATION_WS_METHODS.getTurnDiff); - }), -); - -it.effect("rejects getTurnDiff requests when fromTurnCount > toTurnCount", () => - Effect.gen(function* () { - const result = yield* Effect.exit( - decodeWebSocketRequest({ - id: "req-1", - body: { - _tag: ORCHESTRATION_WS_METHODS.getTurnDiff, - threadId: "thread-1", - fromTurnCount: 3, - toTurnCount: 2, - }, - }), - ); - assert.strictEqual(result._tag, "Failure"); - }), -); - -it.effect("trims websocket request id and nested orchestration ids", () => - Effect.gen(function* () { - const parsed = yield* decodeWebSocketRequest({ - id: " req-1 ", - body: { - _tag: ORCHESTRATION_WS_METHODS.getTurnDiff, - threadId: " thread-1 ", - fromTurnCount: 0, - toTurnCount: 0, - }, - }); - assert.strictEqual(parsed.id, "req-1"); - assert.strictEqual(parsed.body._tag, ORCHESTRATION_WS_METHODS.getTurnDiff); - if (parsed.body._tag === ORCHESTRATION_WS_METHODS.getTurnDiff) { - assert.strictEqual(parsed.body.threadId, "thread-1"); - } - }), -); - -it.effect("accepts git.preparePullRequestThread requests", () => - Effect.gen(function* () { - const parsed = yield* decodeWebSocketRequest({ - id: "req-pr-1", - body: { - _tag: WS_METHODS.gitPreparePullRequestThread, - cwd: "/repo", - reference: "#42", - mode: "worktree", - }, - }); - assert.strictEqual(parsed.body._tag, WS_METHODS.gitPreparePullRequestThread); - }), -); - -it.effect("accepts typed websocket push envelopes with sequence", () => - Effect.gen(function* () { - const parsed = yield* decodeWsResponse({ - type: "push", - sequence: 1, - channel: WS_CHANNELS.serverWelcome, - data: { - cwd: "/tmp/workspace", - projectName: "workspace", - }, - }); - - if (!("type" in parsed) || parsed.type !== "push") { - assert.fail("expected websocket response to decode as a push envelope"); - } - - assert.strictEqual(parsed.type, "push"); - assert.strictEqual(parsed.sequence, 1); - assert.strictEqual(parsed.channel, WS_CHANNELS.serverWelcome); - }), -); - -it.effect("accepts git.actionProgress push envelopes", () => - Effect.gen(function* () { - const parsed = yield* decodeWsResponse({ - type: "push", - sequence: 3, - channel: WS_CHANNELS.gitActionProgress, - data: { - actionId: "action-1", - cwd: "/repo", - action: "commit", - kind: "phase_started", - phase: "commit", - label: "Committing...", - }, - }); - - if (!("type" in parsed) || parsed.type !== "push") { - assert.fail("expected websocket response to decode as a push envelope"); - } - - assert.strictEqual(parsed.channel, WS_CHANNELS.gitActionProgress); - }), -); - -it.effect("accepts server.providersUpdated push envelopes", () => - Effect.gen(function* () { - const parsed = yield* decodeWsResponse({ - type: "push", - sequence: 4, - channel: WS_CHANNELS.serverProvidersUpdated, - data: { - providers: [], - }, - }); - - if (!("type" in parsed) || parsed.type !== "push") { - assert.fail("expected websocket response to decode as a push envelope"); - } - - assert.strictEqual(parsed.channel, WS_CHANNELS.serverProvidersUpdated); - }), -); - -it.effect("rejects push envelopes when channel payload does not match the channel schema", () => - Effect.gen(function* () { - const result = yield* Effect.exit( - decodeWsResponse({ - type: "push", - sequence: 2, - channel: ORCHESTRATION_WS_CHANNELS.domainEvent, - data: { - cwd: "/tmp/workspace", - projectName: "workspace", - }, - }), - ); - - assert.strictEqual(result._tag, "Failure"); - }), -); diff --git a/packages/contracts/src/ws.ts b/packages/contracts/src/ws.ts deleted file mode 100644 index 2bcc37f7c6..0000000000 --- a/packages/contracts/src/ws.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { Schema, Struct } from "effect"; -import { NonNegativeInt, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas"; - -import { - ClientOrchestrationCommand, - OrchestrationEvent, - ORCHESTRATION_WS_CHANNELS, - OrchestrationGetFullThreadDiffInput, - ORCHESTRATION_WS_METHODS, - OrchestrationGetSnapshotInput, - OrchestrationGetTurnDiffInput, - OrchestrationReplayEventsInput, -} from "./orchestration"; -import { - GitActionProgressEvent, - GitCheckoutInput, - GitCreateBranchInput, - GitPreparePullRequestThreadInput, - GitCreateWorktreeInput, - GitInitInput, - GitListBranchesInput, - GitPullInput, - GitPullRequestRefInput, - GitRemoveWorktreeInput, - GitRunStackedActionInput, - GitStatusInput, -} from "./git"; -import { - TerminalClearInput, - TerminalCloseInput, - TerminalEvent, - TerminalOpenInput, - TerminalResizeInput, - TerminalRestartInput, - TerminalWriteInput, -} from "./terminal"; -import { KeybindingRule } from "./keybindings"; -import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project"; -import { OpenInEditorInput } from "./editor"; -import { ServerConfigUpdatedPayload, ServerProviderUpdatedPayload } from "./server"; -import { ServerSettingsPatch } from "./settings"; - -// ── WebSocket RPC Method Names ─────────────────────────────────────── - -export const WS_METHODS = { - // Project registry methods - projectsList: "projects.list", - projectsAdd: "projects.add", - projectsRemove: "projects.remove", - projectsSearchEntries: "projects.searchEntries", - projectsWriteFile: "projects.writeFile", - - // Shell methods - shellOpenInEditor: "shell.openInEditor", - - // Git methods - gitPull: "git.pull", - gitStatus: "git.status", - gitRunStackedAction: "git.runStackedAction", - gitListBranches: "git.listBranches", - gitCreateWorktree: "git.createWorktree", - gitRemoveWorktree: "git.removeWorktree", - gitCreateBranch: "git.createBranch", - gitCheckout: "git.checkout", - gitInit: "git.init", - gitResolvePullRequest: "git.resolvePullRequest", - gitPreparePullRequestThread: "git.preparePullRequestThread", - - // Terminal methods - terminalOpen: "terminal.open", - terminalWrite: "terminal.write", - terminalResize: "terminal.resize", - terminalClear: "terminal.clear", - terminalRestart: "terminal.restart", - terminalClose: "terminal.close", - - // Server meta - serverGetConfig: "server.getConfig", - serverRefreshProviders: "server.refreshProviders", - serverUpsertKeybinding: "server.upsertKeybinding", - serverGetSettings: "server.getSettings", - serverUpdateSettings: "server.updateSettings", -} as const; - -// ── Push Event Channels ────────────────────────────────────────────── - -export const WS_CHANNELS = { - gitActionProgress: "git.actionProgress", - terminalEvent: "terminal.event", - serverWelcome: "server.welcome", - serverConfigUpdated: "server.configUpdated", - serverProvidersUpdated: "server.providersUpdated", -} as const; - -// -- Tagged Union of all request body schemas ───────────────────────── - -const tagRequestBody = ( - tag: Tag, - schema: Schema.Struct, -) => - schema.mapFields( - Struct.assign({ _tag: Schema.tag(tag) }), - // PreserveChecks is safe here. No existing schema should have checks depending on the tag - { unsafePreserveChecks: true }, - ); - -const WebSocketRequestBody = Schema.Union([ - // Orchestration methods - tagRequestBody( - ORCHESTRATION_WS_METHODS.dispatchCommand, - Schema.Struct({ command: ClientOrchestrationCommand }), - ), - tagRequestBody(ORCHESTRATION_WS_METHODS.getSnapshot, OrchestrationGetSnapshotInput), - tagRequestBody(ORCHESTRATION_WS_METHODS.getTurnDiff, OrchestrationGetTurnDiffInput), - tagRequestBody(ORCHESTRATION_WS_METHODS.getFullThreadDiff, OrchestrationGetFullThreadDiffInput), - tagRequestBody(ORCHESTRATION_WS_METHODS.replayEvents, OrchestrationReplayEventsInput), - - // Project Search - tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput), - tagRequestBody(WS_METHODS.projectsWriteFile, ProjectWriteFileInput), - - // Shell methods - tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput), - - // Git methods - tagRequestBody(WS_METHODS.gitPull, GitPullInput), - tagRequestBody(WS_METHODS.gitStatus, GitStatusInput), - tagRequestBody(WS_METHODS.gitRunStackedAction, GitRunStackedActionInput), - tagRequestBody(WS_METHODS.gitListBranches, GitListBranchesInput), - tagRequestBody(WS_METHODS.gitCreateWorktree, GitCreateWorktreeInput), - tagRequestBody(WS_METHODS.gitRemoveWorktree, GitRemoveWorktreeInput), - tagRequestBody(WS_METHODS.gitCreateBranch, GitCreateBranchInput), - tagRequestBody(WS_METHODS.gitCheckout, GitCheckoutInput), - tagRequestBody(WS_METHODS.gitInit, GitInitInput), - tagRequestBody(WS_METHODS.gitResolvePullRequest, GitPullRequestRefInput), - tagRequestBody(WS_METHODS.gitPreparePullRequestThread, GitPreparePullRequestThreadInput), - - // Terminal methods - tagRequestBody(WS_METHODS.terminalOpen, TerminalOpenInput), - tagRequestBody(WS_METHODS.terminalWrite, TerminalWriteInput), - tagRequestBody(WS_METHODS.terminalResize, TerminalResizeInput), - tagRequestBody(WS_METHODS.terminalClear, TerminalClearInput), - tagRequestBody(WS_METHODS.terminalRestart, TerminalRestartInput), - tagRequestBody(WS_METHODS.terminalClose, TerminalCloseInput), - - // Server meta - tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})), - tagRequestBody(WS_METHODS.serverRefreshProviders, Schema.Struct({})), - tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule), - tagRequestBody(WS_METHODS.serverGetSettings, Schema.Struct({})), - tagRequestBody(WS_METHODS.serverUpdateSettings, Schema.Struct({ patch: ServerSettingsPatch })), -]); - -export const WebSocketRequest = Schema.Struct({ - id: TrimmedNonEmptyString, - body: WebSocketRequestBody, -}); -export type WebSocketRequest = typeof WebSocketRequest.Type; - -export const WebSocketResponse = Schema.Struct({ - id: TrimmedNonEmptyString, - result: Schema.optional(Schema.Unknown), - error: Schema.optional( - Schema.Struct({ - message: Schema.String, - }), - ), -}); -export type WebSocketResponse = typeof WebSocketResponse.Type; - -export const WsPushSequence = NonNegativeInt; -export type WsPushSequence = typeof WsPushSequence.Type; - -export const WsWelcomePayload = Schema.Struct({ - cwd: TrimmedNonEmptyString, - projectName: TrimmedNonEmptyString, - bootstrapProjectId: Schema.optional(ProjectId), - bootstrapThreadId: Schema.optional(ThreadId), -}); -export type WsWelcomePayload = typeof WsWelcomePayload.Type; - -export interface WsPushPayloadByChannel { - readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload; - readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type; - readonly [WS_CHANNELS.serverProvidersUpdated]: typeof ServerProviderUpdatedPayload.Type; - readonly [WS_CHANNELS.gitActionProgress]: typeof GitActionProgressEvent.Type; - readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type; - readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent; -} - -export type WsPushChannel = keyof WsPushPayloadByChannel; -export type WsPushData = WsPushPayloadByChannel[C]; - -const makeWsPushSchema = >( - channel: Channel, - payload: Payload, -) => - Schema.Struct({ - type: Schema.Literal("push"), - sequence: WsPushSequence, - channel: Schema.Literal(channel), - data: payload, - }); - -export const WsPushServerWelcome = makeWsPushSchema(WS_CHANNELS.serverWelcome, WsWelcomePayload); -export const WsPushServerConfigUpdated = makeWsPushSchema( - WS_CHANNELS.serverConfigUpdated, - ServerConfigUpdatedPayload, -); -export const WsPushServerProvidersUpdated = makeWsPushSchema( - WS_CHANNELS.serverProvidersUpdated, - ServerProviderUpdatedPayload, -); -export const WsPushGitActionProgress = makeWsPushSchema( - WS_CHANNELS.gitActionProgress, - GitActionProgressEvent, -); -export const WsPushTerminalEvent = makeWsPushSchema(WS_CHANNELS.terminalEvent, TerminalEvent); -export const WsPushOrchestrationDomainEvent = makeWsPushSchema( - ORCHESTRATION_WS_CHANNELS.domainEvent, - OrchestrationEvent, -); - -export const WsPushChannelSchema = Schema.Literals([ - WS_CHANNELS.gitActionProgress, - WS_CHANNELS.serverWelcome, - WS_CHANNELS.serverConfigUpdated, - WS_CHANNELS.serverProvidersUpdated, - WS_CHANNELS.terminalEvent, - ORCHESTRATION_WS_CHANNELS.domainEvent, -]); -export type WsPushChannelSchema = typeof WsPushChannelSchema.Type; - -export const WsPush = Schema.Union([ - WsPushServerWelcome, - WsPushServerConfigUpdated, - WsPushServerProvidersUpdated, - WsPushGitActionProgress, - WsPushTerminalEvent, - WsPushOrchestrationDomainEvent, -]); -export type WsPush = typeof WsPush.Type; - -export type WsPushMessage = Extract; - -export const WsPushEnvelopeBase = Schema.Struct({ - type: Schema.Literal("push"), - sequence: WsPushSequence, - channel: WsPushChannelSchema, - data: Schema.Unknown, -}); -export type WsPushEnvelopeBase = typeof WsPushEnvelopeBase.Type; - -// ── Union of all server → client messages ───────────────────────────── - -export const WsResponse = Schema.Union([WebSocketResponse, WsPush]); -export type WsResponse = typeof WsResponse.Type; diff --git a/packages/shared/package.json b/packages/shared/package.json index d34d1ce453..b35d23ef15 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -28,6 +28,10 @@ "types": "./src/DrainableWorker.ts", "import": "./src/DrainableWorker.ts" }, + "./KeyedCoalescingWorker": { + "types": "./src/KeyedCoalescingWorker.ts", + "import": "./src/KeyedCoalescingWorker.ts" + }, "./schemaJson": { "types": "./src/schemaJson.ts", "import": "./src/schemaJson.ts" @@ -35,6 +39,10 @@ "./Struct": { "types": "./src/Struct.ts", "import": "./src/Struct.ts" + }, + "./String": { + "types": "./src/String.ts", + "import": "./src/String.ts" } }, "scripts": { diff --git a/packages/shared/src/DrainableWorker.ts b/packages/shared/src/DrainableWorker.ts index 6b9ede9f45..55483f33e8 100644 --- a/packages/shared/src/DrainableWorker.ts +++ b/packages/shared/src/DrainableWorker.ts @@ -8,8 +8,8 @@ * * @module DrainableWorker */ -import { Deferred, Effect, Queue, Ref } from "effect"; import type { Scope } from "effect"; +import { Effect, TxQueue, TxRef } from "effect"; export interface DrainableWorker { /** @@ -39,63 +39,30 @@ export const makeDrainableWorker = ( process: (item: A) => Effect.Effect, ): Effect.Effect, never, Scope.Scope | R> => Effect.gen(function* () { - const queue = yield* Queue.unbounded(); - const initialIdle = yield* Deferred.make(); - yield* Deferred.succeed(initialIdle, undefined).pipe(Effect.orDie); - const state = yield* Ref.make({ - outstanding: 0, - idle: initialIdle, - }); + const queue = yield* Effect.acquireRelease(TxQueue.unbounded(), TxQueue.shutdown); + const outstanding = yield* TxRef.make(0); - yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid)); - - const finishOne = Ref.modify(state, (current) => { - const remaining = Math.max(0, current.outstanding - 1); - return [ - remaining === 0 ? current.idle : null, - { - outstanding: remaining, - idle: current.idle, - }, - ] as const; - }).pipe( - Effect.flatMap((idle) => - idle === null ? Effect.void : Deferred.succeed(idle, undefined).pipe(Effect.orDie), - ), - ); - - yield* Effect.forkScoped( - Effect.forever( - Queue.take(queue).pipe( - Effect.flatMap((item) => process(item).pipe(Effect.ensuring(finishOne))), + yield* TxQueue.take(queue).pipe( + Effect.tap((a) => + Effect.ensuring( + process(a), + TxRef.update(outstanding, (n) => n - 1), ), ), + Effect.forever, + Effect.forkScoped, ); - const enqueue: DrainableWorker["enqueue"] = (item) => - Effect.gen(function* () { - const nextIdle = yield* Deferred.make(); - yield* Ref.update(state, (current) => - current.outstanding === 0 - ? { - outstanding: 1, - idle: nextIdle, - } - : { - outstanding: current.outstanding + 1, - idle: current.idle, - }, - ); - - const accepted = yield* Queue.offer(queue, item); - if (!accepted) { - yield* finishOne; - } - }); - - const drain: DrainableWorker["drain"] = Ref.get(state).pipe( - Effect.flatMap(({ idle }) => Deferred.await(idle)), + const drain: DrainableWorker["drain"] = TxRef.get(outstanding).pipe( + Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)), + Effect.tx, ); + const enqueue = (element: A): Effect.Effect => + TxQueue.offer(queue, element).pipe( + Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)), + Effect.tx, + ); + return { enqueue, drain } satisfies DrainableWorker; }); diff --git a/packages/shared/src/KeyedCoalescingWorker.test.ts b/packages/shared/src/KeyedCoalescingWorker.test.ts new file mode 100644 index 0000000000..2226bbd003 --- /dev/null +++ b/packages/shared/src/KeyedCoalescingWorker.test.ts @@ -0,0 +1,96 @@ +import { it } from "@effect/vitest"; +import { describe, expect } from "vitest"; +import { Deferred, Effect } from "effect"; + +import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker"; + +describe("makeKeyedCoalescingWorker", () => { + it.live("waits for latest work enqueued during active processing before draining the key", () => + Effect.scoped( + Effect.gen(function* () { + const processed: string[] = []; + const firstStarted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const secondStarted = yield* Deferred.make(); + const releaseSecond = yield* Deferred.make(); + + const worker = yield* makeKeyedCoalescingWorker({ + merge: (_current, next) => next, + process: (key, value) => + Effect.gen(function* () { + processed.push(`${key}:${value}`); + + if (value === "first") { + yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseFirst); + } + + if (value === "second") { + yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseSecond); + } + }), + }); + + yield* worker.enqueue("terminal-1", "first"); + yield* Deferred.await(firstStarted); + + const drained = yield* Deferred.make(); + yield* Effect.forkChild( + worker + .drainKey("terminal-1") + .pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))), + ); + + yield* worker.enqueue("terminal-1", "second"); + yield* Deferred.succeed(releaseFirst, undefined); + yield* Deferred.await(secondStarted); + + expect(yield* Deferred.isDone(drained)).toBe(false); + + yield* Deferred.succeed(releaseSecond, undefined); + yield* Deferred.await(drained); + + expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]); + }), + ), + ); + + it.live("requeues pending work for a key after a processor failure and keeps draining", () => + Effect.scoped( + Effect.gen(function* () { + const processed: string[] = []; + const firstStarted = yield* Deferred.make(); + const releaseFailure = yield* Deferred.make(); + const secondProcessed = yield* Deferred.make(); + + const worker = yield* makeKeyedCoalescingWorker({ + merge: (_current, next) => next, + process: (key, value) => + Effect.gen(function* () { + processed.push(`${key}:${value}`); + + if (value === "first") { + yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseFailure); + yield* Effect.fail("boom"); + } + + if (value === "second") { + yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie); + } + }), + }); + + yield* worker.enqueue("terminal-1", "first"); + yield* Deferred.await(firstStarted); + yield* worker.enqueue("terminal-1", "second"); + yield* Deferred.succeed(releaseFailure, undefined); + yield* Deferred.await(secondProcessed); + yield* worker.drainKey("terminal-1"); + + expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]); + }), + ), + ); +}); diff --git a/packages/shared/src/KeyedCoalescingWorker.ts b/packages/shared/src/KeyedCoalescingWorker.ts new file mode 100644 index 0000000000..567c1dac17 --- /dev/null +++ b/packages/shared/src/KeyedCoalescingWorker.ts @@ -0,0 +1,140 @@ +/** + * KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key. + * + * Enqueues for an active or already-queued key are merged atomically instead of + * creating duplicate queued items. `drainKey()` resolves only when that key has + * no queued, pending, or active work left. + * + * @module KeyedCoalescingWorker + */ +import type { Scope } from "effect"; +import { Effect, TxQueue, TxRef } from "effect"; + +export interface KeyedCoalescingWorker { + readonly enqueue: (key: K, value: V) => Effect.Effect; + readonly drainKey: (key: K) => Effect.Effect; +} + +interface KeyedCoalescingWorkerState { + readonly latestByKey: Map; + readonly queuedKeys: Set; + readonly activeKeys: Set; +} + +export const makeKeyedCoalescingWorker = (options: { + readonly merge: (current: V, next: V) => V; + readonly process: (key: K, value: V) => Effect.Effect; +}): Effect.Effect, never, Scope.Scope | R> => + Effect.gen(function* () { + const queue = yield* Effect.acquireRelease(TxQueue.unbounded(), TxQueue.shutdown); + const stateRef = yield* TxRef.make>({ + latestByKey: new Map(), + queuedKeys: new Set(), + activeKeys: new Set(), + }); + + const processKey = (key: K, value: V): Effect.Effect => + options.process(key, value).pipe( + Effect.flatMap(() => + TxRef.modify(stateRef, (state) => { + const nextValue = state.latestByKey.get(key); + if (nextValue === undefined) { + const activeKeys = new Set(state.activeKeys); + activeKeys.delete(key); + return [null, { ...state, activeKeys }] as const; + } + + const latestByKey = new Map(state.latestByKey); + latestByKey.delete(key); + return [nextValue, { ...state, latestByKey }] as const; + }).pipe(Effect.tx), + ), + Effect.flatMap((nextValue) => + nextValue === null ? Effect.void : processKey(key, nextValue), + ), + ); + + const cleanupFailedKey = (key: K): Effect.Effect => + TxRef.modify(stateRef, (state) => { + const activeKeys = new Set(state.activeKeys); + activeKeys.delete(key); + + if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, activeKeys, queuedKeys }] as const; + } + + return [false, { ...state, activeKeys }] as const; + }).pipe( + Effect.tx, + Effect.flatMap((shouldRequeue) => + shouldRequeue ? TxQueue.offer(queue, key) : Effect.void, + ), + ); + + yield* TxQueue.take(queue).pipe( + Effect.flatMap((key) => + TxRef.modify(stateRef, (state) => { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.delete(key); + + const value = state.latestByKey.get(key); + if (value === undefined) { + return [null, { ...state, queuedKeys }] as const; + } + + const latestByKey = new Map(state.latestByKey); + latestByKey.delete(key); + const activeKeys = new Set(state.activeKeys); + activeKeys.add(key); + + return [ + { key, value } as const, + { ...state, latestByKey, queuedKeys, activeKeys }, + ] as const; + }).pipe(Effect.tx), + ), + Effect.flatMap((item) => + item === null + ? Effect.void + : processKey(item.key, item.value).pipe( + Effect.catchCause(() => cleanupFailedKey(item.key)), + ), + ), + Effect.forever, + Effect.forkScoped, + ); + + const enqueue: KeyedCoalescingWorker["enqueue"] = (key, value) => + TxRef.modify(stateRef, (state) => { + const latestByKey = new Map(state.latestByKey); + const existing = latestByKey.get(key); + latestByKey.set(key, existing === undefined ? value : options.merge(existing, value)); + + if (state.queuedKeys.has(key) || state.activeKeys.has(key)) { + return [false, { ...state, latestByKey }] as const; + } + + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, latestByKey, queuedKeys }] as const; + }).pipe( + Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)), + Effect.tx, + Effect.asVoid, + ); + + const drainKey: KeyedCoalescingWorker["drainKey"] = (key) => + TxRef.get(stateRef).pipe( + Effect.tap((state) => + state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key) + ? Effect.txRetry + : Effect.void, + ), + Effect.asVoid, + Effect.tx, + ); + + return { enqueue, drainKey } satisfies KeyedCoalescingWorker; + }); diff --git a/packages/shared/src/String.test.ts b/packages/shared/src/String.test.ts new file mode 100644 index 0000000000..d70bfe840f --- /dev/null +++ b/packages/shared/src/String.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; + +import { truncate } from "./String"; + +describe("truncate", () => { + it("trims surrounding whitespace", () => { + expect(truncate(" hello world ")).toBe("hello world"); + }); + + it("returns shorter strings unchanged", () => { + expect(truncate("alpha", 10)).toBe("alpha"); + }); + + it("truncates long strings and appends an ellipsis", () => { + expect(truncate("abcdefghij", 5)).toBe("abcde..."); + }); +}); diff --git a/apps/web/src/truncateTitle.ts b/packages/shared/src/String.ts similarity index 66% rename from apps/web/src/truncateTitle.ts rename to packages/shared/src/String.ts index bce5545283..c93d0c90cb 100644 --- a/apps/web/src/truncateTitle.ts +++ b/packages/shared/src/String.ts @@ -1,7 +1,8 @@ -export function truncateTitle(text: string, maxLength = 50): string { +export function truncate(text: string, maxLength = 50): string { const trimmed = text.trim(); if (trimmed.length <= maxLength) { return trimmed; } + return `${trimmed.slice(0, maxLength)}...`; } diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts index 31f0d0a112..232fa71188 100644 --- a/packages/shared/src/model.test.ts +++ b/packages/shared/src/model.test.ts @@ -1,16 +1,19 @@ import { describe, expect, it } from "vitest"; -import { - DEFAULT_MODEL, - DEFAULT_MODEL_BY_PROVIDER, - type ModelCapabilities, -} from "@t3tools/contracts"; +import { DEFAULT_MODEL_BY_PROVIDER, type ModelCapabilities } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, + getDefaultContextWindow, getDefaultEffort, + hasContextWindowOption, hasEffortLevel, isClaudeUltrathinkPrompt, + normalizeClaudeModelOptionsWithCapabilities, + normalizeCodexModelOptionsWithCapabilities, normalizeModelSlug, + resolveApiModelId, + resolveContextWindow, + resolveEffort, resolveModelSlug, resolveModelSlugForProvider, resolveSelectableModel, @@ -24,6 +27,7 @@ const codexCaps: ModelCapabilities = { ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }; @@ -35,6 +39,10 @@ const claudeCaps: ModelCapabilities = { ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k" }, + { value: "1m", label: "1M", isDefault: true }, + ], promptInjectedEffortLevels: ["ultrathink"], }; @@ -54,14 +62,15 @@ describe("normalizeModelSlug", () => { describe("resolveModelSlug", () => { it("returns defaults when the model is missing", () => { - expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL); + expect(resolveModelSlug(undefined, "codex")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex); + expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe( DEFAULT_MODEL_BY_PROVIDER.claudeAgent, ); }); it("preserves normalized unknown models", () => { - expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model"); + expect(resolveModelSlug("custom/internal-model", "codex")).toBe("custom/internal-model"); }); }); @@ -89,6 +98,42 @@ describe("capability helpers", () => { }); }); +describe("resolveEffort", () => { + it("returns the explicit value when supported and not prompt-injected", () => { + expect(resolveEffort(codexCaps, "xhigh")).toBe("xhigh"); + expect(resolveEffort(codexCaps, "high")).toBe("high"); + expect(resolveEffort(claudeCaps, "medium")).toBe("medium"); + }); + + it("falls back to default when value is unsupported", () => { + expect(resolveEffort(codexCaps, "bogus")).toBe("high"); + expect(resolveEffort(claudeCaps, "bogus")).toBe("high"); + }); + + it("returns the default when no value is provided", () => { + expect(resolveEffort(codexCaps, undefined)).toBe("high"); + expect(resolveEffort(codexCaps, null)).toBe("high"); + expect(resolveEffort(codexCaps, "")).toBe("high"); + expect(resolveEffort(codexCaps, " ")).toBe("high"); + }); + + it("excludes prompt-injected efforts and falls back to default", () => { + expect(resolveEffort(claudeCaps, "ultrathink")).toBe("high"); + }); + + it("returns undefined for models with no effort levels", () => { + const noCaps: ModelCapabilities = { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }; + expect(resolveEffort(noCaps, undefined)).toBeUndefined(); + expect(resolveEffort(noCaps, "high")).toBeUndefined(); + }); +}); + describe("misc helpers", () => { it("detects ultrathink prompts", () => { expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true); @@ -109,3 +154,131 @@ describe("misc helpers", () => { expect(trimOrNull(" ")).toBeNull(); }); }); + +describe("context window helpers", () => { + it("reads default context window", () => { + expect(getDefaultContextWindow(claudeCaps)).toBe("1m"); + }); + + it("returns null for models without context window options", () => { + expect(getDefaultContextWindow(codexCaps)).toBeNull(); + }); + + it("checks context window support", () => { + expect(hasContextWindowOption(claudeCaps, "1m")).toBe(true); + expect(hasContextWindowOption(claudeCaps, "200k")).toBe(true); + expect(hasContextWindowOption(claudeCaps, "bogus")).toBe(false); + expect(hasContextWindowOption(codexCaps, "1m")).toBe(false); + }); +}); + +describe("resolveContextWindow", () => { + it("returns the explicit value when supported", () => { + expect(resolveContextWindow(claudeCaps, "200k")).toBe("200k"); + expect(resolveContextWindow(claudeCaps, "1m")).toBe("1m"); + }); + + it("falls back to default when value is unsupported", () => { + expect(resolveContextWindow(claudeCaps, "bogus")).toBe("1m"); + }); + + it("returns the default when no value is provided", () => { + expect(resolveContextWindow(claudeCaps, undefined)).toBe("1m"); + expect(resolveContextWindow(claudeCaps, null)).toBe("1m"); + expect(resolveContextWindow(claudeCaps, "")).toBe("1m"); + }); + + it("returns undefined for models with no context window options", () => { + expect(resolveContextWindow(codexCaps, undefined)).toBeUndefined(); + expect(resolveContextWindow(codexCaps, "1m")).toBeUndefined(); + }); +}); + +describe("resolveApiModelId", () => { + it("appends [1m] suffix for 1m context window", () => { + expect( + resolveApiModelId({ + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { contextWindow: "1m" }, + }), + ).toBe("claude-opus-4-6[1m]"); + }); + + it("returns the model as-is for 200k context window", () => { + expect( + resolveApiModelId({ + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { contextWindow: "200k" }, + }), + ).toBe("claude-opus-4-6"); + }); + + it("returns the model as-is when no context window is set", () => { + expect(resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6" })).toBe( + "claude-opus-4-6", + ); + expect( + resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6", options: {} }), + ).toBe("claude-opus-4-6"); + }); + + it("returns the model as-is for Codex selections", () => { + expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4"); + }); +}); + +describe("normalize*ModelOptionsWithCapabilities", () => { + it("preserves explicit false codex fast mode", () => { + expect( + normalizeCodexModelOptionsWithCapabilities(codexCaps, { + reasoningEffort: "high", + fastMode: false, + }), + ).toEqual({ + reasoningEffort: "high", + fastMode: false, + }); + }); + + it("preserves the default Claude context window explicitly", () => { + expect( + normalizeClaudeModelOptionsWithCapabilities( + { + ...claudeCaps, + contextWindowOptions: [ + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, + ], + }, + { + effort: "high", + contextWindow: "200k", + }, + ), + ).toEqual({ + effort: "high", + contextWindow: "200k", + }); + }); + + it("omits unsupported Claude context window options", () => { + expect( + normalizeClaudeModelOptionsWithCapabilities( + { + ...claudeCaps, + reasoningEffortLevels: [], + supportsThinkingToggle: true, + contextWindowOptions: [], + }, + { + thinking: true, + contextWindow: "1m", + }, + ), + ).toEqual({ + thinking: true, + }); + }); +}); diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index e633aeb293..2aa378cf63 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -2,8 +2,10 @@ import { DEFAULT_MODEL_BY_PROVIDER, MODEL_SLUG_ALIASES_BY_PROVIDER, type ClaudeCodeEffort, + type ClaudeModelOptions, + type CodexModelOptions, type ModelCapabilities, - type ModelSlug, + type ModelSelection, type ProviderKind, } from "@t3tools/contracts"; @@ -12,10 +14,6 @@ export interface SelectableModelOption { name: string; } -export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug { - return DEFAULT_MODEL_BY_PROVIDER[provider]; -} - // ── Effort helpers ──────────────────────────────────────────────────── /** Check whether a capabilities object includes a given effort value. */ @@ -28,6 +26,97 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null { return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null; } +/** + * Resolve a raw effort option against capabilities. + * + * Returns the effective effort value — the explicit value if supported and not + * prompt-injected, otherwise the model's default. Returns `undefined` only + * when the model has no effort levels at all. + * + * Prompt-injected efforts (e.g. "ultrathink") are excluded because they are + * applied via prompt text, not the effort API parameter. + */ +export function resolveEffort( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const defaultValue = getDefaultEffort(caps); + const trimmed = typeof raw === "string" ? raw.trim() : null; + if ( + trimmed && + !caps.promptInjectedEffortLevels.includes(trimmed) && + hasEffortLevel(caps, trimmed) + ) { + return trimmed; + } + return defaultValue ?? undefined; +} + +// ── Context window helpers ─────────────────────────────────────────── + +/** Check whether a capabilities object includes a given context window value. */ +export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean { + return caps.contextWindowOptions.some((o) => o.value === value); +} + +/** Return the default context window value, or `null` if none is defined. */ +export function getDefaultContextWindow(caps: ModelCapabilities): string | null { + return caps.contextWindowOptions.find((o) => o.isDefault)?.value ?? null; +} + +/** + * Resolve a raw `contextWindow` option against capabilities. + * + * Returns the effective context window value — the explicit value if supported, + * otherwise the model's default. Returns `undefined` only when the model has + * no context window options at all. + * + * Unlike effort levels (where the API has matching defaults), the context + * window requires an explicit API suffix (e.g. `[1m]`), so we always preserve + * the resolved value to avoid ambiguity between "user chose the default" and + * "not specified". + */ +export function resolveContextWindow( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const defaultValue = getDefaultContextWindow(caps); + if (!raw) return defaultValue ?? undefined; + return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined); +} + +export function normalizeCodexModelOptionsWithCapabilities( + caps: ModelCapabilities, + modelOptions: CodexModelOptions | null | undefined, +): CodexModelOptions | undefined { + const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort); + const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined; + const nextOptions: CodexModelOptions = { + ...(reasoningEffort + ? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] } + : {}), + ...(fastMode !== undefined ? { fastMode } : {}), + }; + return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; +} + +export function normalizeClaudeModelOptionsWithCapabilities( + caps: ModelCapabilities, + modelOptions: ClaudeModelOptions | null | undefined, +): ClaudeModelOptions | undefined { + const effort = resolveEffort(caps, modelOptions?.effort); + const thinking = caps.supportsThinkingToggle ? modelOptions?.thinking : undefined; + const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined; + const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); + const nextOptions: ClaudeModelOptions = { + ...(thinking !== undefined ? { thinking } : {}), + ...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}), + ...(fastMode !== undefined ? { fastMode } : {}), + ...(contextWindow !== undefined ? { contextWindow } : {}), + }; + return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; +} + export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean { return typeof text === "string" && /\bultrathink\b/i.test(text); } @@ -35,7 +124,7 @@ export function isClaudeUltrathinkPrompt(text: string | null | undefined): boole export function normalizeModelSlug( model: string | null | undefined, provider: ProviderKind = "codex", -): ModelSlug | null { +): string | null { if (typeof model !== "string") { return null; } @@ -45,18 +134,18 @@ export function normalizeModelSlug( return null; } - const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record; + const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record; const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed) ? aliases[trimmed] : undefined; - return typeof aliased === "string" ? aliased : (trimmed as ModelSlug); + return typeof aliased === "string" ? aliased : trimmed; } export function resolveSelectableModel( provider: ProviderKind, value: string | null | undefined, options: ReadonlyArray, -): ModelSlug | null { +): string | null { if (typeof value !== "string") { return null; } @@ -85,10 +174,7 @@ export function resolveSelectableModel( return resolved ? resolved.slug : null; } -export function resolveModelSlug( - model: string | null | undefined, - provider: ProviderKind = "codex", -): ModelSlug { +export function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string { const normalized = normalizeModelSlug(model, provider); if (!normalized) { return DEFAULT_MODEL_BY_PROVIDER[provider]; @@ -99,7 +185,7 @@ export function resolveModelSlug( export function resolveModelSlugForProvider( provider: ProviderKind, model: string | null | undefined, -): ModelSlug { +): string { return resolveModelSlug(model, provider); } @@ -110,6 +196,33 @@ export function trimOrNull(value: T | null | undefined): T | n return trimmed || null; } +/** + * Resolve the actual API model identifier from a model selection. + * + * Provider-aware: each provider can map `contextWindow` (or other options) + * to whatever the API requires — a model-id suffix, a separate parameter, etc. + * The canonical slug stored in the selection stays unchanged so the + * capabilities system keeps working. + * + * Expects `contextWindow` to already be resolved (via `resolveContextWindow`) + * to the effective value, not stripped to `undefined` for defaults. + */ +export function resolveApiModelId(modelSelection: ModelSelection): string { + switch (modelSelection.provider) { + case "claudeAgent": { + switch (modelSelection.options?.contextWindow) { + case "1m": + return `${modelSelection.model}[1m]`; + default: + return modelSelection.model; + } + } + default: { + return modelSelection.model; + } + } +} + export function applyClaudePromptEffortPrefix( text: string, effort: ClaudeCodeEffort | null | undefined, diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index f1d60bf334..d9e8a7881b 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -10,6 +10,26 @@ type ExecFileSyncLike = ( options: { encoding: "utf8"; timeout: number }, ) => string; +export function resolveLoginShell( + platform: NodeJS.Platform, + shell: string | undefined, +): string | undefined { + const trimmedShell = shell?.trim(); + if (trimmedShell) { + return trimmedShell; + } + + if (platform === "darwin") { + return "/bin/zsh"; + } + + if (platform === "linux") { + return "/bin/bash"; + } + + return undefined; +} + export function extractPathFromShellOutput(output: string): string | null { const startIndex = output.indexOf(PATH_CAPTURE_START); if (startIndex === -1) return null; diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 0b875721fd..c0327ab4ca 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -74,6 +74,8 @@ interface BuildCliInput { readonly keepStage: Option.Option; readonly signed: Option.Option; readonly verbose: Option.Option; + readonly mockUpdates: Option.Option; + readonly mockUpdateServerPort: Option.Option; } function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined { @@ -162,6 +164,8 @@ interface ResolvedBuildOptions { readonly keepStage: boolean; readonly signed: boolean; readonly verbose: boolean; + readonly mockUpdates: boolean; + readonly mockUpdateServerPort: string | undefined; } interface StagePackageJson { @@ -204,6 +208,8 @@ const BuildEnvConfig = Config.all({ keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)), signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)), verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)), + mockUpdates: Config.boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)), + mockUpdateServerPort: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option), }); const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => @@ -231,13 +237,26 @@ const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: B const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget); const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform)); const version = mergeOptions(input.buildVersion, env.version, undefined); - const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release")); + const releaseDir = resolveBooleanFlag(input.mockUpdates, env.mockUpdates) + ? "release-mock" + : "release"; + const outputDir = path.resolve( + repoRoot, + mergeOptions(input.outputDir, env.outputDir, releaseDir), + ); const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild); const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage); const signed = resolveBooleanFlag(input.signed, env.signed); const verbose = resolveBooleanFlag(input.verbose, env.verbose); + const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates); + const mockUpdateServerPort = mergeOptions( + input.mockUpdateServerPort, + env.mockUpdateServerPort, + undefined, + ); + return { platform, target, @@ -248,6 +267,8 @@ const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: B keepStage, signed, verbose, + mockUpdates, + mockUpdateServerPort, } satisfies ResolvedBuildOptions; }); @@ -447,6 +468,8 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( target: string, productName: string, signed: boolean, + mockUpdates: boolean, + mockUpdateServerPort: string | undefined, ) { const buildConfig: Record = { appId: "com.t3tools.t3code", @@ -459,6 +482,13 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( const publishConfig = resolveGitHubPublishConfig(); if (publishConfig) { buildConfig.publish = [publishConfig]; + } else if (mockUpdates) { + buildConfig.publish = [ + { + provider: "generic", + url: `http://localhost:${mockUpdateServerPort ?? 3000}`, + }, + ]; } if (platform === "mac") { @@ -472,8 +502,14 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( if (platform === "linux") { buildConfig.linux = { target: [target], + executableName: "t3code", icon: "icon.png", category: "Development", + desktop: { + entry: { + StartupWMClass: "t3code", + }, + }, }; } @@ -618,7 +654,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ( yield* fs.copy(stageResourcesDir, path.join(stageAppDir, "apps/desktop/prod-resources")); const stagePackageJson: StagePackageJson = { - name: "t3-code-desktop", + name: "t3code", version: appVersion, buildVersion: appVersion, t3codeCommitHash: commitHash, @@ -631,6 +667,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ( options.target, desktopPackageJson.productName ?? "T3 Code", options.signed, + options.mockUpdates, + options.mockUpdateServerPort, ), dependencies: { ...resolvedServerDependencies, @@ -769,6 +807,14 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", { Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."), Flag.optional, ), + mockUpdates: Flag.boolean("mock-updates").pipe( + Flag.withDescription("Enable mock updates (env: T3CODE_DESKTOP_MOCK_UPDATES)."), + Flag.optional, + ), + mockUpdateServerPort: Flag.string("mock-update-server-port").pipe( + Flag.withDescription("Mock update server port (env: T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT)."), + Flag.optional, + ), }).pipe( Command.withDescription("Build a desktop artifact for T3 Code."), Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)), diff --git a/scripts/mock-update-server.ts b/scripts/mock-update-server.ts new file mode 100644 index 0000000000..57dab49ffa --- /dev/null +++ b/scripts/mock-update-server.ts @@ -0,0 +1,44 @@ +import { resolve, relative } from "node:path"; +import { realpathSync } from "node:fs"; + +const port = Number(process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000); +const root = + process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT ?? + resolve(import.meta.dirname, "..", "release-mock"); + +const mockServerLog = (level: "info" | "warn" | "error" = "info", message: string) => { + console[level](`[mock-update-server] ${message}`); +}; + +function isWithinRoot(filePath: string): boolean { + try { + return !relative(realpathSync(root), realpathSync(filePath)).startsWith("."); + } catch (error) { + mockServerLog("error", `Error checking if file is within root: ${error}`); + return false; + } +} + +Bun.serve({ + port, + hostname: "localhost", + fetch: async (request) => { + const url = new URL(request.url); + const path = url.pathname; + mockServerLog("info", `Request received for path: ${path}`); + const filePath = resolve(root, `.${path}`); + if (!isWithinRoot(filePath)) { + mockServerLog("warn", `Attempted to access file outside of root: ${filePath}`); + return new Response("Not Found", { status: 404 }); + } + const file = Bun.file(filePath); + if (!(await file.exists())) { + mockServerLog("warn", `Attempted to access non-existent file: ${filePath}`); + return new Response("Not Found", { status: 404 }); + } + mockServerLog("info", `Serving file: ${filePath}`); + return new Response(file.stream()); + }, +}); + +mockServerLog("info", `running on http://localhost:${port}`);